简体   繁体   中英

Why isn't my script returning a value to my ajax function?

It's the first time I have used ajax. I am simply wanting to pass variables to a php processing script that sends an email out, using ajax. However, I am not getting anything sent back from the php script to the ajax to say it has been successful, even though it is successful and I ask it to return 0 or 1.

My ajax is:

jQuery.ajax({
        //this is the php file that processes the data and send mail
        url: "process.php", 

        //GET method is used
        type: "GET",

        //pass the data         
        data: dataString,     

        //Do not cache the page
        cache: false,

        //success
        success: function (html) {    

        alert(html);

            //if process.php returned 1/true (send mail success)
            if (html==1) {                  
              //hide the form
              jQuery('.form').fadeOut('slow');                 

              //show the success message
              jQuery('.done').fadeIn('slow');

            //if process.php returned 0/false (send mail failed)
            } else alert('Sorry, unexpected error. Please try again later.');               
        }       
      });

My php is:

$username=htmlspecialchars(stripslashes($_GET['username']));
    $telnumber=htmlspecialchars(stripslashes($_GET['telnumber']));
    $email=htmlspecialchars(stripslashes($_GET['email']));
    $numberparty=htmlspecialchars(stripslashes($_GET['numberparty']));
    $message=htmlspecialchars(stripslashes($_GET['message']));
    $to=//myemail address;

    $workshopName=htmlspecialchars(stripslashes($_GET['workshopName']));

    $subject='Booking request for: '.$workshopName;

    $body= "<ul><li>Name:  ".$username."</li>";
    $body.="<li>Email:  ".$email."</li>";
    $body.="<li>Telephone Number:  ".$telnumber."</li>";
    $body.="<li>Number in party:  ".$numberparty."</li>";

    if(!empty($message)){
        $body.="<li>Message:  ".$message."</li>";
    }
    $body.="</ul>";

    function sendmail($to, $subject, $message, $from) {
            $headers = "MIME-Version: 1.0" . "\r\n";
            $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
            $headers .= 'From: ' . $from . "\r\n";

            $result = mail($to,$subject,$message,$headers);


            if ($result) return 1;
            else return 0;
    }


    $result = sendmail($to, $subject, $body, $email);

Instead of return , use echo to get it back to your script:

if ($result) echo 1;
else echo 0;

You can shorten that also like:

echo $result ? 1 : 0;

You don't return , when using AJAX. You need to echo the values.

if ($result) echo 1;
else echo 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM