VM2022:2 Uncaught SyntaxError: Unexpected token : on AJAX call

Viewed 1459

I send a GET request from the back end to get the json response. I got this error.

Uncaught SyntaxError: Unexpected token :
at DOMEval (jquery-3.3.1.js:111)
at Function.globalEval (jquery-3.3.1.js:345)
at text script (jquery-3.3.1.js:9640)
at ajaxConvert (jquery-3.3.1.js:8787)
at done (jquery-3.3.1.js:9255)
at XMLHttpRequest. (jquery-3.3.1.js:9548)

enter image description here

My AJAX request code is:

$.ajax({
  type: "GET", //rest Type
  dataType: 'jsonp', //mispelled
  url: "{{ url_for('live') }}",
  contentType: "application/json",
  success: function (msg) {
    console.log(msg);
    for (var i = 0; i < msg.counters.length; i++) {
      var counter = msg.counters[i];
      console.log(counter);
    }
  }, 
  error: ErrorMsg
});

I have no idea where I went wrong. please help.

1 Answers

You have two issues. Firstly the response will already be deserialised for you buy jQuery. Deserialising it again will cause the error you see. Secondly, the response format appears to be JSON, not JSONP, so the dataType property needs to be amended as well. Try this:

$.ajax({
  type: "GET",
  dataType: 'json',
  url: "{{ url_for('live') }}",
  contentType: "application/json",
  success: function (msg) {
    for (var i = 0; i < msg.counters.length; i++) {
      var counter = msg.counters[i];
      console.log(counter);
    }
  }, 
  error: ErrorMsg
});
Related