March 2, 2012

PHP mail function interrupting jquery .post return data

Question by SPI

I don’t really understand what’s going on here. I have a jquery script that sends form post data to a signup script, where upon an email is sent to the user signing up and the users Id is returned back to the calling jquery function where it is forwarded to yet another script for processing.

Problem: The script works great if I leave out the mail function, however, introducing it into the script blocks the variable from being returned to the calling jquery function. Any ideas what’s going on? Here is the Jquery script:

<script>
/* attach a submit handler to the form */
$("#purchaseForm").submit(function(event) {

    var intRegex = /^d+$/;


/* stop form from submitting normally */
event.preventDefault(); 


    $.post("process_signup.php", $("#purchaseForm").serialize(),function(data){
                                                if(intRegex.test(data)){
                    if(data!=0){
                        alert(data);
                    document.getElementById("bag_contents_hidden").value=data;  
                    $.post("process_order.php", $("#bag_contents").serialize(), function(data2){
                    if(data2){
                    window.location.replace("?process=100&success=1");  
                    }else{
                    window.location.replace("?process=100&fail=1"); 
                    }
                });

            }
        }

else{       //Not Important, validation stuff       


}



        });

  });

//

PHP 
                      if($oid){
               if(mail($email,$title,$message,$headers,'O DeliveryMode=b')){

                    echo $oid;
                    unset($_POST['processorder_hidden']);
                    }else{
                    echo 0; 
                          }
                }

Answer by Starx

Since you are expecting a data from the post request any errors generated by mail function is sure to create problems.

Here is a correct way to solve it

$status = @mail($to, $subject, $content); //suppress the error generated from being passed to the view

//instead handle it later
if($status) {
   //handle success
} else {
  //handle unsuccess
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!