1

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?

4
  • 2
    data: {'checked': 'checked'} Commented Aug 8, 2016 at 10:27
  • 1
    checked is a variable.. Commented Aug 8, 2016 at 10:27
  • You are running AJAX on document ready, instead use click event Commented Aug 8, 2016 at 10:28
  • check for any error in console. are you getting any specific error? Commented Aug 8, 2016 at 10:36

1 Answer 1

3

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']);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.