Issue With Ajax Loading A Php Script, Called From An Onclick;
Solution 1:
First: the problem with your script is that you're trying immediately set the innerhtml after calling ajax. Ajax requests are Asynchronous (unless you tell them not to be), so they will run on their own time, and whatever you put after the call might execute before or after. But basically unless you tell the ajax call to be synchronous (which pauses the script until you get a response), xmlhttp.responseText
doesn't mean anything yet. The way you handle an asynchronous request in regular javascript is to specify a callback function through onreadystatechange
. E.g.
function myCallback()
{
...
}
xmlhttp.onreadystatechange=myCallback;
xmlhttp.send();
you could also do this anonymously with xmlhttp.onreadystatechange = function() { ... };
Either way, for asynchronous calls, you need that callback. And more specifically, you need to handle the callback when the readystate is specifically 200
(successful return), e.g
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("divClass3").innerHTML=xmlhttp.responseText;
}
};
The other option is to make it synchronous, which freezes your javascript until it's loaded (this method is generally not recommended). You could do this by simply changing your .open
statement to
xmlhttp.open("POST","test.php",false);
(the last parameter determines whether the call is asynchronous or not (true=async; false=sync)
jQuery
So that's how you would do it in regular javascript, but since you mentioned it, I would highly recommend using jQuery because it will make your life way easier. Here is your entire ajaxcall function using jQuery:
functionajaxcall()
{
$.post('test.php', function(response) {
$('#divClass3').html(response);
});
}
Let me know if you have any questions about how this works :)
Post a Comment for "Issue With Ajax Loading A Php Script, Called From An Onclick;"