There are several factors to consider when building your web application, the mobility, user-friendliness, and interactivity. The response of the application to user is a must. AJAX or Asynchronous JavaScript and XML solve this problem. Today, I will show you how to combine AJAX, jQuery and WordPress to create simple and powerful WordPress projects that I’m sure you will enjoy. The use of WordPress shortcode will add spice to our tutorial. I’d also included a demo and project file so that you can easily test this project to your own servers. Here are some key points that we need to focus on.
– Creating a form and register it as shortcode
– Adding jQuery library and AJAX script
– Creating a PHP function to handle AJAX request
Creating a form and register it as shortcode
function ajax_form_shortcode() { $form = '<div id="my-ajax-wrap"><form id="my-ajax-form">'; $form .= '<input name="my_ref" type="hidden" value="'.wp_create_nonce('ajax_sample').'" />'; $form .= '<input id="ajax_admin_url" type="hidden" value="'.admin_url('admin-ajax.php').'" />'; $form .= '<input name="action" type="hidden" value="my_ajax_action" />'; $form .= '<p>Nickname</p>'; $form .= '<input name="name" type="text" />'; $form .= '<p>Message</p>'; $form .= '<textarea name="message"></textarea>'; $form .= '<p><input type="submit" value="Send" id="mybutton"></p>'; $form .= '</form></div>'; return $form; } add_shortcode('my_ajax_form', 'ajax_form_shortcode');
You need to create a normal GET/POST form, but this time, register it in a WordPress shortcode. The idea of shortcode in Wordpres is its portability. You can easily paste this shortcode to any page or post you want without editing you template page. Add few hidden input field on your form. These hidden fields are required to validate the AJAX request.
In line #3 we used wp_create_nonce(‘ajax_sample’), this will create a random token for our request, a security check from wordpress. In line #4 we also need to locate the URL of admin-ajax.php, the URL to which the request will be sent. In line #5 we need to set also action, this is basically an indentifier of the PHP function that will handle the GET/POST request from admin-ajax.php.
Now, register the form as a WordPress shortcode using the action hook add_shortcode(). See Shortcode API for more info.
Adding jQuery library and AJAX script
add_action('wp_footer', 'my_script'); function my_script(){?> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> <script type="text/javascript" src="<?php echo bloginfo('template_directory').'/myscript.js';?>"></script> <?php }
Include jQuery library to the template page, because $.post(); function will be used in sending AJAX request. Include js script that contains the AJAX request function. I used myscript.js as my script file located on my template directory root.
myscript.js
$('#mybutton').click(function(){ var admin_ajaxurl = jQuery('#ajax_admin_url').val(); var data = jQuery('#my-ajax-form').serialize(); $.post(admin_ajaxurl, data, function(response){ var res = $.parseJSON(response); alert('Name: '+ res.name +'\r\nMessage: '+ res.message + '\r\n' + 'Token: ' + res.my_ref + '\r\n' +'Action: ' + res.action); }); return false; });
Obtain the input field values and convert it to serialized data using $(‘#my-ajax-form’).serialize(); function. As we all know, admin_ajaxurl contains the admin-ajax.php URL and data contains the field values including your hidden inputs. Then it ready to send the AJAX request, after calling the $.post(); function, the XMLHttpRequest response will be stored as response variable. The output will be in JSON format, that is why you need to parse it using $.parseJSON();. Creating a PHP function to handle AJAX request:
add_action('wp_ajax_my_ajax_action', 'handle_ajax_request'); add_action('wp_ajax_nopriv_my_ajax_action', 'handle_ajax_request'); function handle_ajax_request(){ check_ajax_referer('ajax_sample','my_ref'); $data = $_POST; echo json_encode($data); die(); }
Now, you have your jQuery function that sends the AJAX request. Then, manage the PHP script that will receive the request and return as JSON format. Again, as you can see, a new action hook call is added, add_action(‘wp_ajax_ACTION_NAME’, ‘handle_ajax_request’); and add_action(‘wp_ajax_nopriv_ACTION_NAME’, ‘handle_ajax_request’);.
The idea with ‘wp_ajax_ACTION_NAME’ is to get the data from POST($_POST[‘action’]) and call the ‘handle_ajax_request’ function as its callback. You can also notice that you called add_action(‘wp_ajax_nopriv_ACTION_NAME’, ‘handle_ajax_request’);, which is pretty similar to the first action hook, but the difference is that ‘wp_ajax_ACTION_NAME’ is for logged in users, and ‘wp_ajax_nopriv_ACTION_NAME’ is for public.
Some of you will ask, where did i get ‘wp_ajax_my_ajax_action’. Let us go back to Creating a form and register it as shortcode in line #5, we declared
<input name=”action” type=”hidden” value=”my_ajax_action” />
. You can put any action name you want, as long as it matches the ‘wp_ajax_ACTION_NAME’ and ‘wp_ajax_nopriv_ACTION_NAME’.
Adding a style to our form (Optional)
/*****MY AJAX CSS***/ #my-ajax-wrap input, #my-ajax-wrap textarea, #my-ajax-wrap #mybutton { background:none repeat scroll 0 0 #EEEEEE; color:#444444; -moz-border-radius:4px; -webkit-border-radius:4px; border-radius:4px; border:1px solid #59A3CF; font-size:16px; margin-bottom:10px; } #my-ajax-wrap input:focus, #my-ajax-wrap textarea:focus, #my-ajax-form #mybutton:hover { background:none repeat scroll 0 0 #FFF; } #my-ajax-form p{ padding:0;margin:0; font-size:13px; font-weight:bold; } #my-ajax-form input{ height:23px; width:270px; margin-bottom:10px; } #my-ajax-form textarea{ padding:5px; width:41%; } #my-ajax-form #mybutton{ cursor:pointer; font-weight:bold; width:auto; }
Just paste this css code in your style.css and run the shortcode.
You can run this script by adding the shortcode [my_ajax_form] on your post or page in WordPress text editor. That’s it we’re done!