简体   繁体   中英

Pass variable to php script with AJAX

I'm not sure I understand how ajax works even though I read a lot about it. I want to run the following php if a button is clicked, without loading the page:

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

So I put the following:

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

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

        });
    });
});

And in my php script:

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

However nothing happen. even though the success alert is popping, POST['checked'] is null.

Is the ajax supposes to trigger the php script?
What if I want to send some variable to functions.php ?

The problem is that you need to serialize post data first .

HTML code (The id and name of checkbox is "billing_postcode" ):

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

JS Code

$(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!'),
    })
});

You will get value in post array on server side and enter code here in php script :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM