1

Here is my code it will send get request and renders some content of the response in html.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Mytitle</title>
</head>
<body>

    <script type="text/javascript">
        function httpGet() {
            var xmlHttp = null;
            var x = document.getElementById("city").value;
            var url = "http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json";
            xmlHttp = new XMLHttpRequest();
            xmlHttp.open("GET", url, false);
            xmlHttp.send();
            var obj1 = JSON.parse(xmlHttp.responseText.toString());
            document.getElementById("placeholder").innerHTML = obj1.message
                    + " " + obj1.list[0].name;

        }
    </script>
    <input type="text" id="city" />
    <input type="button" value="submit" onclick="httpGet()" />
    <div id="placeholder"></div>
</body>
</html>

this code is working perfectly when i run in eclipse browser. but its failing in Browser. I have checked browser configuration for script enabling and its enabled. and also no issue with browser configuration.

Im new to javascript http requests. Please suggest

rolfl
  • 17,539
  • 7
  • 42
  • 76
dileepvarma
  • 508
  • 2
  • 7
  • 30
  • Yeah, that's not a very modern way to make an AJAX call. Can you use jQuery? – Elliott Frisch Dec 04 '13 at 05:28
  • Related Question, http://stackoverflow.com/questions/19821753/jquery-xml-error-no-access-control-allow-origin-header-is-present-on-the-req – Isuru Dec 04 '13 at 05:31
  • And why don't you debug javascript in your browser.? There are many plugins available for debuging. Like Firebug in firefox and Chrome has inbuilt debugger. – Vimal Bera Dec 04 '13 at 05:31

4 Answers4

1

I think ur xmlhttprequest instance is not getting created. It is some time browser dependent try this..

     var xmlhttp;
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 && xmlhttp.status==200)
 { your code  }
Sachin9
  • 135
  • 8
1

In addition to needing a cross browser xmlhttpquest (which for that alone I'd use jQuery), you also need to wait for the document ready before accessing the city by id... that is, move your script block after your city definition (and I think you may need a form, depending on browser). Perhaps something like this

<body>
  <form>
    <input type="text" id="city" />
    <input type="button" value="submit" onclick="httpGet()" />
  </form>
  <script type="text/javascript">
    function httpGet() {
        if (typeof (document.getElementById("city")) == 'undefined') {
          alert("Maybe console.log our alarm... but the sky appears to be falling.");
        }
        var xmlHttp = null;
        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 && xmlhttp.status==200) {
            var obj1 = JSON.parse(xmlHttp.responseText.toString());
            document.getElementById("placeholder").innerHTML = obj1.message
                + " " + obj1.list[0].name;
          }
        }
        var x = document.getElementById("city").value;
        var url = "http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json";
        xmlHttp.open("GET", url, false);
        xmlHttp.send();
      }
  </script>
  <div id="placeholder"></div>
</body>
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • 2
    Uhm, the code is executed when the button is clicked, at which point the element with ID `#city` already exists. Regarding DOM access the code is perfectly fine. – Felix Kling Dec 04 '13 at 05:41
  • On closer inspection I see that you're correct, however it's still good advice. – Elliott Frisch Dec 04 '13 at 05:43
  • i tried moving script block to after city definition ..but still not successfull – dileepvarma Dec 04 '13 at 05:44
  • for simplicity i have removed city input tag and get element of city in script code.. so now i will he having only submit button. still im not able to get the response from browser. – dileepvarma Dec 04 '13 at 05:51
1

I read somewhere that the Eclipse browser doesn't adhere to the same origin policy [Wikipedia]. That's why it is possible to make an Ajax request to an external URL, something that is not possible by default in a "normal" browser.

And indeed if I try to run your code [jsFiddle], I get the following error:

XMLHttpRequest cannot load http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access.

There are multiple ways to work around the same-origin policy [SO]. In your case it seems that the service supports JSONP [SO].

With JSONP, your not making an Ajax call to the server, but instead you are using the URL with a dynamically created script element. Script elements are not restricted by the same-origin policy and therefore can load data (code) from other servers.

The server will return a JavaScript file which contains a single function call. The name of the function is specified by you via a query parameter. So, if the JSON response is usually:

{"message":"accurate","cod":"200", ...}

by adding the argument callback=foo to the URL, the server returns

foo({"message":"accurate","cod":"200", ...});

(follow this URL to see an example for your service)

This response can be evaluated as JavaScript. Note that you can not turn every JSON response into JSONP. JSONP must be supported by the server.

Here is a complete example:

// this function must be global since the script is executed in global scope
function processResponse(obj1) {
    document.getElementById("placeholder").innerHTML = 
        obj1.message + " " + obj1.list[0].name;
}

function httpGet() {
    var url = "http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json";
    // the following line is just to explictly show the `callback` parameter
    url += '&callback=processResponse';
    //                ^^^^^^^^^^^^^^^ name of our function

    var script = document.createElement('script');
    script.src = url;
    document.body.appendChild(script);
}

DEMO

If you google for JSONP, you will find more information [Wikipedia] and tutorials.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
-1
function httpGet() {
    var xmlHttp = null;
    var x = document.getElementById("city").value;
    var url = "http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json";
    xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", url, false);
    xmlHttp.onreadystatechange = function(){
         var obj1 = JSON.parse(xmlHttp.responseText.toString());
         document.getElementById("placeholder").innerHTML = obj1.message
                    + " " + obj1.list[0].name;
    }
    xmlHttp.send();
 }
danny.hu
  • 110
  • 3
  • Can't you see? I add event listener for waiting a ajax to finish. – danny.hu Dec 04 '13 at 06:10
  • Nope, didn't see it when I glanced over the code. **Always** explain your solution, don't just post code. While your code is not incorrect, the event handler is not necessary. This code performance a *synchronous* request (`xmlHttp.open("GET", url, false);`) and that's why it is possible to access the response as done in the original code. Or to say it differently: Your change doesn't change the behavior of the code and hence cannot solve the problem. – Felix Kling Dec 04 '13 at 06:15