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://www.mesquitewebsite.com lou

    Great tutorial!

    I have one little problem, prob something I am doing..
    Everything seams to work great…. but the record doesn’t actually get added to the database.
    Checked data connections.. checked that all fields are correct, checked js code against your tutorial… can’t seem to figure out why it’s not actually adding the data (even though it returns as successful. Any ideas?

  • http://www.arifhossen.wordpress.com Mohammad Arif Hossen

    Thank you very much. I have solved my problem according to ur given concent and example.

  • Pingback: Using jQuery and AJAX to select, insert and delete from your database using PHP/MySQL « BrightSky | WordPress Design & Development in Dublin, Ireland

  • http://Yourwebsite... raremon

    Question: if I have this kind of scenario..

    how can I extract data from both input text on one ajax call? thanks in advance!

  • http://Yourwebsite... Andrés Botero

    Hello, Ryan.

    Your example is exactly what I was looking for, but I have an issue. Before, I’d like to state that, while I know this shouldn’t be of your concern, I’d greatly thank you if you can help me out.

    I took all what you typed, modified it to meet my needs and saved it (with gedit) accordingly. I’m on Ubuntu 9.10, and I installed Apache, PHP and MySQL in order to try it locally before deployment.

    While I saved all my files with the default character encoding of gedit (UTF-8), whenever I use the AJAX solution (PHP-only is not affected), I’ll get weird characters stored in my database whenever I try to use a spanish accent, like á, é, í, ó, ú. The content-type charset (HTML meta tag) is UTF-8 as well.

    Do you happen to know what might it be? I can give you all the files and the database information (utf8_general_ci), so that you see that I always use UTF-8 for everything.

    I hope you can help me with this. Thank you very much in advance.

  • http://Yourwebsite... Scott

    Thanks for the post! I too am just looking to use JQuery for a form, and am somewhat confused by all the functions and ()’s everywhere! But it looks less and less like that everyday and has alot of great functionality. Thanks again.

  • http://Yourwebsite... chris

    Very nice script, i am going to try this out

  • http://Yourwebsite... meme

    now is the time for all good man now is the time
    fr all

  • http://Yourwebsite... King mena

    i really appreciated , its wonderful code :)

  • http://Yourwebsite... Mohsen

    this is a very important tutorial, thanks a lot :-)

  • http://Yourwebsite... Brian

    How do you return the mysql_error()? Using your form I’m able to populate data on mysql, but in the event the mysql insert fails how does the user know this? In your example as long as ajax.php exists the ajax call is a success, however, we are not sure the mysql insert worked…thanks.

  • JeanJean

    Hello, first of all thanks for your script :p

    I have one question, where should we configure the database connection with this script ?

    Thanks

  • http://www.gerbenvanerkelens.com Gerben van Erkelens

    Can I put the javascript also in an external (functions.js) file instead of in the page where all the forms are in?

    And is it possible to use this script on multiple forms on a page?

  • Thorsten

    Careful, in PHP the [quote] $fname = htmlspecialchars(trim($_POST['fname'])); [/quote] is by far not enough or even senseful.
    You need the mysql_real_escape_string function, or use htmlentities, which could mess up a lot though.

  • http://tattoos4everybody.com Free tattoo designs

    I came across your article, i think your blog is awsome, keep us posting.

  • http://www.1erpsystem.com @ng

    if i insert a ‘&’ character in fname textfield, it will just save the word before ‘&’ .
    in example :
    fname value is fast&go .
    i save it with
    htmlspecialchars(addslashes($_POST[fname]));
    the outpu will be : “fast” only.

    how i can save the full word (fast&go) ?

  • http://Yourwebsite... Faron

    Nice work…thanks for the help!

  • http://Yourwebsite... Lui

    so what if the server had an error connecting or query’ing the code seems to echo success no matter what how do I implement error handling.

  • http://Yourwebsite... thompcha

    Thanks, this in nice and clean an easy. Just what I was looking for.

  • http://www.contussupport.com/web-development.php Php Programmer

    This is a great tutorial! It will definitely come in useful.

  • http://Yourwebsite... userblocked

    Thanks for this great tutorial.
    I have some queries about it, what if I did first validated the fields in the form, on what part will I insert the codes to call the ajax.php?

  • http://Yourwebsite... Leon

    This is a great tutorial. I get something from here. Much appreciated.
    Thanks

  • http://Yourwebsite... Dutchman

    I was looking for so long for a script like this, because I know a very little of Jquery and wonder how do I get the data in my database.

    Thank you

    The dutchman

  • http://Yourwebsite... jeff

    what will be the jquery part if we want to upload file with this form ?
    waiting for your reply…..

  • http://Yourwebsite... Peter

    Thank’s a lot! Just like what Mohsen said, This is very important tutorial.

  • http://www.advenser Advenser Engineering Services

    Great Advices. i really appreciated

  • http://lockyourpicz.com share picture

    You wouldn’t think it but I’ve wasted all day digging for some articles about this. You’re a lifesaver, it was an beneficial read and has helped me out to no end. Cheers!

  • http://cihip.com cihip

    Use jQuery To Submit Form To PHP/MySQL post for thanx.

  • http://www.marksoftsolutions.com Marco

    About the use of accents, I use the following in the js file:

    var myVal = urlencode($(‘#mytextarea’).val());

    $.post(“index.php?action=createfd”,
    {
    theVal: myVal},function(){alert(‘done’);});

    And in my PHP code I use (for storing it to the database in an ISO field):

    valToDb = utf8_decode(urldecode($_POST ['theVal']));

    If my field in the DB is UT8_unicode I get the value as simple as this:

    valToDb = urldecode($_POST ['theVal']);

    Hope it is useful for you (I spent some hours to find this solution).

  • http://www.ara-bee.com Alaa

    1st i would like thank u about this .

    2nd can u put demo files to see and download .. coz the explanation only u knw give confuse

    3rd i would like to follow ur website always .. coz its very useful

    Alaa
    from Palestine

  • http://armandecastro.wordpress.com ARMAN G. DE CASTRO

    I COMBINED THE POST AND THE SERIALIZE FUNCTION
    WITH THE RETURN MESSAGE FROM THE URL.

    $(document).ready(function(){
    $(“form#submit”).submit(function() {
    var str = $(“form#submit”).serialize();
    $.ajax({
    type: “POST”,
    url: “ajax.php”,
    data: str,
    success: function(msg){
    $(‘form#submit’).hide(function(){$(‘div.success’).fadeIn();});
    $(“.success”).prepend(msg);

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

    visit my website: http://armandecastro.wordpress.com

  • http://www.rackwise.com/index.php/features/data-center-optimization data center optimization

    Yet another fantastic post, always great to visit your website! Keep at it!

  • http://howtobbq.org/ Brandie Bucek

    The catchy webpage together with the intriguing posts. You give the wonderful facts that many people don’t know prior to. most of one’s contents are make me have more information. it can be incredibly diverse. I was impressed with your web page. Never be bored to go to your web site once again. Have the great day.Maintain enjoyed your blogging.

  • http://golfcartbags.us/ Roger Willmott

    “Hello,I appreciate reading through as a result of your weblog, I wished to go away a small remark to assist you and wish you a beneficial continuation. Wishing you the finest of good luck for all of your blogging efforts.”

  • http://Yourwebsite... sabby

    Wow great tutorials i like it very much…………..this help me……….great

  • http://www.incisivepoint.com Robby

    That’s jQuery “write less do more”, nice code anyway…

  • http://webhostinggr.blogspot.com/ Kaycee Rosaro

    Very Nice website. I just finished mine and i was looking for some design ideas and you gave me a few. Did you develop the website alone?

    Cheers

  • http://wedding-slideshows.net Wedding Slideshow

    Hello, just found you through Yahoo. The site looks great and i’ll be sure to come back occassionally.

  • http://www.adobetricks.com Lucy

    The best thing of the internet is that i can find things that i do not know about but at the same time interesting.

  • http://wedding-slideshows.net Wedding Slideshows

    Awesome post and must say it got my attention. I was browsing online and saw your site and am glad i found it.

  • http://www.photographycoursestoronto.com digital photography courses

    Bookmarked, I love your blog! :)

  • http://dataentryjobssite.com make money at home

    good post, added you to my RSS reader.

  • http://www.twitter.com/HowardFrelow Howard Frelow

    Very usefull article can i mention this on my blog? Thanks

  • http://Yourwebsite... Peter

    Excellent tutorial, got it working in Safari, Firefox and Chrome, but IE 8 does not submit anything???

    Any idea?

  • http://dartstarter.onsugar.com/Soft-Tip-Darts-11871407 Matt G

    Thanks for posting, I like this blog!

  • http://workathomeisgreat.tumblr.com/ Jeane Hollingworth

    I really like your writing style, good info , regards for putting up : D.

  • http://www.deletethissite.com Dewitt Koepnick

    Love your site man keep up the good work

  • http://catawowlevelguide.doodlekit.com/ Justine Hatori

    some genuinely nice and utilitarian information on this web site , also I conceive the layout has got excellent features.

  • http://wowcataguide.wordpress.com/ Samuel Darvile

    You have mentioned very interesting details ! ps decent site.

  • http://lxcblog.com/ LxC BLOG

    Hello,

    I have similar posts on JQuery. Sliders, long polling etc… Check it out http://lxcblog.com/
    Let me know if you like them.

    Thanks for sharing.