2012-01-31 107 views
1

我有一個簡單的註冊郵件列表表單。它將用戶的電子郵件地址發送到store-address.php文件。我使用jQuery的ajax對象向php文件發送請求,然後接收響應。即使PHP文件設置正確也沒有Ajax響應

問題是我沒有得到從PHP文件的響應。我試圖在請求中將緩存設置爲false。我也試圖通過URL發送的信息,像這樣:

http://www.fifthtribe.com/inc/store-address.php?ajax=true&cache=false&email=test4%40gmail.com

當我這樣做的工作原理,並給了我一個效應初探。但是當我通過ajax來做時,它並沒有給我一個迴應。這是螢火蟲:

enter image description here

enter image description here

enter image description here

下面是從我的代碼片段:

HTML:

<div id="mlist"> 
<form id="mlist_form" method="POST" action=""> 
    <input type="text" id="email" name="email" placeholder="Email" /> 
    <input type="submit" id="submit_btn" value="Join" /> 
</form> 
<div id="response"></div> 
</div> 

JQuery的:

/* Add to mailing list */   
$("#mlist_form").submit(function(e){ 
    //$('#response').append('<div id="thanks-mce"><div id="mce-arrow"></div>Thanks for signing up!</div>'); 
    var email = escape($('#email').val()); 
    e.preventDefault(); 

    data = { 
     "ajax" : "true", 
     "email" : email, 
     "cache" : "false" 
} 

    $.ajax({ 
      type: "POST",   
      url: 'inc/store-address.php', 
      data: data, 
      success: function(msg){ 
       // successfully signed up 
       $('#response').html(msg); 
       $('#email').val(''); 
      }, 
      error: function(err){ 
       // error while signing up 
       $('#response').html('Error: Is your email correct?'); 
      } 
    }); 

    return false; 

}); 

PHP: 功能storeAddress(){

// Validation 
    if(!$_GET['email']){ return "No email address provided"; } 

    if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$/i", $_GET['email'])) { 
     return "Email address is invalid"; 
    } 

    require_once('MCAPI.class.php'); 
    // grab an API Key from http://admin.mailchimp.com/account/api/ 
    $api = new MCAPI('xxxxxxxxxxxxxxxxxxxxxxxxxxxxx-us4'); 

    // grab your List's Unique Id by going to http://admin.mailchimp.com/lists/ 
    // Click the "settings" link for the list - the Unique Id is at the bottom of that page. 
    $list_id = "xxxxxxxx"; 

    if($api->listSubscribe($list_id, $_GET['email'], '') === true) { 
     // It worked! 
     return 'Success! Check your email to confirm sign up.'; 
    }else{ 
      // An error ocurred, return error message 
      return 'Error: ' . $api->errorMessage; 
    } 

} 

    // If being called via ajax, autorun the function 
    if($_GET['ajax']){ echo storeAddress(); } 
?> 
+1

在php代碼中試試'print_r($ _ REQUEST);'並確保你的數據在那裏 – 2012-01-31 17:55:57

回答

4

你意識到你的PHP腳本使用的是GET方法,但你的jQuery代碼使用的是POST方法嗎?

如果信息發佈到PHP,PHP將需要使用$_POST來檢索它。這解釋了爲什麼使用$_GET的URL方法有效,但jQuery POST沒有。

祝你好運!

+0

謝謝。我知道它一定是我忽視的東西。它總是有助於獲得第二雙眼睛。 – 2012-01-31 17:58:25

2

看起來你正在使用$ _GET代替$ _POST。嘗試回顯$ _REQUEST的內容以查看所持有的內容。

1

調試你的腳本!

在腳本的成功和錯誤部分放置提醒,然後您將知道AJAX是否正常工作。

如果不是,那麼您可以按照文檔的方式查看問題所在。

另外,這裏的錯誤很簡單。您在PHP中使用$ _GET,並且您使用AJAX發佈數據,這不會顯示錯誤。儘管PHP文檔不會處理您的請求,因爲它沒有被提供任何參數。

相關問題