How to process ajax requests correctly using ajax plugins

tl;dr

Both ways are okay, as long as you die() your AJAX-function somehow.

I take it for granted that you handle the security well – this is important for both methods.

The Long Tail

It actually does not really matter which approach you use, and it depends a great deal on what your AJAX-Request does.

The most important thing is that you use a function that does the die() for you, or you put it directly in your AJAX function.

There are two scenarios I can think of on top of my head:

Simple Content Request

You do a simple content request (loading an image for example): in this case you could echo the response directly in your AJAX function, so you can just insert the HTML after your AJAX-call.

If you output <img src="http://url.com/test.jpg" /> in AJAX, you can just use it like that:

success: function(data) {
    $('#targetcontainer').html(data);
}

Do not forget to put the die() in your AJAX function!

Complex/Multiple Results

On the other hand, if you got multiple results or structured data in your callback, the better way would be to use wp_send_json( $results ).

The first reason is that you can pass an array or an object directly to the function, without having to handle the encoding and structuring.

The second reason is the way you can process the data in your success-function.

Examples for this would be loading new posts, automatically refreshing a few parts of your site (like a live score), and stuff like that.

Leave a Comment