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


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


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

  • Nice tutorial. I coded your example using PostgreSQL instead MySQL. It gave me some problems for some hours 'cause I used the same table name and the field name "name". Those are reserved words and you need to escape them in order to use them.

    Anyway, I see you put the script elements after the form instead inside the head element. Playing around with it I saw that moving around just the element that include my_script.js the form is redirected to userInfo.php. To avoid that just put the first jQuery blocks inside a ready function like this:

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

    clearInput();
    });

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

    The function clearInput() can be outside. Then you can put all the script elements where they ought to be:

    Insert Data Into MySQL: jQuery + AJAX + PHP

    And that's it!

  • @Nelson, Thanks for sharing this with us.

    But writing $(‘#myForm’).submit(function() { return false; }); outside $(document).ready(); won't have any problem, as .submit will be invoked once the user clicks on the submit button of #myForm form.

    Look at the video. I'll shown it working.

    Nevertheless what you're telling is also right and it also works.

    Thanks for sharing it with us..am sure, it'll help someone.

  • your good satish, youve done a simple but verry helpfull tutorial it helps alot dude, cool..! keep ti up, thank you! very much!

    • @Lawko, Check with the database fields. Make sure your script is properly/correctly connected with the database.

      And do not copy paste from above article. Watch the video and work along with me. It must work.

      Check with the SQL syntax, the quotation marks etc ..these are the common places for errors.

    • @Emrah, Mistake is in your eraysoft.....js file
      Make sure the return false is inside click event of your button.

      Orelse write everything inside $(document).ready( function() { //all your code; });

      This will solve your problem.