Jump to content

AJAX - a basic start and working example


alpine

Recommended Posts

I see a lot of questions and general questioning around AJAX and what it is, how to do it, is frameworks nessesary etc.
This example might be a fairly easy start for those that are new to using the AJAX method, it's a cut and paste example and should get you started fiddeling on your own.
There are many ways of doing it, this is just one.

Let's start with the mandatory javascript file: [color=red]ajaxrequest.js[/color]
This must be included in your main file head section like any other javascript files (see further down in index.php for an example) and is the part that makes the magic happen without reloading the entire page.

(Note: Read comments)
[code]
// start ajaxrequest.js


// Following is a javascript function that makes a httprequest - AJAX. This is the AJAX bit and all that is needed in that manner.
// Only in this one we won't be using XML in our response, we will accept and handle
// pure text and html and display this response directly to the user within the
// desired <div id> tags. It can even be used to include pure html files as a substitute
// solution to the "old" frames method where as no php or other scripting language is nessesary on the server.
// but use it with care - it is not a search engine supported method and indexing will fail. Workaround for this is not included here

function MyAjaxRequest(target_div,file,check_div)
{
var MyHttpRequest = false;
var MyHttpLoading = '<p>Loading...</p>'; // or use an animated gif instead: var MyHttpLoading = '<img src="loading.gif" border="0" alt="running" />';
var ErrorMSG = 'Sorry - No XMLHTTP support in your browser, buy a newspaper instead';

if(check_div)
{
var check_value = document.getElementById(check_div).value;
}
else
{
var check_value = '';
}



if(window.XMLHttpRequest) // client use Firefox, Opera etc - Non Microsoft product
{
try
{
MyHttpRequest = new XMLHttpRequest();
}
catch(e)
{
MyHttpRequest = false;
}
}
else if(window.ActiveXObject) // client use Internet Explorer
{
try
{
MyHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
MyHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
MyHttpRequest = false;
}
}
}
else
{
MyHttpRequest = false;
}



if(MyHttpRequest) // browser supports httprequest
{
var random = Math.random() * Date.parse(new Date()); // make a random string to prevent caching

var file_array = file.split('.'); // prepare to check if we have a query string or a html/htm file
if(file_array[1] == 'php') // no query string, just calling a php file
{
  var query_string = '?rand=' + random;
}
else if(file_array[1] == 'htm' || file_array[1] == 'html') // calling a htm or html file
{
  var query_string = '';
}
else // we have presumable a php file with a query string attached
{
  var query_string = check_value + '&rand=' + random;
}


MyHttpRequest.open("get", url_encode(file + query_string), true); // <-- run the httprequest using GET


// handle the httprequest
MyHttpRequest.onreadystatechange = function ()
{
if(MyHttpRequest.readyState == 4) // done and responded
{
document.getElementById(target_div).innerHTML = MyHttpRequest.responseText; // display result
}
else
{
document.getElementById(target_div).innerHTML = MyHttpLoading; // still working
}
}
MyHttpRequest.send(null);
}
else
{
document.getElementById(target_div).innerHTML = ErrorMSG; // the browser was unable to create a httprequest
}
}
// end of "AJAX" function


// Here follows a function to urlencode the string we run through our httprequest, it has nothing to do with AJAX itself
// If you look carefully in the above httprequest you se that we use this url_encode function around the file and query_string
// This is very handy since we are using GET in our httprequest and for instance
// any occurrance of the char # (from textboxes etc) will brake the string we are sending to our file - we don't want that to brake!
// It will also convert spaces to +

function url_encode(string)
{
var string;
var safechars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/-_.&?=";
var hex = "0123456789ABCDEF";
var encoded_string = "";
for(var i = 0; i < string.length; i++)
{
var character = string.charAt(i);
if(character == " ")
{
encoded_string += "+";
}
else if(safechars.indexOf(character) != -1)
{
encoded_string += character;
}
else
{
var hexchar = character.charCodeAt(0);
if(hexchar > 255)
{
encoded_string += "+";
}
else
{
encoded_string += "%";
encoded_string += hex.charAt((hexchar >> 4) & 0xF);
encoded_string += hex.charAt(hexchar & 0xF);
}
}
}
return encoded_string;
}

// end .js file
[/code]


Now, below is our main file that we want to use AJAX in, it consists of 3 examples:
onload, a href and a textfield

This file must include the above javascript file to get it working.

All results from the httprequest will be displayed within the <div id="main"></div> tags (called "main" as an example).
You can apply as many result divs as you like, just name the desired result div when you call MyAjaxRequest

Example:

onclick="javascript: MyAjaxRequest('the_result_id', 'file.php?blah=$blah')"
onclick="javascript: MyAjaxRequest('the_result_id', 'file.php?username=', 'textfield_id_to_check_becomes_username_value')"

(compress [color=red]s c r i p t[/color] in line 6) [color=red]index.php[/color]
[code]

<!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" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-15" />

<s c r i p t type="text/javascript" language="javascript" src="ajaxrequest.js"></script>

<title>AJAX Test</title>
</head>

// example on a body onlad call
<body onload="MyAjaxRequest('main','hello.php?state=onload')">


<div id="main"> <!-- all results appears dynamic within the div like right here --> </div>


// an ordinary link example to call the backend file
<p><a href="javascript: MyAjaxRequest('main','hello.php?state=test')">Click to Test</a></p>


// check the contents of the text field against the backend file "hello.php" each time the textfield looses its focus (onblur)
// in some occaitions you might want to use the onkeyup attribute etc.
<p>
<input type="text" id="username_field" name="username" onblur="javascript: MyAjaxRequest('main','hello.php?username=','username_field')">
</p>



</body>
</html>

[/code]



And here follows an example of a "backend" file that we send our AJAX request to via the javascript and gets all the desired responce from - note that whatever responce the below file echo's out will be dislayed in the above index file within the div tags.

Remember, this file consists of just plain php as you know it and all variables comes to it as ordinary GET variables via the first javascript function.
This means that you also can run mysql querys etc. within this file and all results will be echoed out in the above index file without reloading the index file at all.

Examples on query strings made from this actual example is:

http://www.yoursite.net/hello.php?username=dude&rand=629529368494.02
http://www.yoursite.net/hello.php?state=test&rand=402355731057.21826
(the rand part is just to help us to prevent caching and is added in the .js file)

In the example this file is called: [color=red]hello.php[/color]
[code]
<?php

header("Content-Type: text/html; charset=ISO-8859-15");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");


if(!empty($_GET['username'])) // we have a textfield check
{
if($_GET['username'] == "dude")
{
  echo "<p>Correct</p>";
}
else
{
  echo "<p>Username mismatch: <b>".htmlspecialchars($_GET['username'])."</b> is not correct</p>";
}
}

// or a switch example

switch ($_GET['state'])
{
case 'test':
echo "<p>This is a test</p>";
break;

case 'onload':
echo "<p>Hello World</p>";
break;
}

?>
[/code]

Hope this comes in handy for anyone keen on using ajax, i've put it working live here: http://www.vdiag.com/ajaxtest/
I probably could do some more detailed explanation and give more examples on how to use it, but i hate looong tutorials myself.
This is overcoming for anyone that's already been doing som programming, and should point you in the right direction.
Link to comment
Share on other sites

Guest
This topic is now closed to further replies.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.