Friday, February 17, 2012

A Tutorial On Using AJAX In WordPress

A Tutorial On Using AJAX In WordPress:

ajax tutorialAJAX is a remarkable web technology that moved us beyond the simple “click link, go to another page” structure of The Internet 1.0.


AJAX, which stands for Asynchronous Javascript and XML, enables websites to dynamically fetch and display content without the user moving away from the current page. This leads to a far more interactive user experience, and can speed things up too since a whole new webpage needn’t be loaded. Luckily, making use of AJAX is quite easy to do from within the WordPress environment, and today I’m going to show you how.


This Ajax tutorial should be considered fairly advanced, and continues on from last time where we learnt how to use custom database tables from within a WordPress template – in my example, a simple existing table of customer data was used. When it comes to inserting things back into the database though, we’re going to be making use of a little AJAX magic within WordPress.


All the code in todays tutorial will therefore be referencing what we wrote last time, but if you’re just looking for how to do AJAX in WordPress then it’s equally as relevant.


Why Use AJAX?


The most common use of AJAX is related to forms – checking if a username is taken, or populating the rest of the form with different questions depending on a particular answer you give. Basically though, you use AJAX whenever you want an event (like a user clicking something, or typing something) tied to a server-side action that occurs in the background.


We’re going to use it to add new entries to our important customized customer database table, but you can probably come up with something more exciting.


Overview of How To Use AJAX in WordPress



  1. Edit your custom template to include a form or javascript event that will submit data via jQuery AJAX to admin-ajax.php including whatever post data you want to pass in. Make sure jQuery is being loaded.

  2. Define a function in your theme’s function.php; read post variables, and return something back to the user if you wish.

  3. Add an AJAX action hook for your function.


Creating the Form


Let’s start by creating a simple form on the front-end for entering new customer details. It’s nothing complicated, just replace the main part of your custom template with this code that we began last week, around where the is_user_logged_in() check occurs:



if (is_user_logged_in()):?>

<form type="post" action="" id="newCustomerForm">

<label for="name">Name:</label>
<input name="name" type="text" />

<label for="email">Email:</label>
<input name="email" type="text" />

<label for="phone">Phone:</label>
<input name="phone" type="text" />

<label for="address">Address:</label>
<input name="address" type="text" />

<input type="hidden" name="action" value="addCustomer"/>
<input type="submit">
</form>
<br/><br/>
<div id="feedback"></div>
<br/><br/>


The only thing that might look odd to you is that there is the use of a hidden input field called action – this contains the name of the function we’ll trigger via AJAX.


ajax tutorial


The PHP Receiver


Next, open up functions.php and add the following line to ensure jQuery is being loaded on your site:



wp_enqueue_script('jquery');


The basic structure for writing an AJAX call is as follows:



function myFunction(){
//do something
die();
}
add_action('wp_ajax_myFunction', 'myFunction');
add_action('wp_ajax_nopriv_myFunction', 'myFunction');


Those last two lines are action hooks that tell WordPress “I have a function called myFunction, and I want you to listen out for it because it’s going to be called through the AJAX interface” – the first is for admin level users, while wp_ajax_nopriv_ is for users who aren’t logged in. Here’s the complete code for functions.php that we’re going to use to insert data in our special customers table, which I’ll explain shortly:



wp_enqueue_script('jquery');

function addCustomer(){

global $wpdb;

$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$address = $_POST['address'];

if($wpdb->insert('customers',array(
'name'=>$name,
'email'=>$email,
'address'=>$address,
'phone'=>$phone
))===FALSE){

echo "Error";

}
else {
echo "Customer '".$name. "' successfully added, row ID is ".$wpdb->insert_id;

}
die();
}
add_action('wp_ajax_addCustomer', 'addCustomer');
add_action('wp_ajax_nopriv_addCustomer', 'addCustomer'); // not really needed


Just as before, we’re declaring the global $wpdb to give us direct access to the database. We’re then grabbing the POST variables which contain the form data. Surrounded in an IF statement is the function $wpdb->insert, which is what we use to insert data into our table. Since WordPress provides specific functions for inserting regular posts and meta data, this $wpdb->insert method is generally only used for custom tables. You can read more about it on the Codex, but basically it takes the name of the table to be inserted into, followed by an array of column/value pairs.


The ===FALSE checks to see if the insert function failed, and if so, it outputs “error“. If not, we’re just sending a message to the user that Customer X was added, and echoing the $wpdb->insert_id variable, which indicates the auto-increment variable of the last insert operation that happened (assuming you’ve set a field that auto-increments, like an ID).


Finally, die() will override the default die(0) provided by WordPress – this isn’t essential as such, but without it you’re going to get 0 appended to the end of anything you send back to the template.


The Javascript


The final step is the magic bit - the actual Javascript that will initiate the AJAX call. You’ll notice that in the form we added earlier, the action field was left blank. That’s because we’ll be overriding this with our AJAX call. The general way to do this would be:



jQuery.ajax({

type:"POST",

url: "/wp-admin/admin-ajax.php", // our PHP handler file

data: "myDataString",

success:function(results){

// do something with returned data

}

)};


That’s the basic structure of AJAX call we’ll be using, but certainly not the only way you can do it. You might be wondering why we’re referring to wp-admin here, even though this will be on the front-end of the site. This is just where the AJAX handler resides, whether you’re using it for front or admin side functions – confusing, I know. Paste the following code directly into the customer template:



<script type="text/javascript">
jQuery('#newCustomerForm').submit(ajaxSubmit);

function ajaxSubmit(){

var newCustomerForm = jQuery(this).serialize();

jQuery.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php",
data: newCustomerForm,
success:function(data){
jQuery("#feedback").html(data);
}
});

return false;
}
</script>


In the first line, we’re attaching our ajaxSubmit function to the form we made earlier – so when the user clicks submit, it goes via our special AJAX function. Without this, our form will do nothing. In our ajaxSubmit() function, the first thing we do is to serialize() the form. This just takes all the form values, and turns them into one long string that our PHP will parse out later. If it all works out right, we’ll put the returned data into the DIV with the id of feedback.


That’s it. Save everything, refresh and try submitting some form data. If you’re having problems, you can view the full code of the page template here (based on the default twenty-eleven theme), and the code to add to functions.php here (don’t replace, just add this on the end).


ajax tutorial


Things to Keep In Mind


Security: This code isn’t production ready and is for the purposes of learning only. We have left out one key point, and that’s the use of a wp-nonce – a one-off code generated by WordPress that ensures the AJAX request is only coming from where it was intended; a passkey if you will. Without that, your function could effectively be exploited to insert random data. SQL injection attacks aren’t a problem though, because we routed queries through the WordPress $wpdb->insert function – WordPress cleans any inputs for you and makes them safe.


Updating the table of customers: Right now, we only send back a confirmation message, but the table of customers doesn’t get updated – you’ll only see the additional entries if you refresh the page (which kind of defeats the purpose of doing this all via AJAX). See if you can make a new AJAX function that can dynamically output the table.


Input Validation: because there’s no validation going on with the form data, it’s actually possible to add blank entries, or multiple entries if you press too many times. Some input validation on the form fields, clearing them when completed, as well SQL to check the email or phone number that doesn’t already exist in the database would be useful.


That’s it from me this week – if you’ve had any problems following this tutorial then feel free to get in touch via the comments and I’ll do my best to help you; or if you’re trying to customize this in some way, feel free to bounce ideas off me. I hope this really goes to show just how much you can do from within WordPress simply by combining a little JavaScript, PHP, and MySQL. As ever, don’t forget to check out all our other WordPress articles.




No comments:

Post a Comment

[Please do not advertise, or post irrelevant links. Thank you for your cooperation.]