This function runs an AJAX call using GET allowing us to send parameters (object) to a file (string) and launch a callback (function) when the request has been ended.
function ajax(file, params, callback) {
var url = file + '?';
// loop through object and assemble the url
var notFirst = false;
for (var key in params) {
if (params.hasOwnProperty(key)) {
url += (notFirst ? '&' : '') + key + "=" + params[key];
}
notFirst = true;
}
// create a AJAX call with url as parameter
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callback(xmlhttp.responseText);
}
};
xmlhttp.open('GET', url, true);
xmlhttp.send();
}
Here's how we use it:
ajax('cars.php', {type:"Volvo", model:"300", color:"purple"}, function(response) {
// add here the code to be executed when data comes back to this page
// for example console.log(response) will show the AJAX response in console
});
And the following shows how to retreive the url parameters in cars.php
:
if(isset($_REQUEST['type'], $_REQUEST['model'], $_REQUEST['color'])) {
// they are set, we can use them !
$response = 'The color of your car is ' . $_REQUEST['color'] . '. ';
$response .= 'It is a ' . $_REQUEST['type'] . ' model ' . $_REQUEST['model'] . '!';
echo $response;
}
If you had console.log(response)
in callback function the result in console would have been:
The color of your car is purple. It is a Volvo model 300!