[wp-hackers] AJAX Hooks and JSON String

Mike Schinkel mikeschinkel at newclarity.net
Sat Sep 24 18:48:59 UTC 2011


Hi James,

You are over-thinking this.  

Here[1] is a quick code snippet you can drop in your theme's functions.php file that will show you how to send arrays of Javascript objects via AJAX to PHP in WordPress.

Hope this helps.

-Mike
[1] http://pastie.org/2585510


On Sep 24, 2011, at 11:59 AM, James Kirsop wrote:

> Hi All,
> I'm currently in the process of writing my own theme with a custom
> management page for some of the features on the front end. As a challenge to
> myself, I've been hoping to process all the form data I've got via AJAX - to
> avoid page reloads, and to learn more about how WP handles AJAX requests
> etc.
> 
> At the moment, I'm serialising an array of javascript objects
> using JSON.stringify() to result in a string that looks like the following
> (using a bunch of test data for the moment):
> [{"link":"Test 1","title":"Test 1","text":"Test
> 1","image_url":""},{"link":"Test 2","title":"Test 2","text":"Test
> 2","image_url":""},{"link":"Test 3","title":"Test 3","text":"Test
> 3","image_url":""},{"link":"Test 4","title":"Test 4","text":"Test
> 4","image_url":""}]
> Basically, 4 objects, with 4 values in each, but the idea is to have the
> number of objects increase/decrease as needed. I realise that there's built
> in functionality for handling form data in JQuery, but I'd like to be able
> to iterate over the objects to build the data I want to store as an option
> (using update_option()).
> 
> The method described in the codex [1] for processing AJAX requests and
> adding hooks, seems to require a single object of data, with an 'action'
> variable with a value to point wordpress to the correct hook and hence PHP
> function, alongside the rest of the data. I'm currently struggling to work
> out how to add the 'action' and a corresponding value into my JSON string,
> have WP find that data, take it, and then execute the appropriate function.
> I've posted [2] the javascript that's creating the array with objects, that
> then go to the JSON string for people to take a look at.
> 
> Thanks!
> James
> 
> [1] http://codex.wordpress.org/AJAX_in_Plugins
> [2] http://pastie.org/2584753
> _______________________________________________
> wp-hackers mailing list
> wp-hackers at lists.automattic.com
> http://lists.automattic.com/mailman/listinfo/wp-hackers



More information about the wp-hackers mailing list