Submitting a form via AJAX using jQuery, PHP and JSON

My buddy Chris asked for some help the other day on submitting a contact form via AJAX. We had a debate on the best structure for doing so and I explained about using JSON for the AJAX response message from the form processing script. My preferred method is submitting a form via AJAX to a PHP script for processing the form. The PHP script returns a JSON response with whether the form submission was a success or not. I thought this would be a good tutorial so I whipped up a quick sample for everyone.

Your Typical Contact Form
Name:
Email:
Message:

This is usually what you’ll on your average contact form. Name, Email and Message fields with a submit button. Note that I also have a div titled formResponse which is where the form submission message will go.

Response Type Classes

.success{

	border: 2px solid #009400;
	background: #B3FFB3;
	color: #555;
	font-weight: bold;

}

.error{

	border: 2px solid #DE001A;
	background: #FFA8B3;
	color: #000;
	font-weight: bold;
}

Here are two classes for when we display our response message.

Include jQuery from Google

%MINIFYHTML0914efd8bece52a6154e4b1c9f2c167c12%

Including a Javascript file from a different domain is a good tip for speeding up your page load time as any Javascript files included in the HEAD tag that are hosted on your own domain have to be downloaded first before the BODY content is downloaded. If the files are hosted on a different domain however, they will get downloaded in parallel.

jQuery AJAX Code for Form Submission

	$(document).ready(function(){

		$("#myForm").submit(function(){

			$.ajax({
				type: "POST",
				url: "postForm.ajax.php",
				data: $("#myForm").serialize(),
				dataType: "json",

				success: function(msg){
					$("#formResponse").removeClass('error');
					$("#formResponse").removeClass('success');
					$("#formResponse").addClass(msg.status);
					$("#formResponse").html(msg.message);

				},
				error: function(){
					$("#formResponse").removeClass('success');
					$("#formResponse").addClass('error');
					$("#formResponse").html("There was an error submitting the form. Please try again.");
				}
			});

			//make sure the form doesn't post
			return false;

		});

	});

Here we attach a function to the onSubmit event of the contact form “myForm”. It is set to receive a JSON response. If the AJAX request is a success, we remove any previous response classes on the formResponse div, add the response message in and add the appropriate response class onto the div. If the AJAX call failed then we add the failed class to the response and a detailed message indicating that the form submission failed.

The Form Processor

//function to validate the email address
//returns false if email is invalid
function checkEmail($email){

	if(eregi("^[a-zA-Z0-9_]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$]", $email)){
		return FALSE;
	}

	list($Username, $Domain) = split("@",$email);

	if(@getmxrr($Domain, $MXHost)){
		return TRUE;

	} else {
		if(@fsockopen($Domain, 25, $errno, $errstr, 30)){
			return TRUE;
		} else {

			return FALSE;
		}
	}
}	

//response array with status code and message
$response_array = array();

//validate the post form

//check the name field
if(empty($_POST['name'])){

	//set the response
	$response_array['status'] = 'error';
	$response_array['message'] = 'Name is blank';

//check the email field
} elseif(!checkEmail($_POST['email'])) {

	//set the response
	$response_array['status'] = 'error';
	$response_array['message'] = 'Email is blank or invalid';

//check the message field
} elseif(empty($_POST['message'])) {

	//set the response
	$response_array['status'] = 'error';
	$response_array['message'] = 'Message is blank';

//form validated. send email
} else {

	//send the email
	$body = $_POST['name'] . " sent you a message\n";
	$body .= "Details:\n\n" . $_POST['message'];
	mail($_POST['email'], "SUBJECT LINE", $body);

	//set the response
	$response_array['status'] = 'success';
	$response_array['message'] = 'Email sent!';

}

//send the response back
echo json_encode($response_array);

Here is where all the work is done. We check to make sure the Name field is not empty, the Email address is valid through a very nice function, and the Message is not blank. If any of these conditions fail we set the $response_array status to error and add in the error message. If all the data checks out we send the email out and set the $response_array status to success. At the very end we just use json_encode to package the response array as a JSON response for the AJAX can understand what we send it back.

Put it All Together

See the demo: PHP AJAX JSON Form mail() line commented for spam reasons =)
Source Files: PHP AJAX JSON Form Source

References:

jQuery AJAX API
What is JSON?

I hope this simplified AJAX form helps you out. If you have any questions let me know.

Continue Reading

  • This post totally saved my ass. Thanks man, really appreciate the clear, concise information. Keep it coming!

  • Skye

    Not sure why the field validation is showing double empty calls (emptyempty). The plain text version is correct though.

  • perlman

    thanks for this, really helped me

  • Few issues:

    #a. Current form won’t work with Javascript disabled.

    A better option would be to do something like following:
    var paraTag = $(‘input#submit’).parent(‘td’);
    $(paraTag).children(‘input’).remove();
    $(paraTag).append(”);

    This will simply change the input type of Submit from ‘submit’ to ‘button’. Then we can intercept click event for the button input with the id=submit.
    $(‘#main input#submit’).click(function() {
    ———your code goes here..———————
    }}

    #b. PHP script won’t echo standard html in case the Javascript is disabled, thus becoming obsolete in terms of ux..

    #c. Currently, responded json can accommodate only one error+msg pair. IMHO, there are plenty of chances that there are more than one errors. In that case user has to fill form for each subsequent error. Using an associated array for errors and $session variables in form’s ‘value’ attributes may help,

    Two good examples would be:
    http://blog.themeforest.net/tutorials/how-to-create-a-contact-form-using-php-and-ajax/
    tutorialzine.com/2009/09/fancy-contact-form/

    Disclaimer: Although, I’m a user the envanto networks (themeforest is part of it), I don’t have any vested interest in sharing their links here other than sharing a few good things for fellow developers.

    • Skye

      Thanks for the comments.

      #a. Yup, you’re correct. Personally, I’m not worried about that as most sites these days won’t work without JS. I’ve yet to see someone complain about a feature not working because they have JS turned off.
      #b. Correct. Only obsolete for non JS people.
      #c. Good modification if you want multiple error messages.

  • Victor

    What about clearing/resetting the form once it is submitted and leaving behind nothing but the JSON response?

    • Skye

      To clear the form just add a hidden (display: none) reset form input button then in your success statement add $(“#resetButtonID”).click(); That will clear the form.

      If you want to hide the form just do $(“#myForm table”).hide(); You can get more creative with jQuery and do slides and such also.

  • AhmadRyo

    Thanks ..