Insert Data Into MySQL: jQuery + AJAX + PHP

Video tutorial illustrates insertion of data into MySQL database using jQuery and PHP, using AJAX method i.e., $.post() method of jQuery.

There are 5 shortcuts for AJAX in jQuery, ultimately calling ajax method, and by default configured to have different parameters.
$.get
$.post
$.getJSON
$.getScript
$.load

Tutorial Theme: Insert Data Into Database Without Refreshing Webpage

In this tutorial we’ll illustrate $.post method of jQuery.

HTML code
index.html


Insert Data Into MySQL: jQuery + AJAX + PHP


Here we have a form with an id called myForm, which has 2 input box.
A button with id sub. And a span tag with an id of result.

Once the user enters his/her name, age and hits Save button, the information will be sent to userInfo.php file present in the action field, via post method.

Using AJAX technique, we would make sure the form doesn’t redirect to userInfo.php file after the submission, and we’ll display appropriate message to the user on index.html file itself after the user entered values has been processed by userInfo.php file.

Database Connection code: PHP
db.php

< ?php
   $conn = mysql_connect('localhost', 'root', '');
   $db   = mysql_select_db('test');
?>

We connect our application to mysql server using the user name root( and we leave password field empty, as we haven’t set any password to it on our machine ).
Also select the database called test.

Create Database called test.
A table user inside the database test.
user table has 2 fields called name and age.

Processing Page code: PHP
userInfo.php

< ?php
   include_once('db.php');
  
  $name = $_POST['name'];
  $age = $_POST['age'];
  
  if(mysql_query("INSERT INTO user VALUES('$name', '$age')"))
    echo "Successfully Inserted";
  else
    echo "Insertion Failed";
?>

Once the user hits the Save button of our form in index.html, the information is being sent to userInfo.php

Where the user entered values are being copied to local variables $name and $age.
Next a simple MySQL query is formed to insert the data into the table user.

Using mysql_query() standard php function, the MySQL query is being processed.
Using if else conditional statements, we check if the process was successful or failed. Based on which we echo the result.

jQuery code: AJAXing
my_script.js

$("#sub").click( function() {
 $.post( $("#myForm").attr("action"), 
         $("#myForm :input").serializeArray(), 
         function(info){ $("#result").html(info); 
  });
});

Once the user clicks on the button with the id sub, $.post() method is invoked.
$.post() is a shortcut to $.ajax() method.

General Syntax:
$.post( ‘pass_data_to_this_url’, ‘data’, ‘callback_function’ );

We fetch the URL from myForm form, from its action attribute.
Serialize all the user entered input’s.
SerializeArray makes the input into property: value pair.
After the data is passed to the url and is being processed, the result will be returned back to the callback function and is caught in info variable, and is inserted inside the span tag using html() method – which is similar to innerHTML() method of JavaScript.

jQuery code: Disable Form Redirection
my_script.js

$("#myForm").submit( function() {
  return false; 
});

Select the form and make sure to return false upon submission.

jQuery code: Clear Input Fields
my_script.js

function clearInput() {
 $("#myForm :input").each( function() {
    $(this).val('');
 });
}

Write a custom function. Select the input fields and set each of its value to none or empty.
Call this function once the user clicks the submit button.

Full jQuery code
my_script.js

$("#sub").click( function() {
 $.post( $("#myForm").attr("action"), 
         $("#myForm :input").serializeArray(), 
         function(info){ $("#result").html(info); 
   });
 clearInput();
});

$("#myForm").submit( function() {
  return false; 
});

function clearInput() {
 $("#myForm :input").each( function() {
    $(this).val('');
 });
}

Note that, we have called clearInput() function inside the click event of #sub.

Video Tutorial: Insert Data Into MySQL: jQuery + AJAX + PHP



YouTube Link: https://www.youtube.com/watch?v=gvGb5Z0yMFY [Watch the Video In Full Screen.]



Note:
You have to implement addslash and stripslash or any other methods into your PHP code, to secure your script from SQL Injection.

If the PHP returns json encoded data, then we need to use json in $.post() method as follows:

$("#sub").click( function() {
 $.post( $("#myForm").attr("action"), 
         $("#myForm :input").serializeArray(), 
         function(info){ $("#result").html(info); },
         "json" );

But in our example, we are not returning json encoded data from userInfo.php file, so we do not specify encoding information in $.post() method.

View Comments

  • Hello there, I came on your site because of I saw your YouTube for the first time.

    First I liked the tutorial, or how it will be called... I am new to JQuery, JSON, AJAX etc

    But second, when I clicked on more items to view and got a list of them, my browser got jammed, because of all your video's are set on autoplay. Isn't it? They all started anyhow...

    Maybe a good idea to NOT set them autoplay? ;)

    • Thanks for feedback ..

      I had noticed the autoplay before, but it was a fault with the wordpress plugin I was using. I had raised ticket with the author, but had no reply ..so I fixed it myself few minutes back.

      thanks again ..

  • Hi, I liked your tutorial, but I have run into an issue which is my form keeps redirecting to the php file. The data is saved in the db, but I cannot stop the redirection, plz any help would be greatly appreciated! I post my code:

    <input type="text" id="placemarkName" name="placemarkName" placeholder="Name:"/

    Save

    Cancel

    And the my_script.js

    $("#savePlacemark").click( function() {
    $.post( $("#savePlacemarkForm").attr("action"),
    $("#savePlacemarkForm :input").serializeArray();
    });
    clearInput();
    });

    $("#savePlacemarkForm").submit( function() {
    return false;
    });

    function clearInput() {
    $("#savePlacemarkForm :input").each( function() {
    $(this).val('');
    });
    }

    Thx!!

  • wot of if i want to clear only one texbox rather than all the form
    function clearInput() {
    $("#myForm :input").each( function() {
    $(this).val('');
    });

    • Give id to the textbox you want to clear, and then instead of $(this).val(''); put $('textBoxId').val('');

      That's it. Hope that helps

  • Great Video and documenation man !

    i still have a question:

    is is possible to first search for a name.

    the result displays the name and age with a additional field where i could add
    a 2 for exampel which adds the 2 years to the exististing 25, so the result ist 27
    which must be stored in den db?

    many thanks in advanced

    greetings from germany
    mike

      • @Satish, do you have time to develop that for me ? I would pay for it.
        The idea ist to make a stock inventory. i already programmed a solution in ms access but i want to get it work over a webbrowser.

        to do:
        - scan a articlenumber
        - the Article must show with actual stock or alert if not found
        - beyond a field where i could add the actual lot
        - next article

        greeting
        mike

  • satish,

    best tutorial on using ajax to post data to mysql. i have looked all over the internet to learn how to do this. i plan on mentioning your blog and this post in an upcoming entry in my blog.

    one thing that i would like to see, a link to download the files (code) in a .zip format. i got a little confused at first as you progressed with each file.

    again, great job!!!

    cheers,

    -e