Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Everything You Wanted To Know About Handling AJAX In WordPress

Over the recent years, AJAX(Asynchronous Javascript and XML) has become one of the most powerful and robust technology for building dynamic, responsive and utmost user-friendly websites. One of the greatest advantages associated with this technology is that it allows you to update the web page contents without the need for reloading the page in your browser.  The very popular Google Docs is already utilizing Ajax in order to save your work every few seconds/minutes. Likewise, when it comes to using AJAX in WordPress, a multitude of options are available for your use. Through this post, I’ll be introducing you to some of the most simple ones which aid you in handling AJAX in WordPress, in the most efficient way.

Getting Started

As the initial step, you’ll require a plugin which can be named as AH_Shortcode_AJAX_Handler. Next, you’ll require two separate methods in the class viz: one for hooking into WordPress and other one for handling AJAX. The code snippet associated with the same is shown below:

<?php
/*
Plugin Name: AJAX Handling
Description: Everything you wanted to know about handling AJAX in WordPress
*/
class AH_Shortcode_Ajax_Handler {
function hooks(){
}
function ah_ajax(){
}
}
$ajax_handling_plugin = new AH_Shortcode_Ajax_Handler();
$ajax_handling_plugin->hooks();

Now that you have a plugin, you’ll need to get WordPress in action. For this, simply create a JS file which will be handling the AJAX and also queuing it up. Create a folder called “js” in the plugin and name the JS file exactly same as the plugin: ajaxhandling.js. In this tutorial, I’ve used jQuery for this as shown below:

window.ajaxhandling = ( function( window, document, $ ){
var
app = {};
app.cache = function(){/*== Cache function ==*/
};

app.init = function(){/*== Initialize function ==*/
app.cache();
};

app.post_ajax = function(){/*== Post function ==*/
};

app.ajax_response = function(){/*== Response function ==*/
};

app.form_handler = function(){/*== Form handler function ==*/
};

$(document).ready( app.init );/* start from here */

return app;
})( window, document, jQuery );

In the above code:

  • cache– this is the method which holds the selectors, saving you from having to re-access the selectors repetitively.
  • init– this is the method where initialization will take place
  • form_handler– this will be a background post where the usual form processing would be stopped for whatever you want to do
  • post_ajax– this is where you’ll be posting to PHP file and receive the data.
  • ajax_response– serving as a sibling to post_ajax, this will be utilized for handling response from AJAX.

Adding hooks in your WordPress blog

Firstly, you need to hook into the blog’s front-end and later queue up the JS file that has been created(as explained above). Plus, you’ll also be required to set up certain localized things to inform the scripts about the activity it needs to perform. The code snippet for this is shown below:

<?php
/*
Plugin Name: AJAX Handling
Description: Everything you wanted to know about handling AJAX in WordPress
*/

class AH_Shortcode_Ajax_Handler {
function hooks(){
add_action( ‘wp_ajax_ajaxhandling‘, array( $this, ‘ah_ajax‘ ) );
add_action( ‘wp_ajax_nopriv_ajaxhandling‘, array( $this, ‘ah_ajax‘ ) );
add_action( ‘wp_enqueue_scripts‘, array( $this, ‘enqueue_scripts‘ ) );
add_shortcode( ‘ajaxhandling_tut‘, array( $this, ‘shortcode_output‘ ) );
}

function ah_ajax(){

}

function enqueue_scripts(){
wp_enqueue_script( ‘ajaxhandling_js‘, plugins_url( ‘/js/ajaxhandling.js‘, __FILE__ ), array( ‘jquery‘ ), ‘1.0’, true );
wp_localize_script( ‘ajaxhandling_js‘, ‘ajaxhandling’, array(
ajax_url‘ => admin_url( ‘admin-ajax.php‘ ),
nonce‘       => wp_create_nonce( ‘ajaxhandling‘ ),
) );
}

function shortcode_output( $atts ){
$output  = ‘<form action=”” method=”POST” class=”ajax_form”>‘;
$output .= ‘    <input type=”text” name=”ajax_field”>‘;
$output .= ‘    <input type=”submit” value=”submit”>‘;
$output .= ‘</form>‘;

return $output;
}
}

$ajax_handling_plugin = new AH_Shortcode_Ajax_Handler();$ajax_handling_plugin->hooks();

With the above code, you’ve actually localized the script, gaining access to object properties from within the JS file. Both wp_ajax_ and wp_ajax_nopriv_allow you to make AJAX calls while being logged in and logged out.

Using Javascript for processing forms

When its about processing forms, nothing can beat Javascript. Here is the Javascript associated with processing forms:

window.ajaxhandling = ( function( window, document, $ ){
var
app = {};

app.cache = function(){/*== Cache function ==*/
app.$ajax_form = $( .ajax_form);
};

app.init = function(){/*== Initialize function ==*/
app.cache();
app.$ajax_form.on( submit‘, app.form_handler );
};

app.post_ajax = function( serial_data ){/*== Post function ==*/
var post_data = {
action     : ‘ajaxhandling‘,
nonce      : ajaxhandling.nonce,
serialized : serial_data,
};

$.post( ajaxhandling.ajax_url, post_data, app.ajax_response, ‘json)
}
;

app.ajax_response = function( response_data ){/*== Response function ==*/
};

app.form_handler = function( evt ){/*== Form handler function ==*/
evt.preventDefault();
var serialized_data = app.$ajax_form.serialize();
app.post_ajax( serialized_data );
};

$(document).ready( app.init );/* start from here */

return app;
})( window, document, jQuery );

In the above code:

  • cache– this is the cache method that holds the jQuery objects. Here, it is holding AJAX form which is later accessed in init method.
  • init– this initialized cache and registers handler for form’s submission
  • post_ajax– this is where the posting takes place.
  • ajax_response– this won’t be filled up unless PHP script is being informed about the data that needs to be sent back.
  • form_handler– this will be fired from app.init method when the AJAX form is being submitted.

Handling AJAX in PHP

This is the structure of the handle_ajax method which will be utilized for sending json data back to the AJAX request along with appropriate status:

function ah_ajax(){
if( ! wp_verify_nonce( $_REQUEST [‘nonce’], ‘ajaxhandling’ ) )
{
/*== Verify condition ==*/
wp_send_json_error();
}

wp_send_json_success( array(
/*== Success condition ==*/
script_response‘ => ‘AJAX Request Recieved‘,
nonce‘           => wp_create_nonce( ‘ajaxhandling‘ ),
) );
}

In the above method, two little methods viz: wp_send_json_error() and wp_send_json_success() are of prime importance while handling AJAX in WordPress.

Handling PHP’s Response in Javascript

Below is the method which allows us to receive response from PHP:

app.ajax_response = function( response_data ){/*== Response function ==*/
if( response_data.success ){
webdev.nonce = response_data.data.nonce;
alert( response_data.data.script_response );
  } else {
alert( ‘ERROR’ );
}
}
;

Since the _error and _success methods from WordPress have been used, the chances for receiving a success property are higher. Via _success, you’ll receive success=true in the json response which can further be used for checking whether the received response is adequate or not. However, if the AJAX request wasn’t a success, then an error would be thrown.

That’s it!

Conclusion

With AJAX in WordPress, you’re free to do nifty form processing in an absolutely stunning manner. Here’s hoping the above post would have rendered you useful details on dealing with AJAX in your WordPress blog/website. 


 

Author Bio :

Sophia Phillips is a renowned WordPress developer by profession. If you’re about to hire WordPress expert , then you can get in touch with her. Sophia already has multiple WordPress-related articles under her name.

The post Everything You Wanted To Know About Handling AJAX In WordPress appeared first on Creative WordPress Themes Awards.



This post first appeared on House Music Promote, please read the originial post: here

Share the post

Everything You Wanted To Know About Handling AJAX In WordPress

×

Subscribe to House Music Promote

Get updates delivered right to your inbox!

Thank you for your subscription

×