0

This service returns valid JSON data

var gridValsstr;
$.ajax({
    type: "GET",
        url: "InsertMessage",
        cache: false,
        success: function(data)
        {
            //  alert(data);
            gridValsstr = data;
        },
        error: function(xhr, status, error) {
            alert(xhr.responseText);
        }
});

However on this line:

var gridvals = JSON.parse(gridValsstr);

I get the error:

SyntaxError: JSON.parse: unexpected character

Which then causes the rest of my script to fail...

However if I put a break point at that line and wait for a few seconds the line processes correctly and loads the JSON into the UI. So I'm thinking it is processing too quickly or the variable isn't completely ready yet or something?

Niels Keurentjes
  • 41,402
  • 9
  • 98
  • 136
user3196063
  • 41
  • 1
  • 7

2 Answers2

0

Most likely because the Ajax call is asynchronous and your JSON.parse line is running before the request has completed.

The break point is pausing execution long enough for the Ajax request to complete.

Jon Miles
  • 9,605
  • 11
  • 46
  • 66
0

Followed the link from Fabricio, looks like the async request didn't complete before I was trying to access the var. So below code solved the problem. Remember to also put any code that interacts with the result of the call into the .done(){.....} and it will work.

getFilters().done(function(r) {
if(r) {
    gridValsstr = r;
    gridvals = JSON.parse(gridValsstr);     
}
else
{
    //alert("r sucks");
}
})
.fail(function(x) {
    alert("didn't work.")
});
user3196063
  • 41
  • 1
  • 7