Reputation: 2456
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
?
Upvotes: 1
Views: 1776
Reputation: 126
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']);
Upvotes: 3