0

Ajax Helper Functions in WordPress 3.5

On December 11, 2012, WordPress team has released latest version 3.5 with some cool new features. Amongst them WordPress has also introduced some new functions, among those functions there are three brand new Ajax related functions too and these are wp_send_json, wp_send_json_success and wp_send_json_error. These functions would be very useful when dealing with Ajax requests.

Function : wp_send_json( $response )
Description : This function takes one parameter usually an array or object and encodes it as JSON and sends the response back to an Ajax request.
Example :

Function : wp_send_json_success( $response )
Description : This function takes one parameter usually an array or object (optional) and encodes it as JSON and sends the response back to an Ajax request bur it also adds 'success' => true before the encoding process and then encodes (using wp_send_json function) and sends the response back. If there is no data to send back to the client then it sends only {"success":true} as response.
Example :

The third function is wp_send_json_error( $response ) which is just opposite to the wp_send_json_success and I’ve already used it in the previous example. It adds array( 'success' => false ) with the response and encodes and sends the response back to the client and if there is no response then it sends only array( 'success' => false ) as JSON. In the client script (Ajax success handler) return response.success will return false value.

In WordPress, developers have to use die() or exit at the end of the Ajax handler script to terminate the execution but when using these functions, there is no need to use die() or exit manually because these functions take care of it.

Latest Blog

0

New Union Type in PHP – 8

A new RFC has been finished voting and accepted for PHP – 8. That is “Union Types”, which is an extension of PHP’s type system. […]