4

I have the error Uncaught SyntaxError: Unexpected token ILLEGAL in Chrome.

The code is

$("form#new_redemption").live('submit', function() {
  event.preventDefault();
  var that    = $(this);

  var action  = that.attr('action');
  var data    = that.serialize();

  $.ajax({
    type: "POST",
    url:  action,
    data: data,
    dataType: 'json',
    beforeSend: function(request) {
      request.setRequestHeader("Accept", "application/json");
    },
    success: function(res) {
      var response = JSON.parse(res.responseText); // <~~~ Unexpected token ILLEGAL
      if (response.message) {
        that.slideUp();
        $("#results").html(response.message).attr('class', 'notice').slideDown();
      }
      else if (response.url) {
        window.location = response.url 
      }
    },
    error: function(res) {
      var response = JSON.parse(res.responseText);
      $('#results').html(response.error).attr('class', 'error').slideDown();
    }
  });
  return false;
});

On errors, this code works great. But every time its a successful response I get an error. Is there a problem here? And is there a way in VIM to highlight illegal javascript characters in the code?

Thank you!

Eric Koslow
  • 2,004
  • 2
  • 21
  • 33
  • 2
    put `console.log(res.responseText);` before JSON.parse and show the output. – iafonov Aug 09 '11 at 14:41
  • The result coming back from your ajax call is no good. The parser is kicking out the error because the response is invalid json. As Mark suggests try running the result through a json validator. – kasdega Aug 09 '11 at 14:45
  • I get `undefined` for `res.responseText`. Is there a different property for successful responses? – Eric Koslow Aug 09 '11 at 14:47
  • Got is `res` is the `responseText` when there is no error. – Eric Koslow Aug 09 '11 at 14:49
  • > And is there a way in VIM to highlight illegal javascript characters in the code? https://github.com/scrooloose/syntastic – pdoherty926 Mar 02 '13 at 18:25

2 Answers2

2

Setting dataType to json will automagically parse the response JSON for you within the success callback.

Try this:

$("form#new_redemption").live('submit', function() {
  event.preventDefault();
  var that    = $(this);

  var action  = that.attr('action');
  var data    = that.serialize();

  $.ajax({
    type: "POST",
    url:  action,
    data: data,
    dataType: 'json',
    beforeSend: function(request) {
      request.setRequestHeader("Accept", "application/json");
    },
    success: function(res) {
      if (response.message) {
        that.slideUp();
        $("#results").html(response.message).attr('class', 'notice').slideDown();
      }
      else if (response.url) {
        window.location = response.url 
      }
    },
    error: function(res) {
      var response = JSON.parse(res.responseText);
      $('#results').html(response.error).attr('class', 'error').slideDown();
    }
  });
  return false;
});
circusbred
  • 1,240
  • 8
  • 8
  • What is going on here? I see that this fixes his issue, but why? – Toby Allen Mar 06 '12 at 16:01
  • @TobyAllen Although I can't see it in the OP code, it's possible that you an invisible character was causing the issue. See [this question](http://stackoverflow.com/q/12719859/825789) and answer for details. – bfavaretto Oct 08 '12 at 16:00
  • Unrelated the the linked question. The error came when trying to parse the response when jQuery already parses the response. The difference is in the `success` callback; I removed this line: `var response = JSON.parse(res.responseText);` – circusbred Oct 08 '12 at 19:22
0

To expand on one of the comments above, I was getting this error because of a problem in the JSON results that were being returned. Specifically, one of the string values in the JSON response data had an unescapted double quote in it. In my case, it was my own Ajax function that I was calling, so what I did to fix it was to escape the double quotes on the server before returning the JSON data. Then I discovered that I had the same problem with newline characters, so I used a str_replace call that I found in another post: PHP's json_encode does not escape all JSON control characters

function escapeJsonString($value) {
    # list from www.json.org: (\b backspace, \f formfeed)    
    $escapers =     array("\\",     "/",   "\"",  "\n",  "\r",  "\t", "\x08", "\x0c");
    $replacements = array("\\\\", "\\/", "\\\"", "\\n", "\\r", "\\t",  "\\f",  "\\b");
    $result = str_replace($escapers, $replacements, $value);
    return $result;
}
Community
  • 1
  • 1
Eric Barr
  • 3,999
  • 5
  • 29
  • 42