Pippins Plugins
  • Email
  • Facebook
  • Feedburner
  • Github
  • Google
  • Twitter
  • Vimeo
  • Youtube
  • Rss
  • About
  • News
  • Join the Site
    • Member Benefits
    • Member Plugins
    • Email Notifications
  • Plugin Store
    • Affiliate Area
    • Checkout
  • Plugins
    • Plugin Portfolio
      • Plugin Portfolio – List View
    • Free
    • Premium
    • Member Plugins
    • Coding Standards
    • Get Plugin Support
  • Tutorials
    • Series
      • Plugin Development 101
      • Creating a User Follow System Plugin
      • Customizing Restrict Content Pro
      • Displaying Content with Easy Content Types
      • Writing Your First WordPress Plugins, Basic to Advanced
      • Working with Widgets
      • User Submitted Image Galleries
      • Plugin Thoughts
      • Integrating Stripe.com with WordPress
      • WordPress Rewrite API
    • Member Exclusive
      • Free Members
      • Subscriber Only
    • Difficulty
      • Beginner
      • Intermediate
      • Advanced
    • Action and Filter Hooks
    • Ajax
    • Custom Post Types
    • External APIs
    • Short Codes
    • Taxonomies
    • Video Tutorials
    • Widget Tutorials
    • WordPress Admin / Dashboard
    • Working with jQuery
    • WordPress Database
    • Writing Plugins
    • Tag Index
  • Reviews
  • Support Forum
  • Contact
    • Support the Site
    • Request Code Review
    • Plugin Support

Post Data with Ajax in WordPress Pugins

Posted on May 10, 2011 by Pippin in Advanced, Ajax, Contact Forms Tutorials, Tutorials, Working with jQuery, Writing Plugins 9 Comments
Home» Tutorials » Advanced » Post Data with Ajax in WordPress Pugins
Tweet
Love It - 3

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.

Tweet Follow @pippinsplugins
Ajax, forms

9 comments on “Post Data with Ajax in WordPress Pugins”

  1. AJ Clarke says:
    May 11, 2011 at 7:25 pm

    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?”

    Reply
    • pippin says:
      May 11, 2011 at 7:29 pm

      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 says:
    May 12, 2011 at 3:54 pm

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

    Reply
    • pippin says:
      May 12, 2011 at 4:03 pm

      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 says:
      May 12, 2011 at 5:22 pm

      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 says:
      May 12, 2011 at 5:29 pm

      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.

  3. iCosmin says:
    April 18, 2012 at 2:30 pm

    A little late to the party, but you might want to change return false; to e.preventDefault() when you get the time.

    Here’s why: http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/

    Reply
    • Pippin says:
      April 18, 2012 at 2:48 pm

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

  4. Top 8 Best Wordpress Tutorial Sites | The Geek Connection says:
    February 13, 2013 at 2:36 am

    [...] Pippins Plugins [...]

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

  • Login

Lost your password?

Please enter your username or e-mail address. You will receive a new password via e-mail.

  • Facebook Become a Fan Like

  • Twitter Subscribe on Twitter Follow

  • YouTube Follow my Videos Subscribe

  • RSS Feed Subscribe with RSS Subscribe

Easy Digital Downloads

Most Loved

  • Love It Pro for WordPress
  • Write a “Love It” Plugin with Ajax to Let Users Love Their Favorite Posts / Pages
  • Simple Notices Pro Plugin for WordPress
  • User Bookmarks for WordPress
  • Front End Registration and Login Forms Plugin

Similar Plugins and Posts

  • Using Ajax in Your Plugin and WordPress Admin
  • Create a Live Search in WordPress with jQuery and Ajax
  • WordPress Rewrite API – Part 3
  • Love It Pro for WordPress
  • Write a “Love It” Plugin with Ajax to Let Users Love Their Favorite Posts / Pages

Latest Premium Content

  • Plugin Development 101 – Introduction to Adding Dashboard Menus
  • Plugin Development 101 – Intro to Loading Scripts and Styles
  • User Follow System – Part 5
  • Plugin Development 101 – Intro to Short Codes

Latest Tutorials

  • Storing Session Data in WordPress without $_SESSION (19)

    The term Session in web development refers to...

  • Test Your Plugins with RTL (1)

    Right-To-Left languages are those that...

  • Submitting Your First Pull Request to a WordPress Plugin on Github (5)

    Github is an extremely popular tool for managing WordPress plugins, and one...

Enter your email to receive automated updates when new posts are published

WP Core Contributions

  • [24316]

View the ticket on Trac.

WP Codex Contributions

  • Function: shortcode exists
  • Function: has shortcode
  • Function: shortcode exists
  • Function: shortcode exists
  • Function: has shortcode

View all 41 changes in the Codex.

Latest Tweets

  • Could not fetch Twitter RSS feed.

Topics

contextual help featured Tom McFarlin shortcodes meta box get_user_meta register_setting add_options_page attachments campaign monitor hook Sugar Event Calendar wp_enqueue_script forms short codes plugin Related posts login do_action authors mail chimp attachment image recent posts post types apply_filters comments short code bbpress taxonomies custom post type Ajax images gallery Stripe taxonomy jquery widgets users add_filter easy content types add_action widget restrict content pro easy digital downloads

Weekly Newsletter

Useful Links

  • Join the Site
  • Plugin Store
  • Affiliate Area
  • Tag Index
  • Support the Site
  • Suggest a Tutorial
  • Random Post
  • Contact

Monthly Archives

(c) 2013 Pippin's Plugins