got some cool ideas for some stuff to do with ajax? alrighty then, in case you've been under a rock somewhere, AJAX is Asynchronous Javascript And XML, it lets us populate dynamic content on our website without needing to refresh the whole page. The back end in our example here is PHP.
The javascript should look similar to this:
function createRequestObject() {
var ro;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
ro = new ActiveXObject("Microsoft.XMLHTTP");
}else{
ro = new XMLHttpRequest();
}
return ro;
}var http = createRequestObject();
function sndReq(action) {
http.open('get', 'myajax.php?action='+action);
http.onreadystatechange = handleResponse;
http.send(null);
}
function handleResponse() {
if(http.readyState == 4){
var response = http.responseText;
var update = new Array();
if(response.indexOf('|' != -1)) {
update = response.split('|');
document.getElementById(update[0]).innerHTML = update[1];
}
}
} RichetHoldings.com is the personal and business website of Josh Richet.
What does that script do? Well, it creates a request object and functions that send the request and get a response, which will send help us talk to the PHP code without reloading the current page. PHP back end. When you need to call an Ajax function from a page now, you just need to call this code in an event. For simplicity's sake here's an example of an 'onclick' event:
<a href="javascript:sndReq('test')">[test]</a>What happens when someone clicks this link is that the javascript functions we first wrote will invisibly make a POST to myajax.php. the actual post (if written out in HTML) looks like this:
"myajax.php?action=test"
in myajax.php you would have code similar to this:
switch($_REQUEST['action']) {
case 'test':
/ do something /
echo "outputdiv|test is done";
break;
...
}When handleresponse() gets the "outputdiv|test is done" string back, it will seek an element with the id "output div" and change it's content text to "text is done". It would go from having html looking like this:
<div id= "outputdiv"></div>
to having html looking like this:
<div id= "outputdiv">test is done</div>
feel free to leave any questions in the comments below, as I will be back here as often as possible, and will respond.
No comments:
Post a Comment