A Tutorial On Using AJAX In WordPress

Ads by Google

featured wordpress   A Tutorial On Using AJAX In WordPressAJAX 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.

Ads by Google

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.

form   A Tutorial On Using AJAX In WordPress

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).

added   A Tutorial On Using AJAX In WordPress

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.

Ads by Google

20 Comments - Write a Comment

Reply

Edgar

Very helpful post. I did the same process that you mention but when I sutdmit the form I receive an error saying “[object Object]”. Do you have an idea of what I am doing wrong?

muotechguy

Can you post a URL for me to test from? The debugger should show me what exactly the object being returned is.

Edgar

Hey!! Thank You for your response! I used the debugger I found the issue. My theme and this were loading different jquery versions.

Anthony

Hello,
your example working corectly in localhost but when I tried it on domain Ajax return -1 The same situtaion is in localhost in Chrome browser. Path to ajax is correct. thank you for you support

muotechguy

Could you post a URL?

Anthony

Yes URL is correct problem in admin-ajax.php line48 die(‘-1′); I tried return jQuery.post(“”, { name: “John”, time: “2pm” } ); to existing site URL but still error 404 have you any idea why. page exist it is not problem. What I doing? I create new custom post typy wp_insert_post( $tacher_cal_post, $wp_error );
Working correctly but I need return $post_id to $_POST variable for the next post processing in template file.
Thanks

muotechguy

I mean, please post a URL for a demo page, and a pastebin with relevant code added if you can. It’s difficult to tell you whats wrong with the code you’ve pasted here…

Reply

Sharaz

I tried you tutorial but I don’t think data is getting to my PHP function. I get a returned value of 0. Any ideas?

Camaleo

@Sharaz I had the same problem when I used uppercase letters in the first add_action parameter:

the following return “0” :(

add_action(‘wp_ajax_form_Test_Validator’, ‘__formTestValidator’);
add_action(‘wp_ajax_form_Test_Validator’, ‘__formTestValidator’);

the following work :)
add_action(‘wp_ajax_form_test_validator’, ‘__formTestValidator’);
add_action(‘wp_ajax_form_test_validator’, ‘__formTestValidator’);

@James Simple, clean… perfect: Thank you so much!!

muotechguy

Are you running on Windows server by any chance? Or perhaps an older version of PHP?

Camaleo

I am on OSX 10.7.4, MAMP PRO, PHP 5.2.17

muotechguy

Ahh, probably the local server thing is not liking the capitalisation. Oh well, as long as you got it fixed, thanks adding that for others here.

Camaleo

sorry Sharaz, I meant:

wrong
add_action(‘wp_ajax_form_Test_Validator’, ‘__formTestValidator’);
add_action(‘wp_ajax_nopriv_form_test_validator’, ‘__formTestValidator’);

right
add_action(‘wp_ajax_form_test_validator’, ‘__formTestValidator’);
add_action(‘wp_ajax_nopriv_form_test_validator’, ‘__formTestValidator’);

also, if you keep seeing a 0 in the ajax output, be sure to close function addCustomer() with a die(); I guess using a return; will let ajax print the result code.

Reply

Alex

You should always separate the javascript from the HTML output. The javascript should live in its own file and be enqueued to the header.

muotechguy

I respectfully disagree. What if you have PHP dependant Javascript variables? WordPress doesn’t have a Javascript API, so you’re left with declaring Javascript globals somewhere in the PHP regardless.

On a single page template, it also keeps things neater and more efficient. Theres simply no need to make multiple files and hook into the header.

muotechguy

MY code works. Are you having problems following the tutorial?

Alex

Yes, I get a 404 error on submit with the fields in the URL. I am currently specifying the url as: url: . “/wp-admin/admin-ajax.php”,

Your comment