I have the following js to process an ajax request:
$('#someelement').click(function() {
var cokeValue="coke";
var data = {
action: 'load_post',
another_par: someVar
};
jQuery.post(ajax_object.ajax_url, data, function(response) {
alert(response);
});
});
And this is my ajax handler function (hopefully my terminology is correct):
add_action('wp_ajax_get_coke', 'get_coke_ajax');
function get_coke_ajax() {
// need to get another_par in here !!!!!!!
die();
}
As you can see, the action is load_post
which is fine, but I need to pass the another_par
parameter to my ajax function so that I can assign its value to a variable and use it for my purposes.
1
When you use jQuery.post()
, the data
is sent as regular $_POST
arguments.
So this JavaScript …
var data = {
action: 'load_post',
foo: 'bar'
};
… is available in your callback function per:
$action = $_POST['action'];
$foo = $_POST['foo']; // bar
And when you are using jQuery.get()
, the data is in $_GET
. You can also use $_REQUEST
which returns both, GET
and POST
data (and COOKIE
). But you should always ask for the specific resource to avoid injection from sources you didn’t expect, like a cookie.