0

I want to know how I can correctly return the data from the following json: pretend i have a url http://test.com/tesdata which gives me the following data:

[{"Identifier":1, "Name":"Test"},
 {"Identifier":2, "Name":"Test"},
 {"Identifier":3, "Name":"Test"}]

So I did the following to get this data in a div:

                $.ajax({ 
    type: 'GET', 
    url: 'http://notgiven', 
    data: { get_param: 'value' }, 
    dataType: 'json',
    success: function (data) { 
        alert("s");
        $.each(data, function(index, element) {
            $('.result').append("a");
        });
    },
    error: function(jqXHR, textStatus, errorThrown){
        alert("jqXHR: " + JSON.stringify(jqXHR));
        alert("textStatus: " + JSON.stringify(textStatus));
        alert("errorThrown: " + JSON.stringify(errorThrown));
    }
});

And i get the following error Unable to parse Json string

bdz
  • 321
  • 1
  • 6
  • 15
  • how far did you get? where do the error occur? – Niklas Wulff Aug 13 '12 at 12:04
  • 1
    Test: `element.Identifier+' '+element.Name` – Alex Ball Aug 13 '12 at 12:05
  • 1
    There is an extra `}` in the array. – Ram Aug 13 '12 at 12:06
  • the fact that it didn't show the alert is maybe something you could add to your question (pretty important detail in locating the issue) – VDP Aug 13 '12 at 12:13
  • does it show an error in the console window? You can also catch the error by adding an `error(jqXHR, textStatus, errorThrown)` - callback like you did with the success callback – VDP Aug 13 '12 at 12:15
  • Could you confirm that you are getting the json response from the url.Please use development tools like firebug or chrome's inspector.. – Nick Aug 13 '12 at 12:18
  • I cannot acces the page in chrome nor firefox, im building it with xcode and phonegap, so i can't debug the javascript here.. :( – bdz Aug 13 '12 at 12:20
  • 1
    possibly a cross-origin error. Add the error callback and log it with `console.log(jqXHR, textStatus, errorThrown);` I'm pretty sure you can also get to the log messages inside xcode. Are you testing it with the simulator? Once deployed phonegap should resolve any cross origin issues. – VDP Aug 13 '12 at 12:21
  • like this??: error: function(jqXHR, textStatus, errorThrown){ alert("error" + errorThrown); } – bdz Aug 13 '12 at 12:35
  • your backend script could simply return the correct headers like so: header('Content-Type: application/json'); that way jQuery will decode the response for you. or you could just "eval" the response yourself – Eugene Kuzmenko Aug 13 '12 at 14:31
  • @Al jey i don't understand you.. – bdz Aug 13 '12 at 14:41
  • @bdz yes that's what I meant. But I think jqXHR, textStatus and errorThrown are objects (hard to debug using alert). you can maybe JSON.stringify(errorThrown) if you really can't get a [console.log out of xcode](http://stackoverflow.com/questions/4022152/how-to-see-the-javascript-errors-of-phonegap-app-in-xcode) – VDP Aug 13 '12 at 14:49
  • 1
    @bdz you forgot a comma => [working fiddle](http://jsfiddle.net/p8qXs/) you see it's not working because of the cross-origin issue. (and its a dummy url) Sadly you can't capture those error's only see them in the console.. (at least I haven't been able to yet) – VDP Aug 13 '12 at 14:58
  • @VDP updated my question ! see above. – bdz Aug 13 '12 at 15:24
  • @bdz what does the jqXHR output? Is there any response data or response text? – VDP Aug 13 '12 at 15:27
  • @VDP yes jqxhr much, but the text status = parserror and the textstatus = message unable to parse Json string – bdz Aug 13 '12 at 15:30
  • @bdz de content is relevant. It is possible that the output rendered by the backend contains an error (isn't exactly what you say/think it is) and perhaps the backend is even throwing an error. Just for test purpose you could add the content of the response to a textarea on you're page to view the actual content better. Every quote, comma or bracket counts. And if you don't find it please add the result to your question. I've overlooked millions of such stupid things. Maybe we can help. – VDP Aug 13 '12 at 19:03

3 Answers3

1

Try this:

// create empty object
var json = {};

$.each(data, function(index, element) {
 // for each element, create empty object 
 json[index] = {};
 // map response data to new json object
 json[index]['id'] = element.Identifier;
 json[index]['name'] = element.Name;
});

the json variable now contains all the information in json format stored convenient in an javascript object :)

enter image description here

In your example this would mean:

$.ajax({ 
  type: 'GET', 
  url: 'http://test.com/tesdata', 
  data: { get_param: 'value' }, 
  dataType: 'json',
  success: function (data) { 

       var json = {};

       $.each(data, function(index, element) {
         json[index] = {};
         json[index]['id'] = element.Identifier;
         json[index]['name'] = element.Name;
         // don't know exactly what you try to do here, but let's append this data to '.result'
        $('.result').append("<span id='" + element.Identifier + "'>" + element.Name + "</span>"); 

       });   

  }
});

Please note that if all you want is to append this values to some div it is not necessary to do the whole json conversion. In this case you can just do

 success: function (data) { 
               $.each(data, function(index, element) {
                $('.result').append("<span id='" + element.Identifier + "'>" + element.Name + "</span>"); 

  }); 

}

tmaximini
  • 8,403
  • 6
  • 47
  • 69
  • @frankblizzard what's the added value? You convert the array of objects to an object with objects. Not sure what you wanted to achieve with this, aside from confusion... Last part is correct, but that's almost what he was doing. Also note that JSON is the string format. Once inside the data var it's already parsed, so it's just js objects. The string `[1,2,3]` is just as much json format as the string `{ "a": 1, "b": 2, "c": 3 }` the first is just an array and the last an object. What you call "the json format" is in fact just a javascript object. So you might want to edit you answer :) – VDP Aug 13 '12 at 19:35
0

As I suggested in the comments It's probably a cross-origin issue. You can't access data/scripts from a different origin meaning same protocol (http/https) same domain (mydomain.com) same port (usual omitted defaults to :80)

So origin of: http://localhost:8080/data != https://localhost:8080/data
   origin of: http://mydomain.org/data   != http://localhost/data
   origin of: http://mydomain.org/data   != http://localhost/data
   origin of: http://localhost/data      == http://local

host/somethingelse

Still I'm not 100% sure. But a first step in resolving the issue is proper debugging.

It is possible to debug using xcode But if you want to try without. Define an error handler. (check this fiddle)

You'll see it's not working because of the cross-origin issue. (and its a dummy url) Sadly you can't capture those cross origin error's. You can only see them in the console.. (at least I haven't been able to yet)

But now the good news!

PhoneGap apps aren't limited to the cross-origin policy! So if deployed the issue should be resolved.

If you have access to the backend I have an easy fix for this too. You should set the Access-Control-Allow-Origin: * header to enable CORS (cross origin resource sharing)

NOTE: for development this shouldn't be a problem, for production I advice setting a fixed url or if not needed remove it.

EDIT: So it isn't a cross origin issue. as the error sais: Unable to parse Json string

So you check what's inside the jqXHR response. Look at the raw data verify if it's valid. 95% chance it isn't because my best bet is the jquery json-parser is pretty solid.

Community
  • 1
  • 1
VDP
  • 6,340
  • 4
  • 31
  • 53
-1

You need to call JSON.parse function before any operation on json data with js.

$.ajax({ 
        type: 'GET', 
        url: 'http://test.com/tesdata', 
        data: { get_param: 'value' }, 
        dataType: 'json',
        success: function (data) { 
            var items = JSON.parse(data);
            $.each(items, function(index, element) {
                $('.result').append(element.Id + " " + element.Name);
            });
        }
        });

For IE 6 and 7 you have to include json2.js file for supporting JSON.parse function.

vadim
  • 1,698
  • 1
  • 10
  • 19
  • 1
    The `dataType` explicitly specifies to jQuery that the response should be parsed as JSON before it is handed over to you. Also, jQuery has `$.parseJSON` so there is no need for json2.js – Esailija Aug 13 '12 at 12:52