In this tutorial I am going to cover how to use Ajax to submit and process form data in your WordPress plugins. In order to tie things together, and to provide you a real world example, I am going to be working with the code used in my Short Code Contact form plugin.

As I’ve already set all of the HTML up in the other tutorial, I’m just going to show you what is going on with the jQuery.

Normally, when a user clicks the submit button on an HTML form, the data is sent to a PHP file for processing, then the user is redirected to some page. Processing the form data with Ajax is not much different, except that the user stays on the page and is never redirected. So what we are going to do is essentially disable the submit button, so that the page doesn’t change, and then intercept the data sent from the form with jQuery. We will then pass that data to a PHP file for processing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<script type="text/javascript"> 
	var $j = jQuery.noConflict();
	$j(window).load(function(){		
		// this is the ID of your FORM tag
		$j("#contact-form").submit(function(e) {
                    e.preventDefault(); // this disables the submit button so the user stays on the page
		    // this collects all of the data submitted by the form
			var str = $j(this).serialize();					 
			   $j.ajax({			   
			   type: "POST", // the kind of data we are sending
			   url: "path/to/sendmail.php", // this is the file that processes the form data
			   data: str, // this is our serialized data from the form
			   success: function(msg){	// anything in this function runs when the data has been successfully processed
 
					// this sets up our notification area for error / success messages
					$j("#note").ajaxComplete(function(event, request, settings)
					{ 
						if(msg == "OK") // Message Sent? Show the Thank You message and hide the form
						{
							// This is shown when everything goes okay
							result = "Your message has been sent. Thank you!";
 
							// now hide the form fields
							$j("#fields").hide();
						}
						else // if there were ewrrors
						{
							result = msg; // msg is defined in sendmail.php
						}								 
						$j(this).html(result); // display the messages in the #note DIV							 
					});					 
				}					 
			 });					 
		});			
	});
</script>

One of the things you should note about this code is how I have setup jQuery in noConflict mode. This helps to mitigate conflicts between jQuery scripts. Unfortunately, jQuery conflicts are all too common with themes and plugins. Refer to my Coding Standards page for more information.

I’ve left detailed comments throughout the code here, but here’s what is going on.

First, we are using jQuery to intercept the data sent by the HTML form with:

$j("#contact-form").submit(function() {

Next, we serialize the data and storing it in a variable:

var str = $j(this).serialize();

What this means is that we are converting all of the data into POST format. So, for example, you have an input field named “message” with a user enter value of “hello”. Once serialized, that data looks like this:

message=hello

and will be accessible in our sendmail.php like:

$message = $_POST['message'];

The next step in our jQuery script is

$j.ajax({ . . });

which is used to actually send our serialized data to the PHP file for processing. Within this function we have the definitions for the sendmail.php file path, the type of data we are sending (POST), and also what we want to happen when the data has been processed successfully.

So inside of the ajax function, we have a “success” function, which runs after the data has been processed successfully. And inside of this function, we have another function

$j("#note").ajaxComplete(function(event, request, settings)

that takes care of displaying the error / success messages, and also hiding the form fields upon success.

The last piece of our function is

return false;

This makes sure that page just not get reloaded or redirected when the submit button is clicked. It essentially disables the button.

And that’s it! This is all you need to process forms with ajax. Obviously I have not included the PHP in sendmail.php necessary for the actually processing of the form, but that is all covered in my Ajaxified Contact Form tutorial.

  1. AJ Clarke

    nice tutorial. You’ve done a good job commenting every line so its easy for people to see what’s going on.

    The only thing left is to add a simple CAPTCHA – like “what color is grass?”

    • pippin

      Some form of captcha like validation would be good, but that would be better placed in the other tutorial on creating the actual plugin, as this is just focusing on the ajax 😉

  2. Topher

    I’m working on a plugin that really needs modal windows for forms inside the admin area. Could you speak about how to keep those secure, load just a form without the rest of the admin page content around it, etc.?

    • pippin

      Are you loading custom forms that you have created, or forms that already exist in the dashboard? And are you trying to load them in the dashboard, or on the front end?

    • Topher

      These would be custom forms I created, and I’m loading them in the admin area. I’ve read some about nonce, and I’m aware of the is_admin function. It seems however, like I’d need to include something from wordpress in my form to make it so that is_admin is a known function in my form, or at least in the submit file.

    • pippin

      If your submit file, if you include wp-load.php, as I did in this tutorial, you will be able to use any and all of the core wordpress functions.

      Send me an email if you want with a detailed explanation of what you are trying to do, and what the forms are going to be used for, and I should be able to help you out easier.

    • Pippin

      Thanks for the link. I wasn’t aware of that. I’ve updated the post.

  3. Glenn

    Hi Pippin,

    Thanks for sharing this easily readable code. This is exactly what I need, if I could only make it work. For some reason the submit button doesn’t post anything. Do you happen to know where the problem could lie? The button id is the same as $j(“#contact-form”).submit…

    With Regards from Germany,
    Glenn

    • Pippin

      Show me a live URL.

  4. surendra

    If we want to fetch the data and modify the data on the same page is it possible to do with Jquery or there is another way?.
    I am trying to fetch data using Jquery and fill that data into forms. Later after user modifies the form data again on submit I want to update the data in database without reloading using Jquery again

    • Pippin

      Yep, jQuery makes that pretty easy!

Comments are closed.