2016-08-08 69 views
1

我不確定我瞭解ajax如何工作,即使我閱讀了大量的內容。 我想,如果一個按鈕被點擊,無需加載頁面運行下面的PHP:將變量傳遞給使用AJAX的php腳本

unset($checkout_fields['billing']['billing_postcode']); 

所以我把以下內容:

jQuery(document).ready(function($) { 
    $('.keep-buying-wrapper').click(function(){ 

     $.ajax({ 
      url: "url-to-the-script.php", 
      method: "POST", 
      data: {'checked': checked}, 
      success: alert('success!'), 

     }); 
    }); 
}); 

而且在我的PHP腳本:

if($_POST['checked'] == 'checked'){ 
     unset($checkout_fields['billing']['billing_postcode']); 
} 

然而沒有發生。即使成功警報彈出,POST['checked']爲空。

ajax是否設法觸發php腳本?
如果我想發送一些變量到functions.php怎麼辦?

+2

'data:{'checked':'checked'}' – Saurabh

+1

checked是一個變量.. – Avishay28

+0

您正在文件運行時運行AJAX,而不是使用'click'事件 – Saurabh

回答

3

問題是你需要先將帖子數據序列化爲

HTML代碼(ID和複選框的名稱爲"billing_postcode"):

<input type = "checkbox" id = "billing_postcode" name = "billing_postcode"> 

JS代碼

$(document).on('click', '#billing_postcode', function (event) { 

    var data = $("#billing_postcode").serializeArray(); 
    $.ajax({ 
     url: "url-to-the-script.php", 
     method: "POST", 
     data: data, 
     success: alert('success!'), 
    }) 
}); 

您將獲得在服務器端和enter code here在後數組值php腳本

if($_POST['billing_postcode']) 
    unset($checkout_fields['billing']['billing_postcode']);