Here is a sample code to use ajax:
Lets say you have a field that you want to update the db every time someone insert info there without refreshing the page or going to another page.
So the html will look like:
[code]
<input type=”text” name=”field1″ id=”field1″ onchange=”update_field()”>
[/code]
This is very basic input type.
Now to the javascript:
first we need to call to the ajax libary:
[code]<script type=”text/javascript” src=”zxml.js”></script>[/code]
now we will create the update_field() function:
[code]function update_field(){
var field1 = document.getElementById(”field1″);
var Str = “update.php?field=” + field1;
var oXmlHttp = zXmlHttp.createRequest();
oXmlHttp.open(”get”, Str , true);
oXmlHttp.onreadystatechange = function () {
if (oXmlHttp.readyState == 4) {
if (oXmlHttp.status == 200) {
save_info(oXmlHttp.responseText);
} else {
save_info(”An error occurred: ” + oXmlHttp.statusText); //statusText is not always accurate
}
}
oXmlHttp.send(null);
}[/code]
on this function we send the value of the field to a php file. On update.php we will update the the db with some php code:
[code]
$sql = “update tbl_field set field=$field”;
[/code]
Now the php return a message we need to take it and dispaly it on a div. First we will create a div on the body section:
[code]<div id=”php_message”></div>[/code]
then we will create a function save_info that we are calling it from update_field() after the php sent 400 code status (meaning everthing is ok)
[code]
function save_info(sText) {
var php_message = document.getElementById(”php_message”);
php_message.innerHTML = sText;}
[/code]
and that’s it! easy!
====================================================[ END ]====