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

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

I was so confused and lost, seeing the code was so abstract to me. So in this tutorial, I want to show you how to use the jQuery framework to submit data through a form using jQuery to a PHP page that submits to a database.

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.

YOU SHOULD HAVE AN IDEA OF

  • Some principles of PHP
  • Basic knowledge of JavaScript and/or jQuery framework
  • MySQL
  • XHTML to build the form

JQUERY FUNCTIONS

HTML OUTLINE

<form id="submit" method="post">
<fieldset><legend>Enter Information</legend> <label for="fname">Client First Name:</label> <input id="fname" class="text" type="text" name="fname" size="20" /> <label for="lname">Client Last Name:</label> <input id="lname" class="text" type="text" name="lname" size="20" /> <button class="button positive"> <img src="../images/icons/tick.png" alt="" /> Add Client </button></fieldset>
</form>
<div class="success" style="display: none;">Client has been added.</div>

JQUERY TO COOK IT ALL

$(document).ready(function(){
	$("form#submit").submit(function() {
	// we want to store the values from the form input box, then send via ajax below
	var fname     = $('#fname').attr('value');
	var lname     = $('#lname').attr('value');
		$.ajax({
			type: "POST",
			url: "ajax.php",
			data: "fname="+ fname +"&amp; lname="+ lname,
			success: function(){
				$('form#submit').hide(function(){$('div.success').fadeIn();});

			}
		});
	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?

  • http://Yourwebsite... Ivan

    Hello its possible to also update the comments so it add the recently posted?

  • http://www.phptechie.com phptechie

    I can easily makeup my code with your example ..
    Thanks a lot..

  • http://Yourwebsite... Ash Wood

    hey guys, i had a few problems with this mysql and i had to make a few changes to get it working here are the page names and the codes i used that successfully got it working.

    index.html

    $(document).ready(function(){
    $(“form#submit”).submit(function() {
    // we want to store the values from the form input box, then send via ajax below
    var fname = $(‘#fname’).attr(‘value’);
    var lname = $(‘#lname’).attr(‘value’);
    $.ajax({
    type: “POST”,
    url: “ajax.php”,
    data: “fname=”+ fname +”& lname=”+ lname,
    success: function(){
    $(‘form#submit’).hide(function(){$(‘div.success’).fadeIn();});

    }
    });
    return false;
    });
    });

    Enter Information

    Client First Name:

    Client Last Name:

    Add Client

    Client has been added.

    ajax.php

    Thanks for the tutorial ive have been looking all over for something like this and even thought some changes needed to be made in the ajax.php it works and its great! thanks so much!

  • http://www.arohatech.com Ashish Kumar

    Informative article!actually I am working on php projects so this content is proof to be very helpful.thanks for sharing it.

  • http://drebpro.com Dreb

    I like the header of your blog. It’s quite amusing.

  • http://Yourwebsite... Rico Cremer

    For everyone who’d still like to know how to handle mysql error report… this can be done using JSON.

    Just add “dataType: ‘json’,” To the script and let your php return an JSON encoded array.

    PHP Example:

    $query = mysql_query(‘…’);

    if(!$query)
    {
    $error = array(
    ‘error’ => true,
    ‘error_msg => ‘Due an error your registration attempt has failed. Please try again’);
    }

    The JavaScript would be something like this:
    $(document).ready(function(){
    $(“form#submit”).submit(function() {
    // we want to store the values from the form input box, then send via ajax below
    var fname = $(‘#fname’).attr(‘value’);
    var lname = $(‘#lname’).attr(‘value’);
    $.ajax({
    type: “POST”,
    dataType “json”,
    url: “ajax.php”,
    data: “fname=”+ fname +”& lname=”+ lname,
    success: function(j) {
    if(J.error)
    { $(‘div.success’).fadeIn().html(j.error_msg);
    }
    else
    {
    $(‘div.success’).fadein().html(‘Registration succeed’);
    }
    }
    });
    return false;
    });
    });

    Or something like this. Not tested.

    Anyway, nice script. :)

  • http://www.unibands.co.uk/ Unibands

    Thank you so much for this! You really helped me out here which leaves me more time to go outside and enjoy the sunshine!

    It’s a pity the jQuery documentation (whilst very good) lacks good examples like this.

    Keep up the good work there friend.

    Michael.

  • http://jcanker.com Jca

    Oh, thank goodness–I’m learning jQuery and AJAX using XML not JSON, and I’ve been beating myself up trying to figure out why something wasn’t working as expected (or at all, for that matter.)

    In short, I’m trying to use the autocomplete widget to pull the list of customer names from my database and select one to display all the info in a containing div on the center column. Everything worked great **IF** I hard coded the $_POST variable in the php that pulled the specific customer data. I couldn’t figure out for the life of me how to get the specific data being sent via POST into the query. I tried $_POST[0] and a host of other options to no avail.

    Then in desperation I went out on the net one last time to slog through the sites I hadn’t yet looked at–I avoided yours because I wasn’t specifically using form data, I was grabbing the .value from the object returned from the autocompleter.

    And your example showed me what all the others didn’t. Most of the others just submit all the form data as an array using #MyForm. Your example showed me that I just had to change the .Ajax data option from selectedObj.value to “customer=”+selectedObj.value

    You, Good Sir,–May I call you Sir? You rock.

  • http://Yourwebsite... Samuel

    Thank you so much for that. I have looked over so many tuts trying to do just this and no one is explaining things properly or more so no one is explaining the whole process. So cheers showing me this method.

    @Rico Cremer I could not get your idea to work. Could you please go into some detail about how to get this JSON error to work. Does function(J) refer to the return JSON data? Cheers.

  • http://Yourwebsite... Paz

    Hi,
    i need your help….
    first of all congrat for your article
    but….how can i do if i have 6 page…. 10 elem per page….60 elements !
    there’s a way to make an arrya of all the element present in the form and send them via post ?
    thanx

  • http://Yourwebsite... Rico

    @Samuel

    Well, the example I gave ísn’t complete tho. It was just an idea :P

    I didn’t mentioned the jSON php code to encode the array and that’s what you’ve need to do.

    This example must work fine:

    // The JavaScript

    $(document).ready(function(){
    $(“form#submit”).submit(function() {
    // we want to store the values from the form input box, then send via ajax below
    var fname = $(‘#fname’).attr(‘value’);
    var lname = $(‘#lname’).attr(‘value’);
    $.ajax({
    type: “POST”,
    dataType: ‘json’,
    url: “ajax.php”,
    data: “action=addClient& fname=”+ fname +”& lname=”+ lname,
    success: function(j){

    if(j.error)
    {
    $(‘div.success’).fadeIn().html(j.msg);
    }
    else
    {
    $(‘form#submit’).hide(function(){$(‘div.success’).fadeIn().html(j.msg);});
    }
    });
    return false;
    });
    });

    // The PHP
    true,
    ‘msg’ => “An error occured”);
    }
    else
    {
    $response = array(
    ‘error’ => false,
    ‘msg’ => “Client has been added successful!”);
    }

    return $response;
    }

    // now we’ve got to jSON encode the $response array

    if (@$_REQUEST['action'] == ‘addClient’ && isset($_SERVER['HTTP_X_REQUESTED_WITH']))
    {
    echo json_encode(addQuery($_POST['fname'], $_POST['lname']));
    exit;
    }
    ?>

    I’m sure it would work fine but still i haven’t tested it ;)

  • http://Yourwebsite... Rico

    Darn, they messed up my code.
    I hope this will work: http://pastebin.com/hzjvLMjJ

  • http://Yourwebsite... Sam

    Want to create a wordpress login for my app. I think what you presented is the right route but Im not sure exactly how to parse the wordpress login info. Im not looking to create a wordpress mobile theme. I just want to be able to authenticate users (existing and new) from my app through the wordpress site. Any suggestions are greatly appreciated… Thanks

  • http://beerbragger.com jb

    Works great

    Just having trouble with my radio buttons for some reason I’m only getting the value from the first radio button not the one selected

  • http://Yourwebsite... Mat

    Great job! Thanks so much for the help.
    I was wondering how you would handle multiple submit buttons in a single form, each one calling a different php script and then returning the results to the current page?
    Any help would be awesome!
    Thanks.

  • http://google.com Administrat0r

    Clear, simple, and well explained

  • http://Yourwebsite... Lance

    A great example – Thanks!!!!

  • http://Yourwebsite... thxxx

    THx It my first time to work with jquery form elements.

  • http://Yourwebsite... learner

    Hi,
    Thanks for the tutorial.
    I understand the XHTML->ajax.php->mysql
    However,
    I was wondering if it cannot insert for some reason(i.e,mysql column unique) how it will return error message to form.
    ajax.php->xhtml.

  • http://Yourwebsite... kenv

    I does show me the success part but it doesnt send it to mysql… what i did wrong?

  • http://Yourwebsite... Ricky

    Hello,

    I’m trying to follow your tutorial. But I have a problem .. He enters senpre to backoff, even if the data are not in the database.

    http://paste2.org/p/1651166 —> post.php
    http://paste2.org/p/1651170 —> ajaxSubmit.js

  • http://www.sosius.hk/town Osuka

    Thanks ryan, my leader asked me to do something like this. Can you give some hints about using jQueryUI’s dialog widget that meet this article’s goal? :)

  • http://drfranca.com Daniel

    Why not “$(‘#fname’).val()” ?

  • http://tornadofilms.co.uk/ Sean

    What would be the security implications of using this script?
    Would you use jQuery to submit a Login which includes passwords and email addresses?

  • http://www.r-gate.net/ Mohamed Tair

    Thanks a lot for this interesting tutorial!

  • Ivan Djordjevic

    Thank you, this was very helpful!

  • Pingback: Retrieving Data with Jquery, AJAX, and PHP from a MySQL Database | DIGG LINK

  • Bigbrodesign

    Could I also use this to submit the form to a new page? So POST in the form, and GET on a new page?

  • Vikas kumar

     i have study your code .Thanks
    for code its easy.

  • Koykis

    Thanks for the info, this is the way i use to POST data asynchronusly. But what about if you have a file field in the form? I tried that one and the PHP doesn’t seem to catch any $_FILES… Any suggestions?