Oct 26, 2011

Insert Record Into Database Using AJAX | How To Insert Data Into Database Using AJAX

In todays tutorial, I am going to teach you, HOW AJAX WORKS. This tutorial is good for people who are seeking on internet to learn AJAX with PHP and MYSQL.

I am going to share a AJAX Driven tutorial with you, in which we will insert a record in our Database through AJAX, which means data will be added into database, without refreshing the page and we will also show the added values.

So lets start this, first we need to setup a folder structure.
Make a folder and inside it, add three files,

  • index.php

  • data.php

  • ajax.gif


Now we will add basic html code into our index.php file

[html]

<body>
<div id="wrapper">
<input type="text" id="name" value="Your Name" />
<input type="button" value="Submit" onclick="addRecord()" />
<div id="propspectDiv"></div>
<table id="data" border="1" cellspacing="0" cellpadding="0" width="75" style="display:none;"></table>
</div>

</body>

[/html]

Now comes the main AJAX code.

Inside your head tag, add the following code:

[html]

<script src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">

function addRecord()
{
var term_name = $('#name').val();        //Storing the value of textbox into a variable

if(term_name == '')        //Checking for NULL
{
$('#propspectDiv').html('Enter A Valid Name');    //Prints the progress text into our Progress DIV
$('#name').addClass('error');                    //Adding the error class to the progress DIV
return;
}
else{
$('#name').removeClass('error');
$('#propspectDiv').removeClass('error'); //Removing the error class from the progress DIV
$('#propspectDiv').html('Submitting your Request.<img src="ajax.gif" />');//Prints the progress text into our Progress DIV

$.ajax({
url : 'data.php', //Declaration of file, in which we will send the data
data:{
"name" : term_name                //we are passing the name value in URL
},
success : function(data){
window.setTimeout(function(){
$('#propspectDiv').html('Your Name is added to our records'); //Prints the progress text into our Progress DIV
$('#data').css("display","block");  //Changes the style of table from display:none to display:block
$('#data').html(data);                //Prints the data into the table
}, 2000);
}
});
}
}

</script>

[/html]

Explanation:

In our AJAX function first we are storing the value of textbox in a variable.
Then we check whether the variable is not passed NULLED, if condition is satisfied, then it enters to a condition, where it adds some HTML code into progress div.

Finally we call our AJAX function, where we pass the "name" value to our file data.php through URL. data.php file echoes some values and inserts name into our database.

We call this echoed values and display it in our table.

data.php code

[php]

<?php
$name = $_REQUEST['name'];

$con = mysql_connect("localhost","root","");

mysql_select_db("test", $con);

$sql = 'INSERT INTO `test`.`name` (`ID`, `Name`) VALUES (NULL,"'.$name.'")';

if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
else{
$sqlnew = 'SELECT * from name;';
$res = mysql_query($sqlnew);
echo '<tr><th>Name:</th></tr>';
while($row = mysql_fetch_array($res))
{
echo '<tr><td>'.$row['Name'].'</td></tr>';
}
}

mysql_close($con);
?>

[/php]

Conclusion:
Here we are learning the basics of JQUERY AJAX, if you understand the main concept and the flow of AJAX with PHP, then with the help of google you can make many ajax driven programs.

Final Output:


download


download

23 comments :

  1. Welisson_goldmann16/1/12 3:51 AM

    Man I really liked your tutorial, thank you, but
    and if I want to send more fields what should I do here:

    date: {
    "name": term_name
                                         / / "Url": url name?

    ReplyDelete
  2. If you want to pass more fields to database, then just edit this code:

    data:{
    "name" : term_name,
    "extra-field1" : field1,"extra-field2" : field2
    },and so on you can continue.

    ReplyDelete
  3. Welisson_goldmann16/1/12 6:04 AM

    Thanks man, I'm really very grateful for your response.Starting today I will follow you closely! Thanks! One more thing, how  to only send data if all fields are completed?eg: if (term_name =='') & & (other_field =='') & & (another_field =='')I have trouble with the syntax validation using JavaScript.

    ReplyDelete
  4. It depends on the text input if its no blank value, then you can use this condition

    if(term_name == '') {
    }elseif(term_name2 == ''){}and so onnn

    ReplyDelete
  5. [...] Take a look at this amazing url... jquery-popup [...]

    ReplyDelete
  6. [...] Go check out this great webpage... jquery-page-loading [...]

    ReplyDelete
  7. Siavashganji4/5/12 7:55 PM

    i want add some field and if its empty ...its error ....can you explain it clearly ?!

    ReplyDelete
  8. what you are trying to say? can you explain in detail?

    ReplyDelete
  9. excellent ! :) keep it up

    ReplyDelete
  10. hi,
    thanks for this fantastic tutorial, so i would like to add a simple fade out, it's possible?

    ReplyDelete
  11. What if we want to check that the name already exists and print message accordingly?

    ReplyDelete
  12. Thanks man ... very nice tutorial

    ReplyDelete
  13. NIce......explain..

    ReplyDelete
  14. Shanmugananthan28/2/13 10:42 PM

    Thank you

    ReplyDelete
  15. Thank you so much for writing such a step by step and simple tut...I have searched so many sucking sites to learn ajax bt all were *** Thank you

    ReplyDelete
  16. hey guys, I am busy trying to add some attributes in data base and textfields using this example but when I submit using index.php takes long without example!! could you please tell me why?

    ReplyDelete
  17. after insert record, i can't see table view.

    ReplyDelete
  18. $('#data').html(data); this one not working for me :( help

    ReplyDelete