I have a working PHP web service that returns data (if I input the url into the browser I get the results). I need to use Javascript to retrieve this data from my web service, but I’m not too great with Javascript. Based on all the tutorials, examples, and StackOverflow questions and answers I’ve read this should work, but it doesn’t. Please Help!
<script type="text/javascript">
var url = '*working url*';
var xmlhttp = null;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
else { document.write('Perhaps your browser does not support xmlhttprequests?'); }
xmlhttp.open('GET', url, true);
xmlhttp.send(null);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myObj = eval ( xmlhttp.responseText );
} else {
// wait for the call to complete
}
};
</script>
Also, I need help making sure that I’m calling this correctly. Currently I do it like this, which may be the problem:
<script type="text/javascript">
document.write(myObj);
</script>
I’m aware this doesn’t directly answer your question but if you are “not too great” with javascript I would recommend just going straight to jQuery instead of messing with the lower level objects.
It will also help you with cross browser compatibility.
http://jquery.com/
http://api.jquery.com/category/ajax/
However if you have a particularly boring day some time in the future, going back and learning what’s going on behind the scenes is always beneficial.
This would be a simple ajax post using jQuery (with a text response):
To answer your second question (in comments), the code looks correct but perhaps you’re getting a bad response. You can attach additions events onto the ajax call to get additional information.
This code is borrowed and modified from jQuery’s site:
http://api.jquery.com/jQuery.post/
I got the function parameter info from:
http://api.jquery.com/jQuery.ajax/