Writings, notes, and work of a Boston based designer

Use jQuery To Submit Form To PHP/MySQL Nov 4 + 2 comments

written by: ryan coughlin

UPDATE: This was updated on August 18, 2012 – updated demo and code! Cleaner and proper code updates.

Using jQuery to submit a form, is something you are seeing more and more of as jQuery’s popularity grows. When I first started reading about jQuery and Ajax all I wanted to do was learn how to submit a form using jQuery and yes this was years ago.

View the demo to submit a form using jQuery and Ajax. Updated demo with new styles and code. This new code is using the elements and styles that belong to the Twitter Bootstrap, download and get it setup if you want the same look and feel as the demo.

We are going to take form data and submit it to a jQuery Ajax call then send that to a PHP page with the data. Check out a live example of this post.

JQUERY FUNCTIONS

HTML STRUCTURE

<form class="well" id="jquery-submit-ajax" method="post">
	<label>Your Name</label>
	<input type="text" class="span7" name="yourName" placeholder="Type something…">
	
	<label>Your Email</label>
	<input type="text" class="span7" name="yourEmail" placeholder="Type something…">
	<span class="help-block">When this form is submitted it will be sent via jQuery/AJAX.</span>

	<input class="btn btn-primary" type="submit" value="Submit & Test Form">
	<br /><br />
	<div class="alert alert-success hide">
		<p>Form successfully submitted! The data sent is below:</p>
		<div id="success-output" class="prettyprint"></div>
	</div>
	<div class="alert alert-error hide">
		<p>Oh shit! Error below:</p>
		<div id="error-output" class="prettyprint"></div>
	</div>
</form>

JQUERY TO COOK IT ALL

 

$(document).ready(function(){
$(&quot;#jquery-submit-ajax&quot;).submit(function(e) {
	$.ajax({
		type: &quot;POST&quot;,
		url: &quot;jquery-ajax-control.php&quot;,
		data: $(e.target).serialize(),
		dataType: &quot;json&quot;,
		beforeSend:function <a href="http://nomunication.com/">Electronic Cigarette</a>(){
			$(&#039;.alert-error,.alert-success&#039;).hide();
		},
		error: function(jqXHR, textStatus, errorThrown){
			$(&#039;.alert-error&#039;).fadeIn();
			$(&#039;#error-output&#039;).html(errorThrown);
		},
		success: function(data){
			$(&#039;.alert-success&#039;).fadeIn();
			$(&#039;#success-output&#039;).html(data);
		}
	});
	return false;
});

The next section is the bulk of the code. jQuery makes it very nice and easy to create Ajax calls. As you see, we have type, url, data, and success. These are pretty self explanatory.

  • TYPE – Are you going to use POST or GET
  • URL – What is the URL you are sending the data to
  • DATA – The data that you are sending the the URL to be processed
  • SUCCESS – What should the function do after the call has been executed

Remember that all of these are explained at the jQuery page, you can find the documentation for the Ajax calls here. There is a slew of options you can run within this one jQuery.ajax() function.

The success part:

success: function(){
     $('form#submit').hide(function(){$('div.success').fadeIn();});
}

Once the form is successfully submitted, the form will hide and thanks to jQuery callbacks, we then show the success message.

THE BACKEND – AJAX.PHP

Below is what our ajax.php file will look like, this will carry out the submission. Save this as ajax.php.

<?php

	include ("../../inc/config.inc.php");

	// CLIENT INFORMATION
	$fname        = htmlspecialchars(trim($_POST['fname']));
	$lname        = htmlspecialchars(trim($_POST['lname']));

    $addClient  = "INSERT INTO clients (fname,lname) VALUES ('$fname','$lname')";
    mysql_query($addClient) or die(mysql_error());

?>

There you have it, a straight forward guide to to using jQuery, PHP, and a simple HTML form to submit a form. Hopefully this will be a help to users new to the jQuery/Ajax world! If you have any comments or questions get in touch with me.

Take a peak at some more?

  • Ewu0512

    Where do I get the file “config.inc.php”"

  • A212

    دست شما متشکر
     

  • Sanj

    This is a great example, I am trying to learn jQuery form elements. I having trouble trying to submit the response from checkbox and select menus. I am looking for direction or help with a similar form example that has checkbox and select menus

  • http://www.facebook.com/totto.bennington Totto Bennington

    What is the code of include (“../../inc/config.inc.php”); ?

  • Ray Boy

    Been lookin for this code everywhere thanks for making it so easy n siple  KUDOS BRO

  • Dani

    do you have a complete demo package for download? I’m trying to follow but there seems to be missing steps in this tutorial

  • bhuss

    saddsad

  • Andre

    where?

  • Peter

    jquery-ajax-control.php???? where can i get these?

  • Peter

    which Formailer can I use? Help pls

  • OMFG4Real

    lol!! Jackass! Config is the file that contains his database connection info.

    You write your own…

  • Ruprecht Coleman

    Looks like you’re missing “});” to close the function in the example above.  Adding it makes the example work for me.

    $(document).ready(function() {
    $(“#jquery-submit-ajax”).submit(function(e) {
    $.ajax({
    type: “POST”,
    url: “ajax.php”,
    data: $(e.target).serialize(),
    dataType: “json”,
    beforeSend:function(){
    $(‘.alert-error,.alert-success’).hide();
    },
    error: function(jqXHR, textStatus, errorThrown){
    $(‘.alert-error’).fadeIn();
    $(‘#error-output’).html(errorThrown);
    },
    success: function(data){
    $(‘.alert-success’).fadeIn();
    $(‘#success-output’).html(data);
    }
    });
    return false;

    }); 
    });

  • Santhiyagusa

    test

  • Ponraj Paul

    So easy and works well. For the last 3 months i have tried lot of methods but output is zero. This is the only one best method. Thank u Mr.Ryan Coughlin.

  • A Persian Language!

    go to google translate and translate this Comment!
    سلام.این متن اصلا مهم نیست و شما انگلیسی زبان ها ، سرکار هستید!

  • salim

    Hi All, form is submiting for me but the value is not storing in my database… What is wrong ?