Whenever I want to do something like that, I just use one of the following 3 functions, along with the AjaxRequest library, found
here
function myGetAjaxResponse(target, url)
{
AjaxRequest.get(
{
'url':url,
'onSuccess':function(req){ target.innerHTML=req.responseText; }
}
);
}
function myGetAjaxResponseWithCallback(target, url, callbackFunc)
{
AjaxRequest.get(
{
'url':url,
'onSuccess':function(req){ target.innerHTML=req.responseText; callbackFunc();}
}
);
}
function myGetAjaxResponseWithCallback2(target, url, callbackFunc)
{
AjaxRequest.get(
{
'url':url,
'onSuccess':function(req){ callbackFunc(req.responseText, target);}
}
);
}
Here's a quick example of use. You'll just need to get the AjaxRequest library.
1. The php file that returns data we'd like to make use of
jsonDir.php
<?php
class mFile
{
public $name, $time, $size;
}
foreach (glob("*.*") as $curFilename)
{
$curFileObj = new mFile;
$curFileObj->name = $curFilename;
$curFileObj->time = date("d/m/Y - H:i", filectime($curFilename));
$curFileObj->size = filesize($curFilename);
$fileArray[] = $curFileObj;
}
printf("%s", json_encode($fileArray));
?>
2. The file that makes the request for the data and then does something with it. (I just add the names of all the files in the current directory to a drop-down list - a select element)
index.html
<!DOCTYPE html>
<html>
<head>
<script src='script/ajaxRequest.js'></script>
<script>
function byId(e){return document.getElementById(e);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}
window.addEventListener('load', mInit, false);
function mInit()
{
}
function myGetAjaxResponseWithCallback2(target, url, callbackFunc)
{
AjaxRequest.get(
{
'url':url,
'onSuccess':function(req){ callbackFunc(req.responseText, target);}
}
);
}
function onLoadBtnClick()
{
var tgt = byId('resultsContainer');
myGetAjaxResponseWithCallback2(tgt, 'jsonDir.php', jsonDataAvailableCallback);
}
function jsonDataAvailableCallback(responseText, targetContainer)
{
var resultArray = JSON.parse(responseText);
var select, option, i, n, curFilename;
select = newEl('select');
n = resultArray.length;
for (i=0; i<n; i++)
{
option = newEl('option');
option.setAttribute('value', i);
curFilename = resultArray[i].name;
option.appendChild( newTxt(curFilename) );
select.appendChild(option);
}
targetContainer.innerHTML = '';
targetContainer.appendChild(select);
}
</script>
<style>
</style>
</head>
<body>
<input type='button' value='load file list' onclick='onLoadBtnClick()'/>
<div id='resultsContainer'></div>
</body>
</html>