Ajax Request

Hi, i am giving here a complete javascript code to do a ajax request that runs on any browser.This example has a text box and a div below itwhen you type a user name in text box it will fetch matching results by like query and show you rest formating you can do as u wish.

<html>
<body>

<script type=”text/javascript”>
function ajaxFunction()
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject(”Msxml2.XMLHTTP”);
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject(”Microsoft.XMLHTTP”);
}
catch (e)
{
alert(”Your browser does not support AJAX!”);
return false;
}
}
}

xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
//alert(xmlHttp.responseText);
document.getElementById(”hint”).innerHTML=xmlHttp.responseText;
}
else
{
alert(”failure”);
}
}
}

//xmlHttp.open(”GET”,”ajax.php?username=”+document.
getElementById(’username’).value,true);

//for get
//xmlHttp.send(null);   //for get

xmlHttp.open(”post”,”ajax.php”,true);  //for post
var query=”username=”+document.getElementById(’username’).value;  //for post
xmlHttp.setRequestHeader(”Content-Type”, “application/x-www-form-urlencoded”);

//for post
xmlHttp.send(query);   //for post

}
</script>

<form name=”myForm”>
Name: <input type=”text” onkeyup=”ajaxFunction();” name=”username” id=”username”>
Hint: <div id=”hint”></div>
</form>
</body></html>

This is the html file and here is a php code for server side processing-

<?php
$username=$_REQUEST['username'];
if($mysqli=new mysqli(’localhost’,'root’,”,’test’))
{
//echo”conected”;
$query=”select login from user where login like ‘”.$username.”%’”;
$query_result=mysqli_query($mysqli,$query);
while($row=mysqli_fetch_array($query_result))
{
$query_array[]=$row['login'];
}

echo $query_array[0].’ ‘.$query_array[1];
}
else
{
echo “Sorry! Unable to connect”;
}
?>



Subscribe / Share

Article by Irfan Raza

Authors bio is coming up shortly.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>