6CS028 Workshop - Ajax

From mi-linux
Revision as of 14:31, 22 May 2009 by In9352 (talk | contribs)
Jump to navigationJump to search

Main Page >> Web Application Development >> Workbook >> Week 05

The web page:

<HTML>
  <HEAD>
    <TITLE>Test Ajax</TITLE>
    <SCRIPT type="text/javascript" src="ajax.js"></SCRIPT>
  </HEAD>
  <BODY>
    Check name: <INPUT type="text" id="a_name" onblur="send_request(this);">
    <DIV id="div_result"></DIV>
  </BODY>
</HTML>

The Javascript file:

var liveSearchReq = false;
var name = "";
	
var isIE = false;
// on !IE we only have to initialize it once
if (window.XMLHttpRequest)
{
	liveSearchReq = new XMLHttpRequest();
}

// +----------------------------------------------------------------------+
// | Init HTTP object
// +----------------------------------------------------------------------+
function initliveSearchReq()
{
  if(window.XMLHttpRequest)
  {
    // Firefox et autres
  	liveSearchReq = new XMLHttpRequest();
  } 
  else if(window.ActiveXObject)
  {
    // Internet Explorer 
  	try
    {
  		liveSearchReq = new ActiveXObject("Msxml2.XMLHTTP");
  	}
    catch (e)
    {
      liveSearchReq = new ActiveXObject("Microsoft.XMLHTTP");
  	}
  } 
}
// +----------------------------------------------------------------------+
// | Send request
// +----------------------------------------------------------------------+
function send_request(t)
{
  // Get user input
  name = t.value;
  if(name!="")
  {
    // Create HTTP object
    initliveSearchReq();
  	
  	// Set function to handle response
  	liveSearchReq.onreadystatechange= DisplayResult;
  	
  	// Send request
  	liveSearchReq.open("GET", "ajax.php?name=" + name);
  	
    // Finish transaction
  	liveSearchReq.send(null);
  }
  else
  {
	  var  sh = document.getElementById("div_result");
	  sh.innerHTML = "Please enter value";    
  }
}
// +----------------------------------------------------------------------+
// | Handle response
// +----------------------------------------------------------------------+
function DisplayResult()
{
	if (liveSearchReq.readyState == 4)
  {
		var  sh = document.getElementById("div_result");
		sh.innerHTML = liveSearchReq.responseText;
	}
}

The PHP file:

<?

  // Get value coming from request
  $name = $_GET['name'];

  // Connect to DB
  
  // Check if name exists in table
  
  if($name=="Alix")
    echo("This name is in the database");
  else
    echo("This name is NOT in the database :(");
  
  //Close connection

?>