I’ve read as much as I can, but totally stuck here (had it working at one stage but only if I put alerts in – ??). What I need:
- User inputs a list into a textarea.
- text area read to array.
- ajax requests to php script for each element in array.
- php script then runs a mysql query and returns the result to ajax.
- ajax then creates a new element and fills it with the response.
Hopefully the user will see a list being built as the results come through (the tables are quite large so expecting some data to take longer than others).
Code so far:
<script type="text/javascript">
function ajaxFunction(value){
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
} catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if (ajaxRequest.readyState == 4){
return ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "results.php?list=" + value, true);
ajaxRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajaxRequest.send(null);
}
function loopAJAX() {
var box = document.getElementById("results-table");
box.innerHTML = "";
var vars = document.getElementById('list').value;
var varArray = vars.split("\n");
var len = varArray.length;
for(var i=0; i<len; i++) {
var text = ajaxFunction(varArray[i]);
var entry = document.createElement('p');
entry.innerHTML = text;
box.appendChild(entry);
}
}
</script>
Output should be like:
<div id='results-table'><p>id1</p><p>id2</p></div>
Currently the output looks like:
<div id='results-table'><p>undefined</p><p>undefined</p></div>
Thanks in advance!
The
XMLHTTPRequests you are doing are asynchronous, so they cannot return the text at function definition time (they are called later). What you need to do is pass a reference to your<p>tag to theonreadystatechangemethod and then update theinnerHTMLinside the callback: