Webdesign,code & ...stuff!

Sep 25, 2009

Simple PHP-Ajax

ajax.js
//we will initialize ajax
function initAjax(){
var xmlHttp=null;
try{ xmlHttp=new XMLHttpRequest(); } // Firefox, Opera 8.0+, Safari
catch (e) {// Internet Explorer
try {xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");}
catch (e){ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); }
}
return xmlHttp;
}

function get_text(){
var simpleajax = new initAjax();
var container = document.getElementById("container");
var inputext = document.getElementById("text").value;

if(simpleajax==null)
alert("Your browser does not support Ajax");

simpleajax.onreadystatechange = function(){
if(simpleajax.readyState == 4){
container.innerHTML = simpleajax.responseText;
}
}

simpleajax.open("GET","gen_text.php?text="+inputext,true);
simpleajax.send(null);

}

get_text.php
<?php
$text = $_GET["text"];
echo strtoupper($text);//we will display the capital letters of the input
?>

index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>An example of Simple Ajax</title>
<script language="javascript" src="ajax.js"></script>
<style>

#container{
font-family:Verdana, Arial, Helvetica, sans-serif;
font-size:12px;
text-decoration:underline;
}

</style>
</head>

<body>
<input type="text" name="text" id="text" onkeyup="get_text();"/>
<div id="container"></div>
</body>

</html>

0 comments: