I am a JavaScript beginner have just been introduced to concepts of web services, one-page sites and AJAX. In the assignment I got, one of the problems is to access a web service (using AJAX js) on a different domain. There is a side note in the assignment explaining something called "CORS" which enables the browser to access a foreign web service using the origin header. Setting the valuse of the origin header is, if I understood correctly, not controlled by the user. So, I wrote the following code:
HTML:
<html>
<INPUT TYPE = "button" id = "button" VALUE = "Access web service"><br>
<div id = "message"></div>
<script src = "zaz2.js" type = "text/javascript"></script>
</html>
JavaScript:
function check()
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if(ajax.readyState == 4 && ajax.status == 200)
{
document.getElementById("message").innerHTML="OK.";
document.getElementById("message").style.backgroundColor="green";
}
else document.getElementById("message").innerHTML = "Error";
}
ajax.open("GET", "http://zamger.etf.unsa.ba/provjeriGrad.php", true);
ajax.send();
}
var button = document.getElementById( "button");
button.addEventListener("click" , check);
The code simply prints "OK" if accessing the web service was successful and "Error" if it was not. The web service you see here is an example one I got to use for the assignment. It allows even "localhost" domains to access it, which is what I am doing (Windows OS and WAMPSERVER). Currently, I only get the "Error" printed in my div. I am not sure if my code is wrong, or web service simply doesn't work. I would like your advice regarding my code, if it needs improvement. If web service is the problem, I would be grateful if you could provide me with an example of a working web service, just so I can test my code. Thank you in advance.