0

I created an HTML file foo.html with the following contents:

  <script src="http://code.jquery.com/jquery-1.8.3.js"></script>
    <script> 
      $.ajax({url:"http://foo.com/mdata",
        error: function (results) {
          alert("fail");
        },
        success: function (result) {
          alert("sucesses");
        }
      });
    </script>

When I load this HTML file in the web browser it always shows a dialog box with fail.

  1. Any idea why this is happening?
  2. Also what is the best way to debug this?

PS:

Assume that http://foo.com/mdata is a valid web service path.

EDIT#1

Solution

a similar code worked perfectly fine with me using $.getJson http://jsfiddle.net/dpant/EK3W8/

i also did save the content as a .html file and a request from file:// to an web service also seems to work.

<!DOCTYPE html>
<html>
<head>
  <style>img{ height: 100px; float: left; }</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <div id="images">

</div>
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
  {
    tags: "mount rainier",
    tagmode: "any",
    format: "json"
  },
  function(data) {
    $.each(data.items, function(i,item){
      $("<img/>").attr("src", item.media.m).appendTo("#images");
      if ( i == 3 ) return false;
    });
  });</script>

</body>
</html>

Looks like most of the browsers supports the CROS so you can write a script save it as .html and open it in browser and it will do a Ajax request successfully *provided that the server you are making request supports it *. In this case my web server (service) does not support CROS (and default configuration of Apache will not support it).

Many of the web-services have enabled the CROS eg http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=? hence the request goes through successfully.

Few links:

http://enable-cors.org/

https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS

http://en.wikipedia.org/wiki/Cross-Origin_Resource_Sharing

David
  • 4,634
  • 7
  • 35
  • 42
  • I'm getting a 500 server error... – Snakes and Coffee Feb 03 '13 at 08:18
  • Try to add `/` at the end of your url in your ajax request – Pierrickouw Feb 03 '13 at 08:22
  • i have changed the web service name. assuming it working fine, is there any other reason why it is not working. – David Feb 03 '13 at 08:23
  • @GreenLeaf: did that still no luck. – David Feb 03 '13 at 08:26
  • You're trying to do cross-domain scripting. Please don't. – raina77ow Feb 03 '13 at 08:26
  • is it something to do with cross domain ajax request? – David Feb 03 '13 at 08:27
  • @raina770w : so what is the best way to do this. Let say you want to develop and debug you code without putting in the server. I want to debug locally – David Feb 03 '13 at 08:28
  • `jsonp` is the only dataType for cross domain requests. – Jai Feb 03 '13 at 08:30
  • CORS has been around for years now, cross-domain requests are not a problem in modern browsers and don't demand that use of JSONP. – Quentin Feb 03 '13 at 08:31
  • @Quentin: then why is it now working in my case. – David Feb 03 '13 at 08:32
  • @David — Because (a) you haven't set up CORS and (b) you are dealing with an HTML document loaded from the file system and not a web server on a different origin. – Quentin Feb 03 '13 at 08:34
  • @Quentin: what do you mean by setting up CORS? Does it make a difference (for same origin policy ) from where i am loading my document? – David Feb 03 '13 at 08:38
  • Google it if you're interested, it isn't the solution to your problem though (the solution is "get a local development server"), it was a counter to all the "cross domain requests are impossible" commentary. And yes, it does make a difference where the document is loaded from. – Quentin Feb 03 '13 at 08:39
  • @jai putting dataType: 'jsonp' also didn't help – David Feb 03 '13 at 08:39
  • its not that way, Your webservice is giving json in response only then. – Jai Feb 03 '13 at 08:40
  • thanks @Quentin. So if I set-up a local development sever i can do request to other domain also (apart from http://localhost) without doing any configuration for CORS? – David Feb 03 '13 at 08:43
  • No, if you are running a local development server then CORS will work consistently across browsers that support CORS. Running a local development server will mean that the you can make the request to `http://localhost/mdata` instead of `http://foo.com/mdata` – Quentin Feb 03 '13 at 08:51
  • @Quentin, Agree if I make the request to the http://localhost/mdata it should work, but based on the CROS description it can also work for some web-service(s) http://foo.com/abc which is not available through the localhost, if http://foo.com/abc allows so. – David Feb 03 '13 at 09:09
  • @Quentin: I found an example working (so you can actually make a request from file:// to an web service) http://jsfiddle.net/dpant/EK3W8/. it is working even if i store the content as a file in computer and open it – David Feb 04 '13 at 01:45

3 Answers3

3

It always fails for two reasons:

  • You need a webserver that answers to your request (200 = success, 404 i.e. is an error) on Linux you can easily setup one, on Windows and Mac look at Bitnami
  • You can't call a different domain via AJAX. If you're running your script on www.example.com you can't ask for www.example.net Look at the same origin policy.
napolux
  • 15,574
  • 9
  • 51
  • 70
  • I agree. But isn't there any way to get around the same origin policy just for the development cycle. I do have a webserver setup, but for each change putting in the web server seems to me too much of repetitive work – David Feb 03 '13 at 08:31
  • In most cases, the process for deploying to your development server should be "1. Press Save in your editor. 2. There is no step 2". – Quentin Feb 03 '13 at 08:33
  • That's why you need a local webserver to develop your stuff. After you finish you can upload to the real server. You can't escape the same origin policy easily, use a PHP (or Python, or whatever) as a proxy that runs on your local webserver. But as you can see, you still need a webserver that runs locally. – napolux Feb 03 '13 at 08:33
  • Well you actually can call a different domain via AJAX as long as both your web browser and the remote server both support [CORS](http://www.w3.org/TR/cors/). (Also if you're fetching JSON there is a workaround known as [JSONP](http://json-p.org).) – hippietrail Feb 03 '13 at 13:02
1

Actually we are trtying to send a AJAX request cross the domains so it will happen. I have tried this code. on my machine it shows success.

<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
    <script> 
    $.support.cors = true;
      $.ajax({url:"http://www.google.co.in/",
        error: function (xhr, ajaxOptions, thrownError) {

            alert("fail");
            alert(xhr.status);
            alert(thrownError);
       },
        success:function(result){
              alert("sucesses");
        }
      });

    </script>

Code works fine with the addition of the line $.support.cors=true, it will definitely work for you.

Emil
  • 7,220
  • 17
  • 76
  • 135
  • Both the local browser and the remote server must support CORS. Internet Explorer < 10 doesn't support it. Opera only began support a couple of months ago. Some mobile browers might not support it yet. Setting `$.support.cors` to `true` won't make it work with such browsers and servers. – hippietrail Feb 03 '13 at 13:05
  • 1
    @Monhpreet This still did not work for me. Still goes to fail. I am using Firefox and chrome. – David Feb 03 '13 at 18:33
0

As I figured out, in Content Scripts, you can't do any Cross-Domain XHRs. You would have to do them in an extension page such as Background, Popup, or even Options to do it.

For more information regarding content script limitation, please refer to the page on Content Scripts in the Google Developer's Guide.

And for more information regarding xhr limitation, please refer to the XHR page.

doppelgreener
  • 4,809
  • 10
  • 46
  • 63