1

I am having a webserver running on my localhost. If i load my webpage from my webserver everything works fine. I am able to OPEN a REST session with my webserver.

JS code :--

$(document).ready(function() {

                      var xhr = new XMLHttpRequest();
                      var open_str = "http://localhost:8080/vscp/rest?user=admin&password=d50c3180375c27927c22e42a379c3f67&format=json&op=1";
                      xhr.open("GET", open_str, true);
                      xhr.onreadystatechange = function() {
                                  alert(xhr.readyState + "" + xhr.status);
                        if (xhr.readyState == 4 && xhr.status == 200) {

                            alert("session opend success");

                            var json = JSON.parse(xhr.responseText);
                            alert(JSON.stringify(json, null, 10));

                        }
                      }
                      xhr.send();
});

HTML code :--

<!DOCTYPE html>
<html>
    <head>
        <title>Hello jQuery</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script src="hello.js"></script>
    </head>

    <body>
        <div>
            <p class="greeting-id">Trying to open the REST session with vscpd </p>
        </div>
    </body>
</html>

Now if i load the same html page from my D: drive :--

file:///D:my_folder/htm_test.html

I am getting following error "No 'Access-Control-Allow-Origin' header is present". And i have checked in javascript code that xhr.readyState is 4 and xhr.status is 0.

Please suggest what changes to make to my javascript code so that, if i open the html file directly from my D: drive using file:/// then also REST session is opened correctly with my webserver.

========================= JSONP code ========================

$(document).ready(function() {

                      var url = "http://localhost:8080/vscp/rest?user=admin&password=d50c3180375c27927c22e42a379c3f67&format=json&op=1";

                      function jsonpCallback(response) {

                          alert('success');
                      }

                      $.ajax({
                          url: url,
                          dataType: 'jsonp',
                          error: function(xhr, status, error) {
                                     alert("error" + "  " + error.message);
                          },
                          success: jsonpCallback
                      });
                      return false;
});

Error i get :-- server is sending the right response :-- {"success":true,"code":1,"message":"success","description":"Success","session-id":"e5a36e14b687c37b615dbc6a9506df5c","nEvents":0}

But ajax call giving error for this response i.e "Uncaught SyntaxError: Unexpected token :"

enter image description here

Katoch
  • 2,709
  • 9
  • 51
  • 84

2 Answers2

4

You have run into the Same Origin Policy - this is a security mechanism that restricts JavaScript loaded from one domain from sending requests to a different domain.

There are various ways around it, if you are using Google Chrome I would suggest setting the --allow-file-access-from-files flag when you start the browser, Firefox also provides a way to work around it, but don't forget to disable these options when you have finished testing, they are there for a good reason!

codebox
  • 19,927
  • 9
  • 63
  • 81
  • can i not do it in javascript ?? – Katoch Aug 12 '15 at 07:21
  • No, the Same Origin Policy is meant to stop malicious JavaScript from doing things it shouldn't - if it were possible to 'turn it off' from within JavaScript code it would make the whole thing pointless. – codebox Aug 12 '15 at 07:26
  • Yes, JSONP is one of the methods listed in the link above, but you would no longer be using AJAX/XMLHttpRequest and would need to change your server-side code. – codebox Aug 12 '15 at 07:40
  • I tried JSONP but getting some error .. please see my edited original post .. please suggest what is missing now – Katoch Aug 12 '15 at 07:58
  • You need to change the data that is returned in the JSONP response to be a valid JavaScript statement, try assigning the JSON object to a variable, like `var obj = {"success":true," .... }` – codebox Aug 12 '15 at 08:06
  • Also, you can try CORS (Cross-Origin Resource Sharing). CORS is a mechanism that allows resources to be shared across different domains. Take a look at this rundown: http://www.html5rocks.com/en/tutorials/cors/ – michaelpoltorak Aug 12 '15 at 08:57
  • you wrote : "try assigning the JSON object to a variable, like .... var obj = {"success":true," .... }; " so you mean to say that i have to return this complete statement & then value of the "var obj" will be assigned to function argument response in following function ---> function jsonpCallback(response) – Katoch Aug 12 '15 at 09:42
0

That's because Chrome and some other browsers are blocking the local files for security reasons and I don't think there is a method for resolving this issue. You have to use a webserver.