使用AJAX将变量传递给php脚本

时间:2016-08-08 10:26:08

标签: javascript php ajax wordpress woocommerce

我不确定我是否理解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

,该怎么办?

1 个答案:

答案 0 :(得分: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!'),
    })
});

您将获得服务器端的post数组和 php脚本中的enter code here的价值:

if($_POST['billing_postcode'])
    unset($checkout_fields['billing']['billing_postcode']);
相关问题