Pages - Menu

Monday 17 February 2014

Fetch Data using Jquey Ajax in php

Are you new in Jquery Ajax. Not a problem.

Today I will tell you How to fetch data from database using Jquery Ajax.
This tutorial is for beginners. In this tutorial I will show you how to retreive data from database use Jquery Ajax in your php with out refreshing the webpage.
we need to create two php 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.

create database named "school" and table name "students". table student contain the fields name, rno and address.

"We can aslo 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."

Enjoy the code

2 comments: