0

Actually in my website have a WebMethod that return two values from MySQL database.

I'm calling that method throw AJAX but the problem is that when i'm trying to parse a specific data i get the following error: Unexpected token o in JSON at position 1

Here is debug of ajax code enter image description here

While here is the code

function getAjax(data) {
    $.ajax({
        type: "POST",
        url: "stats.aspx/getSC",
        data: JSON.stringify({ data: data }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {
            var data = $.parseJSON(result);
            $('#sc-gg').text(data.TOTSC);
        },
        error: function (xhr) {
            alert(xhr.status);
        }
    });

}

The WebMethod will ever return just two values from the database which i will set to a "statistic box"

NiceToMytyuk
  • 3,644
  • 3
  • 39
  • 100
  • Because you set `dataType: 'json'` jQuery already deserialises the response for you. The error is because you are again deserialising the object. Simply remove the `$.parseJSON()` call. See the duplicate for more details – Rory McCrossan Jul 18 '19 at 14:56
  • @RoryMcCrossan actually even by writting just result.TOTSC i get undefined, i've yet tryed with and without deserializing it. – NiceToMytyuk Jul 18 '19 at 14:57
  • 1
    That's a separate issue. It's because, if you look at the response, you have an additional `d` property in there which is an array. The correct accessor would be`result.d[0].TOTSC` – Rory McCrossan Jul 18 '19 at 14:59
  • @RoryMcCrossan even with result.d[0].TOTSC it return undefined :|, could the problem be the JSON as TOTSC value is 241 and not "241"? – NiceToMytyuk Jul 18 '19 at 15:03
  • My bad, I just noticed that the `d` property in the tooltip is in fact a string which itself is JSON. As such you need to deserialise that: `JSON.parse(result.d)[0].TOTSC`. This should work. However it seems a waste of time in this case to return JSON within JSON. Just encode the response once and use the first accessor I mentioned in my previous comment – Rory McCrossan Jul 18 '19 at 15:06
  • @RoryMcCrossan so i just should remove dataType: 'json' as in WebMethod i'm yet serializing the data and use result.d[0].TOTSC? If that is, still undefined.. – NiceToMytyuk Jul 18 '19 at 15:17
  • 1
    No you need to leave that and call `JSON.parse` on the `d` property of the response only. Given the state of the response in your question my previous example should work for you: `JSON.parse(result.d)[0].TOTSC` – Rory McCrossan Jul 18 '19 at 16:03

0 Answers0