Difference between revisions of "6CS028 Workshop - Ajax"

From mi-linux
Jump to navigationJump to search
Line 1: Line 1:
[[Main Page]] >> [[Web Application Development]] >> [[Web Application Developpment - Workbook|Workbook]] >> Week 05
+
[[Main Page]] >> [[CP3207|Web Application Development]] >> [[Web Application Developpment - Workbook|Workbook]] >> Week 05
  
 
The web page:
 
The web page:

Revision as of 15:15, 22 May 2009

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:

// ajax.js

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:

<?
  // ajax.php

  // 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

?>