AJAX database update with PHP and JQuery

AJAX database update with PHP and JQuery

Often web developers love to use AJAX in their applications because of the elegance in use and the beautiful interface options. AJAX update can be a very useful tool to modify or access database tables without render of pages from the server or navigating to a different page. In this way, your web application becomes smart and sleek. Most of all, the numerous page loads can be avoided; thus making the user’s experience much easier.

Some of the very common examples of mysql database update and modifications using AJAX and a PHP program are like buttons of Facebook, post buttons, tweet buttons from Twitter, +1 of Google, voting systems, rating systems and more.

Have you ever dreamt of getting one of these on your website? Well, in this article I’ll describe some very easy steps to follow in subjects like MySQL AJAX JQuery that will help you achieve your dreams.

PHP and AJAX can create milestones for web developers. One of the strongest JavaScript libraries – JQuery, helps in this motive. When punched with JQuery, the total application becomes awesome to see and use.

Remember that all of them – PHP AJAX JQuery need to be coded separately and punched together. This way your approach would be easier than anything. First, the JQuery code is done. So, we create some mark-up and do the designs. Let us consider that the following text box gathers a string and stores it in the database instantly upon the click of the button.

AJAX PHP database update without page navigation

So, considering the above mark-up and styling is done we proceed to the JavaScript part. Within the script tags, we define the AJAX POST method for transferring the data from this HTML / PHP file to the server side PHP file for database jobs. This transfer is asynchronous and does not require the browser to navigate over to some other page.

Implementing AJAX

Now, if we closely look at the AJAX POST method, we can clearly have an idea what it is all about. Have a close look so that you could manipulate this information later to suit your own needs. The first argument is the URL. This should be the filename that you are sending the data to. Next is the JSON variable pair.

The second variable is the JavaScript variable from this file that collects the value. The first variable stores the value and is sent to the URL location for usage. One very important message at this point is that always remember to keep the first variable name here and the variable that collects the $_POST call in the URL file same. If the names are not same, the procedure might not work correctly.

After this is the call back function. You could just ignore this if you’re not so expert at your JQuery skills. (There is a fourth argument also. This argument states the data-type of the call-back function’s parameter. By default it is HTML.) For the moment, you need not worry about the third and the fourth parameter.

Here’s the code example of a POST method call and AJAX database update –

<div id="c">
<input id="text1" type="text" name="text1" /> 
<input id="submit" type="submit" name="submit" value="SAVE IT" />
</div>
<div id="cn">
</div>

Now we declare the JQuery code to make a POST call

<script type="text/javascript">
$(document).ready(function () { 
$('#submit').click(function(){
var ths = this;
var str = $(ths).siblings("#text1").val();
$.post("saveData.php", {t:str}, function(value){
$(ths).parent("#c").fadeOut("fast");
$(ths).parent("#c").siblings("#cn").html(value);
});
});
});
</script>

Note that the POST method calls “saveData.php”.This is the PHP file that receives the value and updates the database. Here’s the code for that –

$t = $_POST['t'];

$link = mysql_connect(servername, username, password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(databasename, $link);

// Insert the data
$query2="INSERT INTO p_a_j(scrap) VALUES('$t')";
$results2 = mysql_query($query2, $link)
or die(mysql_error());

if(mysql_affected_rows()&gt;=1){
echo '<span>You entered'.$t.'</span>'.
'Database updated'.
'<a href="index.html">Try this again</a>'; }

Just try the demo for better understanding

So, when the POST function is set, we just bind a .click function to the submit button and collect the data through jQuery.

Now, as soon as we type some text and hit the button, the value is taken and the control switches to the URL PHP file. Here, in this file the $_POST value is collected and database actions are performed accordingly.

That’s it! We’re done. It is as simple as that. AJAX and MySQL can do even more. Some internet applications just don’t store these values; they show some kind of a result or confirmation. Like maybe the number of likes gets increased or the rating gets changed instantly. These are all to do with the call-back function. If you are all ready for that stage then jump on to the tutorial Updating Web page content without page navigation .

Happy coding!!

  • obvioquesigmailcom

    Hello, i think your download link is broken.,
    Can you upload it again please?
    Thanks for your tutorial.

    • Sorry @obvioquesigmailcom:disqus .. Actually the link was in .rar instead of .zip. Thanks for the notification. I hope this helps

  • Alagu Sundar

    really nice article. nice explanation. Thanks for sharing this information.
    http://www.cavinitsolutions.com/

  • Pingback: JQuery POST method in PHP - A 100 Web Solutions()

  • Dean Jones

    Hi Nice tutorial. Its simple to understand
    http://www.techrecite.com/

  • Zi

    Your Demo:

    Warning: mysql_connect() [function.mysql-connect]: Access denied for user ‘kaustav’@’localhost’ (using password: YES) in/home/a100wkoh/public_html/projects/ajax-database-update/saveData.php on line 6
    Could not connect: Access denied for user ‘kaustav’@’localhost’ (using password: YES)

    • Hi Zi,
      Thanks for letting me know. That was a technical issue. Fix done. :)

  • Pingback: Emails in PHP without page navigation using AJAX -()

  • I am extremely impressed with your writing skills and also with the structure in your blog.
    Is this a paid subject matter or did you modify it your self?
    Either way keep up the nice quality writing, it’s uncommon to peer a great weblog like this one nowadays..