Inder
Inder

Reputation: 11

No reply received using XmlHttpRequest

I am trying to write a small script, which can send a request and download a json response.

var xmlhttp = false;

    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }

      xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4)
        {
         // I tried checking for status but that is always coming 0
        document.getElementById("myDiv").innerHTML=xmlhttp.responseText+"a";
        }
      }*/
      var url = 'http://exampleurl.com/[email protected]';
    xmlhttp.open('GET',url,true);
    xmlhttp.send(null);

Now if I replace the URL with a text file, it works fine. However my server is replying in JSON encoding. Also if I visit the URL in my browser, it shows me the desired output.

However when I query it using XmlHttpRequest it always gives me a status of 0, and has a null response (nothing to decode).

Upvotes: 1

Views: 542

Answers (2)

tpow
tpow

Reputation: 7886

Did you try URL encoding your query parameters? Looks like you might be sending across special characters.

As kjy112 mentioned, there are limitations to making client-side requests to other domains, even sub-domains - same origin policy..

Update: Inder, see http://en.wikipedia.org/wiki/Same_origin_policy, this is a security mechanism that prevents what you are trying to do.

Here is how you can solve it: Have your server make the call on behalf of your client. What I mean by that, is take the call you were going to make from the browser(via AJAX), and make it a web service on the server. Then have your AJAX call go to your server, which will then make the call and return the response. So, you're using your server as an intermediary.

Or

If it's a public API, they are probably configured for JSONP (http://ajaxian.com/archives/jsonp-json-with-padding)

Upvotes: 1

Shad
Shad

Reputation: 15451

I usually validate xmlhttp.status after validating readyState (200 is what you want)

Have you tried checking xmlhttp.statusText to see if it holds anything interesting?

Upvotes: 0

Related Questions