4

The json response is in {"userName":"clevermeal835","userRole":"Participant"}

I am getting an alert message as success but while reading the response I am getting the error:

XMLHttpRequest cannot load the url Origin null is not allowed by Access-Control-Allow-Origin.

If I run the code from command prompt by

--disable-web-security

I am getting response. Can any one help me resolving this problem with out using command prompt. The below code.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="Scripts/jquery-1.4.2.min.js"></script>

<script>
$(document).ready(
    function() {
        $("#jsonpbtn2").click(function() {
            var uid = "clevermeal835";
            var pwd = "Welcome_1";
            var userType = "participant";
            var surl="http://localhost:8080/RESTlet_WS/MobiSignIn/{\"userName\":\""+uid+"\",\"password\":\""+pwd+"\",\"userType\":\""+userType+"\"}/";

$.ajax({
    type : 'GET',
    contentType: "application/json; charset=utf-8",
    url : surl,
    dataType : 'json',
    headers : {Accept : "application/json","Access-Control-Allow-Origin" : "*"},
    crossDomain : true,
    success :SucceedFunc ,
    error : function(data, textStatus, errorThrown) {
        console.log("error"+' '+JSON.stringify(data) + textStatus  + errorThrown);}
    });

function SucceedFunc(data) {
    alert("success");
    var userName = data.userName;
    alert(userName);
    }
});
});
</script> 
</head>
<body>
<input id="jsonpbtn2" type="submit" value="button" />
</body>
</body>
</html>
Patricia
  • 7,752
  • 4
  • 37
  • 70
shireasha
  • 151
  • 1
  • 2
  • 10
  • 1
    Are you testing your site by serving your web pages over `file://` in Chrome? You should server it from your web server. – apsillers Aug 21 '12 at 14:18

2 Answers2

4

It looks like you're testing your site by serving your web page over file:// in Chrome. For security reasons, Chrome does not allow you to perform Ajax calls from file:// resources.

The security threat here is that someone could email you a .html file that, when opened with file://, sent out Ajax requests to fetch the contents of your email inbox (if allowed to query web pages) or other files on your computer (if allowed to query other file resources).

You should instead test your pages by serving them from the same localhost:8080 server that is serving your API pages.

apsillers
  • 112,806
  • 17
  • 235
  • 239
  • Getting same error.. Origin 'http://localhost:63342' is therefore not allowed access. The response had HTTP status code 405. And i have enabled CORS in my node server – Prasanth Jaya Feb 25 '16 at 06:02
-1

Try adding:

beforeSend: function( xhr ) {
     xhr.overrideMimeType( 'text/plain; charset=UTF-8' );
}

to your Ajax call.

DeweyOx
  • 719
  • 5
  • 14