2015-10-02 46 views
0

我最近一直試圖從jQuery的ajax函數獲取php的信息發送請求工作正常,但接收信息沒有。我將不勝感激這項援助。PHP post請求數據檢索使用jquery AJAX

的Jquery:

$.ajax({      
    url: 'sendEmail.php',  
    type: 'post', // performing a POST request 
    data: values, 
    dataType: 'json',     
    success: function(result)   
    { 
    console.log("check");//code does not come here 
    if(result=="Success"){ 
     alert("Your message has been sent. I will get in touch with you soon"); 
    } 
    else{ 
     alert("Umm.. The meesage was not sent :(. You can still contact me on [email protected]"); 
    } 

    } 
}); 

的PHP:

<?php 
    $recipient = '[email protected]'; 
    $subject = "Portfolio Message"; 
    $fromName = stripslashes($_POST['Name']); 
    $fromEmail= stripcslashes($_POST['Email']); 
    $msg = "Message from: $fromMessage\nEmail: $fromEmail\n\n".stripslashes($_POST['Message']); 



    if (mail($recipient, $subject, $msg)){ 
     echo "Success"; 
    } 
    else { 
     echo "Fail"; 
    } 
?> 
+0

的響應,因爲你發送回類型不是JSON嘗試回波這樣'回聲json_encode(陣列( 「錯誤」 =>假, 'message'=>「成功」 ));'並且在你的連續數據中獲得數據作爲'result.message' – guradio

+0

或者如果你想要的話,你可以改變'dataType'到'text' – guradio

回答

1

問題:

響應類型沒有阿賈克斯

預計具體的數據類型

匹配爲了解決你有兩個選擇:

  1. 您的dataType更改爲文本
  2. 發回適當的json響應

任兩個都可以解決發送JSON的您的問題的例子是編碼在json_encode

1
dataType: 'json', 

需要從PHP一個JSON應答,在你的PHP代碼添加標題。

<?php 
    header('Content-Type: application/json'); 
    $recipient = '[email protected]'; 
    $subject = "Portfolio Message"; 
    $fromName = stripslashes($_POST['Name']); 
    $fromEmail= stripcslashes($_POST['Email']); 
    $msg = "Message from: $fromMessage\nEmail: $fromEmail\n\n".stripslashes($_POST['Message']); 

    if (mail($recipient, $subject, $msg)){ 
     echo json_encode("Success"); 
    } 
    else { 
     echo json_encode("Fail"); 
    } 
?>