Thursday, 17 January 2013

jQuery Ajax Tutorial and Example of jQuery Ajax in PHP | PHP Tutorials for Beginners

What is jQuery?
jQuery is a lightweight JavaScript library whos aim is "write less, do more". As jQuery is lightweight, it is easier to load in your website and has fast responce. With help of jQuery it much easier to use JavaScript on your website.
Jquery eliminates the many lines of code which we are doing in javascript and make them available with help of single method.

What is AJAX?
AJAX stand for Asynchronous JavaScript and XML. it is used for creating dynamic and fast web pages. Since AJAX is Asynchronous, it helps in updating a part of web page with out reloading the whole page.

What About jQuery and AJAX?
The combination of jquery and ajax provide powerfull functionality. With jquery ajax you can make request for text or html from your  remote server. If data is large you can use json to receive them. After receiving ajax response we can use them in our html page.

jQuery provides some powerful set of jQuery AJAX API’s to handle AJAX requests. In normal way of making AJAX calls using JavaScript is a little bit odd as you have to first create an XMLHttpRequest object that depends on the browser and then make an AJAX call. Also sending a form data using AJAX is also bit difficult if we use normal JavaScript approach of calling AJAX.
jQuery provides simple yet powerfull functions which have extended the JavaScript AJAX methods and provide more flexible way. Let us see way of doing AJAX things in jQuery.

In this tutorial of php code for beginners we will show you how to use Jquery Ajax in your php form.
Lets start... To use Jquery Ajax we need to create two files, In first file our html php code present from where we do ajax request. in second file we process the ajax request and return the result to first page.

Step 1:- Create a school.php file and put this code in it.

<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function getdetails(){
var name = $('#name').val();
var rno = $('#rno').val();
$.ajax({
type: "POST",
url: "details.php",
data: {fname:name, id:rno}
}).done(function( result ) {
$("#msg").html( " Address of Roll no " +rno +" is "+result );
});
}
</script>
</head>
<body>
<table>
<tr>
<td>Your Name:</td>
<td><input type="text" name="name" id="name" /><td>
</tr>
<tr>
<td>Roll Number:</td>
<td><input type="text" name="rno" id="rno" /><td>
</tr>
<tr>
<td></td>
<td><input type="button" name="submit" id="submit" value="submit" onClick = "getdetails()" /></td>
</tr>
</table>
<div id="msg"></div>
</body>
</html>

In above code we are taking name and roll no of student and pass this to details.php using jquery ajax.

Step 2:- Create details.php and put the below code in it.

<?php
$name = $_POST['fname'];
$rno = $_POST['id'];

$con = mysql_connect("localhost","root","");
$db= mysql_select_db("school", $con);
$sql = "SELECT address from students where name='".$name."' AND rno=".$rno;
$result = mysql_query($sql,$con);
$row=mysql_fetch_array($result);
echo $row['address'];
?>

In above code we are getting address of student with help of his name and roll number.

Note: We can do this with help of normal coding but the difference here is we are getting result without refreshing the page and that's the magic of jquery Ajax.

Don't forget to create database named "school" and table name "students". table student contain the fields name, rno and address.

Hope this php tutorial is useful for you. Keep following www.phpcodeforbeginner.blogspot.in for more help.

34 comments:

  1. What a great article.
    Thankyou,
    AhmedBilal

    ReplyDelete
  2. Nice one! Excellent for introduction in php+jquery.

    ReplyDelete
  3. I am very glad for know basic ajax post data .

    ReplyDelete
  4. Thanks for this useful post. For more visit: examanswer24.com

    ReplyDelete
  5. Awesome post for Ajax introduction in php. For quick access of popular websites, you can try OSIpage: http://www.osipage.com

    ReplyDelete
  6. I have spent money on books and tutorials BUT this is the most Decent and easy to follow tutorial for newbies I have yet come across!

    Well Done!

    If you have anymore articles similar to this regarding Ajax/Php/jQuery please let me know.

    Regards
    kwandoa

    ReplyDelete
  7. how to use ajax to create a comment pannel,can you write tutorials about this,sir
    --signutre:ec-shalom.com

    ReplyDelete
    Replies
    1. Ya sure i will write one post for creating comment panel using ajax.

      Delete
  8. I'm very new to AJAX so my question:

    The results in the above example is passed to the div tag id="msg" to be display but what if you pull a set of data from the database. How do you take the set of date(array format) and assign to a php variable so that you cant format the data for display for example using foreach to loop through?.

    ReplyDelete
    Replies
    1. In thats case you have to use json encode decode.
      Here is the link for JSON example.
      Encoding and Decoding JSON Data in Php

      Delete
  9. This is really fantastic as a first introduction, thank you!

    ReplyDelete
  10. Nice work! Thanks

    ReplyDelete
  11. can you explain this line of code, i know this is xmlhttpRequest object but what are the parameters of this functions?

    $.ajax({
    type: "POST",
    url: "details.php",
    data: {fname:name, id:rno}
    }).done(function( result ) {
    $("#msg").html( " Address of Roll no " +rno +" is "+result );
    });

    ReplyDelete
  12. Thank You Very Much !!!
    It's my first ajax program, but please also explain this line of code.
    $.ajax({
    type: "POST",
    url: "details.php",
    data: {fname:name, id:rno}
    }).done(function( result ) {
    $("#msg").html( " Address of Roll no " +rno +" is "+result );
    });

    ReplyDelete
    Replies
    1. This is where the details.php function returns a response. The .done refers to when the request has been sent to the php and it has finished processing and delivered a result. In this code it will print "Address of Roll No *Sent to php* is *Result from php* into a div with the id 'msg'.

      Delete
  13. Nice and Fresh code, easy to understand and implement.
    Thank you dear!

    ReplyDelete
  14. thanks, useful tutorial.

    ReplyDelete
  15. sir need your help
    i have create registeration page with jquery and database table with mysql(phpmyadmin)

    how can i store the data to the database

    ReplyDelete
  16. nice post with an post

    ReplyDelete
  17. when iam runing this code it giving error plz help me it is giving
    Address of Roll no 2 is
    ( ! ) Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\wamp\www\sirProgram\details.php on line 9
    Call Stack
    # Time Memory Function Location
    1 0.0012 675960 {main}( ) ..\details.php:0
    2 0.0087 683320 mysql_fetch_array ( ) ..\details.php:9

    ReplyDelete
    Replies
    1. Don't forget to create database named "school" and table name "students". table student contain the fields name, rno and address.

      Delete
  18. Hi great tutorial! - question: How to pass a variable that isn't from html form or from a submit button, just from a simple PHP variable?

    ReplyDelete
    Replies
    1. Use one hidden field and put your value in it. After Submiting you will get you variable in next page.
      Example:-
      <\input type = "hidden" name = "my_variable" value = "$YOUR_VALUE">

      In next page you will receive it by $_POST['my_variable'].

      Delete
  19. thanks for the jquery example tutorial

    ReplyDelete
  20. You should not be using mysql function in PHP. It has been depreciated. This should be replaced with mysli or PDO. Also, why does your php page have an echo in it? The ajax submits data to the php page without actually redirecting the user there so the echo statement is redundant. You should be showing how you can send data to php using ajax and then retrieve a response in json format that can then be used by jquery on the original page.

    ReplyDelete
  21. Thanks for the great trick I like this tutorial, and I was always searching for this. I also find one simple and easy method here on this website, I hope you want to take a look at this.
    http://www.smartwebtricks.com/2013/07/Submitting-A-PHP-Form-Without-Page-Refresh.html

    ReplyDelete