9

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.

0

1 Answer 1

15

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.

1
  • Sorry, my WordPress escapes the input, when it is json_encoded. Some slashes are added infront of " characters. wpartisan.me/tutorials/… Commented Jul 21, 2018 at 0:41

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.