I’ve been stuck on this topic for a while. I followed Pippin’s tutorial . According to a 2nd wordpress developer who I got advice from, this tutorial is now out of date/ not appropriate.
He told me that I shouldn’t echo
things in the AJAX callback.
JavaScript should handle that. Also to send data in your callback, use wp_send_json()
or the higher level functions wp_send_json_success()
and wp_send_json_error()
. All of them will die
for you. No need to exit
or die
afterward, like Pippin has done it in his tutorial.
Which developer is correct? In the Codex, the example uses echo
in the callback, just like Pippin has in his tutorial.
Please can someone clarify? I’ve been getting conflicting advice & I’m confused by this topic.
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="https://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.