0
Php

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 :

jQuery(document).ready(function(){
    jQuery('#send').on('click', function(){
        var data = { action: 'MyAjaxFunction', userId: 5 };
        jQuery.post(ajaxurl, data, function(response) {
            alert(response.user_email); // "example@yahoo.com"
        });
    });
});
function MyAjaxFunction()
{
    // More code here...

    $response = array(
        'id' => 1,
        'user_email' => 'example@yahoo.com'
    );
    

    // or get a row as object from database and send back as JSON
    
    $query = "SELECT * FROM $wpdb->users WHERE ID = $_POST['id']";
    $response = $wpdb->get_row($query);
    
    wp_send_json($response); // encode to JSON and send response
}
add_action( 'wp_ajax_nopriv_ MyAjaxFunction', 'MyAjaxFunction' );  
add_action( 'wp_ajax_ MyAjaxFunction', 'MyAjaxFunction' );

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 :

jQuery(document).ready(function(){
    jQuery('#send').on('click', function(){
        var data = { action: 'MyAjaxFunction', userId: 5 };
        jQuery.post(ajaxurl, data, function(response) {
            if(response.success)
            {
                alert('User already exists!');
            }
        });
    });
});
function MyAjaxFunction()
{
    // More code here...
    $query = "SELECT * FROM $wpdb->users WHERE ID = $_POST['id']";
    $response = $wpdb->get_row($query);
    if($response != null)
    {
        wp_send_json_success($response); // encode and send response
    }
    else wp_send_json_error(); // {"success":false}
}
add_action( 'wp_ajax_nopriv_ MyAjaxFunction', 'MyAjaxFunction' );  
add_action( 'wp_ajax_ MyAjaxFunction', 'MyAjaxFunction' );

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
Php

PHP – 8.0 Match Expression

In PHP 8.0 there is a new feature or I should say a new language construct (keyword) going to be introduced,  which has been implemented depending […]

0
Php

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. […]