Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

share|improve this question
add comment

2 Answers

up vote 0 down vote accepted

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 :)

share|improve this answer
    
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 Jul 21 '12 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 Jul 21 '12 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 :) –  TheDeadMedic Jul 21 '12 at 23:08
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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