pTutorial

New way to learn Programming

Ajax PHP MySql examples

Retrieve data from data base using Ajax

Following Ajax example retrieve or fetch the data from the database using Ajax without refreshing whole webpage or requesting new web page.

Type Raebareli to fetch the data from the database because raebareli is the name of city that is used in the query so it will fetch the data where city name is raebareli, you can make own query easily by using this example.

Name of Database

uk

Name of table

persons

Query

select *from persons where city='$a'

Ajax PHP MySql Example

<!--index.html-->

<html>
<head>
<script>
var request;
function db()
{
var v=document.frm.ct.value;
var url="php-connect.php?val="+v;

if(window.XMLHttpRequest){
request=new XMLHttpRequest();
}
else if(window.ActiveXObject){
request=new ActiveXObject("Microsoft.XMLHTTP");
}

request.onreadystatechange=getInfo;
request.open("GET",url,true);
request.send();
}

function getInfo(){
if(request.readyState==4){
var val=request.responseText;
document.getElementById('kk').innerHTML=val;
}
}

</script>
</head>
<body>
<h1>This is an example of ajax with database</h1>
<h3>Type raebareli and click anywhere else on the screen or press tab key</h3>
<form name="frm">
<input type="text" name="ct" onKeyUp="db()">
</form>

<span id="kk"> </span>

</body>
</html>

PHP FILE

<?php
//php-connect.php
$e=mysql_connect("localhost","root","") or die("con fail");
$f=mysql_select_db("uk",$e) or die("cont fail 2");

$a=$_GET['val'];
$qc="select *from persons where city='$a'";


$data1 = mysql_query($qc)or die(mysql_error());
echo "

Data from database

"; while($row = mysql_fetch_array($data1)) { echo $row['id']."
"; echo $row['name']."
"; echo $row['City']."
"; echo "
"."
"; } ?>

Download and execute instruction

First you have to download this example and after that create a database named "uk" and import the uk.sql (provided in the download folder) file into the uk Database and execute this example.

See Also


QUOTES OF THE DAY

Tomorrow life is too late, live today.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER