JSON Request appended with [object%20Object] in jQuery
Asked Answered
S

3

6

I'm trying to fetch a custom JSON feed I have written with jQuery using the getJSON method. For an unknown reason the URL seems to be having cache_gen.php?location=PL4 stripped from the end and replaced with [object%20Object] resulting in a 404 error occurring.

Here's the jQuery I'm using:

var fetchData = function() {

    if (Modernizr.localstorage) {

        var api_location = "http://weatherapp.dev/cache_gen.php";
        var user_location = "PL4";
        var date = new Date();

        console.log(api_location + '?location=' + user_location);

        jQuery.getJSON({
            type: "GET",
            url: api_location + '?location=' + user_location,
            dataType: "json",
            success: function(jsonData) {
                console.log(jsonData);
            }
        });

    } else {
        alert('Your browser is not yet supported.  Please upgrade to either Google Chrome or Safari.');
    }
}

fetchData();

From the console log I can see the URL string is calculated correctly as: http://weatherapp.dev/cache_gen.php?location=PL4

However the second line in the console is: Failed to load resource: the server responded with a status of 404 (Not Found).

Can anyone point me in the right direction with this?

UPDATE 19/01/2013 23:15

Well, I've just converted so that is fits the docs perfectly using $.ajax. I've also added a fail event and logged all of the data that gets passed to it.

var fetchData = function() {

    if (Modernizr.localstorage) {

        var api_location = "http://weatherapp.dev/cache_gen.php";
        var user_location = "PL4";
        var date = new Date();

        var url = api_location + '?location=' + user_location;

        console.log(url);

        jQuery.ajax({
            type: "GET",
            url: api_location + '?location=' + user_location,
            dataType: "json",
            success: function(jsonData) {

                console.log(jsonData);
            },
            error: function( jqXHR, textStatus, errorThrown ) {
                console.log('textStatus: ' + textStatus );
                console.log('errorThrown: ' + errorThrown );
                console.log('jqXHR' + jqXHR);
            }
        });

    } else {
        alert('Your browser is not yet supported.  Please upgrade to either Google Chrome or Safari.');
    }
}

fetchData();

After this my console gives me the following information:

http://weatherapp.dev/cache_gen.php?location=PL4
download_api.js:44textStatus: parsererror
download_api.js:45errorThrown: SyntaxError: JSON Parse error: Unable to parse JSON string
download_api.js:46jqXHR[object Object]

I have ensured the headers for the JSON feed are current, and the feed is definitely serving valid JSON (it effectively caches a 3rd party service feed to save costs on the API).

Sweated answered 19/1, 2013 at 22:48 Comment(11)
weatherapp.dev/cache_gen.php?location=PL4 is not a working url. <----- click itImmoderacy
@popnoodles, it may be a /etc/hosts redirection :). But, certainly .dev sounds fishyDorwin
.dev is a development domain. It have set this up has an Apache virtual-host on my local system, which is has an entry in my /etc/hosts to ensure that is resolves properly. I can access this domain in my browser, its the same domain as where the JS file is being loaded from.Sweated
What appears on screen when you just browse to the URL?Tasso
@Dorwin i did consider hosts after I posted but thought it's so unlikelyImmoderacy
Just as it should I get the JSON data. cloud.danielgroves.net/Q0WrSweated
I can assure you that your feed is not serving valid JSON and that is what is causing the error that you are now seeing.Christachristabel
I can prove it, copy your response from dev tools and paste it in jsonlint.com - it will show you where your error is.Christachristabel
@Adam Thanks. I appreciate this. It seems to be appending a random 2728 onto the end of the file during the readfile() method.Sweated
Solved. Thanks @Adam. If you you want the rep make an answer and I'll mark it as solved.Sweated
Possible duplicate of %5Bobject%20Object%5D (404 not found) when attempting to submit via AJAXBlubber
C
6

The reason why you see this error:

http://weatherapp.dev/cache_gen.php?location=PL4
download_api.js:44textStatus: parsererror
download_api.js:45errorThrown: SyntaxError: JSON Parse error: Unable to parse JSON string
download_api.js:46jqXHR[object Object]

Is because your JSON is invalid. Even if a response comes back from the server correctly, if your dataType is 'json' and the returned response is not properly formatted JSON, jQuery will execute the error function parameter.

http://jsonlint.com is a really quick and easy way to verify the validity of your JSON string.

Christachristabel answered 20/1, 2013 at 13:17 Comment(1)
Extending @Adam's good answer. More generally, something is mismatched between your 'datatype' value on the call (explicit or implied) and the actual data returned from the server. I was specifying "html" as my datatype and got this error. I omitted the optional datatype parameter and stopped seeing the error. I'm definitely returning html and inserting in the page but am willing to bow down to the ajax goddess and let her think my return value is any type she wants as long as my call works.Civet
L
4

I was running into the same issue today. In my case I was assigning a JSON object to a variable named 'location' which is a reserved word in JavaScript under Windows and appearantly is a shorthand for windows.location! So the browser redirected to the current URL with [object%20Object] appended to it. Simple use a variable name other than 'location' if the same thing happens to you. Hope this helps someone.

Lighting answered 11/11, 2014 at 19:44 Comment(1)
This saved me some time & headache. I was not aware that "location" was a reserved word in JavaScript on Windows. Thanks!Butterball
C
0

Check out the actual function usage:

http://api.jquery.com/jQuery.getJSON/

You can't pass on object parameter into $.getJSON like with $.ajax, your code should look like this:

    jQuery.getJSON('api_location + '?location=' + user_location)
         .done(function() {
            //success here
         })
         .fail(function() {
           //fail here
         });

To maybe make it a little clearer, $.getJSON is just a "wrapper function" that eventually calls $.ajax with {type:'get',dataType:'JSON'}. You can see this in the link I provided above.

Christachristabel answered 19/1, 2013 at 22:58 Comment(4)
Actually just easier for the OP to replace .getJSON with .ajaxImmoderacy
@popnoodles why? OP not using any options that $.getJSON doesn't already includePhonon
@Phonon because they've written their code as if they should have been using .ajax - changing just 7 characters is easier.Immoderacy
Just updated the main post, what you picked yup on was a mistake after trying multiple different things. Added more debugging information now as well.Sweated

© 2022 - 2024 — McMap. All rights reserved.