0

Pasting following url to address bar prompts for a username and password. Once authenticated it sends results in json format. http://metabolomics.pharm.uconn.edu:2480/connect/iimdb

However following code doesn't work. Results in alert "failed". I also tried hard coding username and password. Can someone spot the problem. Thanks in advance.

    <script type="text/javascript" src="jquery-1.9.1.min.js"></script>
        <script type="text/javascript">
        $(document).ready(function(){   
            var userName = $('#username').val();
            var password = $('#password').val();
            var submitButton = $('#submitButton');
            submitButton.click(function(){
    $.ajax( {
        type: 'Get',
    url : 'http://metabolomics.pharm.uconn.edu:2480/connect/iimdb',
    dataType : 'json',
        username : userName,
        password : password,
    success : function(data) {
        alert("success");
        response(data);
    },
        error : function()
        {
        alert("failed");
        }
});
    });
        }); 
        </script>
lochi
  • 860
  • 2
  • 12
  • 26
  • 1
    check out this question: http://stackoverflow.com/questions/5507234/how-to-use-basic-auth-and-jquery-and-ajax – tmsimont Feb 21 '13 at 19:20
  • 1
    isn't this a same origin policy issue? http://en.wikipedia.org/wiki/Same_origin_policy – p1100i Feb 21 '13 at 19:22

2 Answers2

2

From the client side you can NOT make a request into any other domains (not even the same domains different port like :81) then the host itself. This is the same origin policy.

If you want this authentication implemented, you need direct the AJAX post on your host (where the app runs) and the app itself needs to propagate this request to the desired address - in your case to metabolomics.

After you receive the answer, you can reply on the clients ajax request in any way you please.

If you really want to stick to your format of JavaScript there is a workaround to just proxy such requests, see Q: Make cross-domain ajax JSONP request with jQuery and Q: Ajax cross domain call

Community
  • 1
  • 1
p1100i
  • 3,710
  • 2
  • 29
  • 45
  • How would you call this web service with jQuery? I need to use the username and password and get the Json file. – lochi Feb 21 '13 at 19:54
  • 1
    Read the answer above. It's not going to work because browsers by default restrict you from making calls to other domains. The links in the answer will help. – Brian Kelly Feb 21 '13 at 20:04
0

You can also use the $.getJSON(), which does not have ploblem with the "Same origin policy".

It's iquivalent to:

$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: success
});
Samuel L
  • 139
  • 3
  • 5