1

I can't get this request to do anything other than fail. I've used curl and the web developer toolbar to check the created URL, WD always says the response comes back correctly as 200. I've tried altering the content types to text, octet-stream, and commenting it out. I've also taken the JSON response and validated it using JSONLint.

The code I'm using is this;

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
    <link rel="stylesheet" type="text/css" href="css/testing.css">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" ></script>
    <script type="text/javascript">
    $(function(){
        $("body").append("<p>Testing.....</p>");
        var test= {latitude:"37.0205",longitude:"-7.969141667",startDate:"09-01-2014",endDate:"09-02-2014"};
        var url="<hidden>";

        $.ajax({
            url : url,
            type: "GET",
            data : test,
            dataType:"json",
            contentType:"application/json",
            success: function(data,status)
            {
                $("body").append("<p>Success"+JSON.stringify(data)+"</p>");
                $("body").append("<p>Success"+status+"</p>");
            },
            error: function (jqXhr,textStatus,errorThrown)
            {
                $("body").append("<p>Failure " + JSON.stringify(jqXhr)+"----- "+ textStatus+ "----- "+ errorThrown+"</p>");
            }
        });
        $("body").append("<p>input"+JSON.stringify(test)+"</p>");
    });
    </script>
</head>
<body>
    <h1>Weather test</h1>

</body>
</html>

The output in my web browser from the error function is "Failure {"readyState":0,"responseText":"","status":0,"statusText":"error"}----- error----- "

The header is of the form,

HTTP/1.1 200 OK Cache-Control: private, max-age=0 Server: Microsoft-IIS/7.5 X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Date: Fri, 03 Oct 2014 11:57:47 GMT Content-Length: 25328

and was taken using a curl -ivs --raw to the url with all appropriate get parameters. The valid JSON followed directly after this. I'm worried that not having a content type might be throwing this.

I know there are a lot of other questions like this, but I've tried to go through them first and apply the lessons learnt. If you've any other suggestions, I would be very grateful.

Thanks,

Adrian Forsius
  • 1,437
  • 2
  • 19
  • 29
James
  • 1,764
  • 5
  • 31
  • 49
  • What's the value of `url`? In particular, it is for a different origin (e.g., a different domain) that the page you're running the script on? – apsillers Oct 03 '14 at 13:16
  • Just tried that, no change, but thanks. – James Oct 03 '14 at 13:16
  • @Ninsly actually `data: test,` will convert `test` object to URL params using `$.param`. It's normal behaviour. – Regent Oct 03 '14 at 13:16
  • I'm running the web-page on a server on my home machine and the url is for a different, external server not under my control. – James Oct 03 '14 at 13:17
  • @Regent Ahh, nvm, you're correct. He's specifying a `GET` not a `POST`. – Stryner Oct 03 '14 at 13:19
  • 2
    [GET requests shouldn't carry body content, because it's meaningless.](http://stackoverflow.com/questions/978061/http-get-with-request-body) (Thus, `contentType` is pointless here, and jQuery is smart enough not to populate the request body on a GET request.) – apsillers Oct 03 '14 at 13:20
  • @apsillers So we shouldn't be using a GET request for this, as it's a violation of the HTTP standard. I'll try and ask them to change this. So Get requests are a one-way deal, you can use them to upload data, and get a new page, but you can't get any JSON data. – James Oct 03 '14 at 13:28
  • "*you can use [GET] to upload data...*" -- If you're using GET to upload data, you must put all the uploaded content the URL string, since, again, the request body on a GET is never used. – apsillers Oct 03 '14 at 13:47
  • Yes that's happening, I can see it in the Network tab of web developer toolbar. I used that URL with parameters in the Curl command I ran. – James Oct 03 '14 at 14:10
  • Using dev tools you should see warnings like so: `Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http........ This can be fixed by moving the resource to the same domain or enabling CORS.` – PeterKA Oct 13 '14 at 22:35
  • Does your home server support php and curl? – anhlc Oct 14 '14 at 04:12

2 Answers2

7

As you wrote, I'm running the web-page on a server on my home machine and the url is for a different, external server not under my control.

It typically means that Same origin policy rule works here.

It does not allow you to send cross-domain ajax request so easy.

If you really need to send cross domain ajax request, take a look at JSONP or CORS.

Amy
  • 4,034
  • 1
  • 20
  • 34
Bogdan Burym
  • 5,482
  • 2
  • 27
  • 46
  • 1
    In addition to this you can check cross domain notices using firebug in firefox. It shows hints how to use cross domain ajax/requests – RN Kushwaha Oct 13 '14 at 19:27
  • To solve the problem if the cause is as @BogdanBurim suggested, you should add the http header Access-Control-Allow-Origin with value * to the response of the url action. – Oday Fraiwan Oct 14 '14 at 07:00
1

If you are able to retrieve the url using curl but your ajax call returns error in your browser, this means that url doesn't support CORS (Cross-origin resource sharing) and returns a response header without Allow-Control-Allow-Origin permission for your domain.

As the url is for a different, external server not under your control, you can't enable Allow-Control-Allow-Origin header, hence you can't properly solve this issue at client/javascript level.

However, the solution is simple if you can create a PHP script on your server which uses curl to retrieve that external url, and modify your ajax to call that PHP script instead. In this way, your ajax call an local url and there is no more cross-domain issue.

You can create the PHP script and name it as 'local.php', replace 'your_external_url' with your url:

<?php
$url = 'your_external_url';
$ch =  curl_init($url.'?'.$_SERVER['QUERY_STRING']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo $result;
?>

And modify your ajax url to 'local.php':

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
    <link rel="stylesheet" type="text/css" href="css/testing.css">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" ></script>
    <script type="text/javascript">
    $(function(){
        $("body").append("<p>Testing.....</p>");
        var test= {latitude:"37.0205",longitude:"-7.969141667",startDate:"09-01-2014",endDate:"09-02-2014"};
        var url="local.php";

        $.ajax({
            url : url,
            type: "GET",
            data : test,
            dataType:"json",
            contentType:"application/json",
            success: function(data,status)
            {
                $("body").append("<p>Success"+JSON.stringify(data)+"</p>");
                $("body").append("<p>Success"+status+"</p>");
            },
            error: function (jqXhr,textStatus,errorThrown)
            {
                $("body").append("<p>Failure " + JSON.stringify(jqXhr)+"----- "+ textStatus+ "----- "+ errorThrown+"</p>");
            }
        });
        $("body").append("<p>input"+JSON.stringify(test)+"</p>");
    });
    </script>
</head>
<body>
    <h1>Weather test</h1>

</body>
</html>
anhlc
  • 13,839
  • 4
  • 33
  • 40