In the code below I try to post some data to a table and then retrieve several records from the table afterwards. For testing purposes I have only included a dummy query in the php, which returns a valid xml.
But the Javascript readystate only reach readystate 1 (twice). As the php seems to be working fine I suspect I have scripted the javascript incorrectly. Is it a problem with the "request" variable?
$(document).ready(function() {
$('form').submit(function(event) { //Trigger on form submit
$('#name + .throw_error').empty(); //Clear the messages first
var name = $('input[name=name]').val();
var request = !window.XMLHttpRequest ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var xml = request.responseXML;
var dynamiclist = '';
document.getElementById("myLink").innerHTML = '';
var posts = xml.documentElement.getElementsByTagName("post");
for (var i = 0; i < posts.length; i++) {
var Msg = posts[i].getAttribute("Msg");
alert("test");
var dynamiclist = dynamiclist + '<article class="middleContent"><header><h2><a href="#" title="Post">' + Msg + '</a></h2></header> </article>';
document.getElementById("myLink").innerHTML = dynamiclist;
};
};
};
request.open('POST', 'process.php', true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send('name=' + name);
});
});
</div>
Using jQuery makes sense here.
Simple solution however most probably is to simply remove the last "true" in request.open(), which makes the request an asynchronous, non-blocking one (which it really should be anyway). MDN also states at onreadystatechange that you shouldn't be using it with synchronous requests (aka requests that have "true" as third argument for open())
Source: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
Try preventing the default form event from firing:
$('form').submit(function(event) { event.preventDefault();
This prevents the form element from reloading the browser window.