2012-05-14 72 views
1

这是我第一次使用ajax。我只是想将变量传递给一个使用ajax发送电子邮件的php处理脚本。但是,我没有得到从PHP脚本发送回AJAX说它是成功的东西,即使它是成功的,我要求它返回0或1为什么我的脚本没有为我的ajax函数返回一个值?

我的AJAX是:

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.');    
     }  
     }); 

我的PHP是:

$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); 

回答

4

相反的return,使用echo拿回来给你的脚本:

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

可以缩短也喜欢:

echo $result ? 1 : 0; 
+0

+1打我8秒。 –

+0

@火箭︰刚喝咖啡:) – Sarfraz

+0

只是在这里添加一个问题,我可以添加一条消息返回到ajax函数,即返回1或0,如果它是0也返回一个字符串作为$字符串? – Nicola

3

你不return,使用AJAX时。您需要echo的值。

if ($result) echo 1; 
else echo 0; 
相关问题