0

When making an AJAX request is works when my data is a URL style string.

var options = {
    type: 'post',
    data: 'action=my_action'
};

The function will get called and return some fake data just fine.

If I try to make the same call but use JSON, it doesn't work. I've tried several different ways of doing it, but admin.php just return -1.

Is there something in jQuery or Wordpress that I need to change to allow this?

Here are a couple of the other ways I've tried.

var options = {
    type: 'post',
    data: { action: 'my_action' }
};

var options = {
    type: 'post',
    data: JSON.stringify({ action: 'my_action' })
};

The example in the docs have it using a JSON object too. http://codex.wordpress.org/AJAX_in_Plugins

2 Answers 2

0

Firstly, stringify won't build a URL query - it serializes it into JSON object notation.

And secondly, you don't even need to build the URL query - if you're using jQuery to make the AJAX call, just pass the JSON object as it is - jQuery.param() will internally handle it :)

3
  • I'm using Backbone.js and it's messing with it a little by sending it as application/json and a json string. Does Wordpress/PHP not handle that type of input? If not, I can make it use jQuery.param(). Using straight jQuery, the first "non-working" example would actually work because it gets converted, but the second one doesn't.
    – Josh Close
    Commented Jul 21, 2012 at 22:23
  • using jQuery.param() makes everything work just fine. Can you confirm that Wordpress/PHP won't accept JSON formatted data?
    – Josh Close
    Commented Jul 21, 2012 at 22:54
  • WP/PHP has no problem handling JSON - I think you better post a little more code, perhaps the script that actually makes the AJAX call & the PHP that handles it :) Commented Jul 21, 2012 at 23:08
1

Ignore this reply if you're not copying the bad practice examples provided in the wordpress codex.

If you are, I'd recommend reading this article on properly (and securely) using Ajax in WP: http://www.garyc40.com/2010/03/5-tips-for-using-ajax-in-wordpress/

That article is actually also linked on the codex page, so I'm left wondering why the examples on the codex page are still written as they are.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.