Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this invalid JSON?

Tags:

json

jquery

I am sending some data from an server back to a page. It looks like valid JSON to me, yet, it is being caught/handled by the error handler in my jQuery.ajax() call.

This is the error message displayed:

Error: Invalid JSON: ({"id":"#settingsResult","payload":"<form id=\"pwd_change_frm\" action=\"post\">\n    <div>\n        <div>\n            <div><\/div>\n            <div><label for=\"changepwd_password\">New Password<\/label><\/div>\n            <div><input type=\"password\" name=\"changepwd[password]\" title=\"Enter new password\" style=\"width:258px;\" id=\"changepwd_password\" \/><\/div>\n        <\/div>\n        <div class=\"spacer\">&nbsp;<\/div>\n        <div>\n            <div><\/div>\n            <div><label for=\"changepwd_password_confirm\">Confirm New Password<\/label><\/div>\n            <div><input type=\"password\" name=\"changepwd[password_confirm]\" title=\"Retype new password)\" style=\"width:258px;\" id=\"changepwd_password_confirm\" \/><\/div>\n        <\/div>\n        <div class=\"spacer\"><\/div>\n        <div><img id=\"pwd_chg_btn\" class=\"submit_btn\" src=\"\/images\/button_submit.gif\" alt=\"Button_submit\" \/><\/div>\n    <\/div>\n    <input type=\"hidden\" name=\"changepwd[_csrf_token]\" value=\"1b7f3529797245c0fc43c3ddf5ade30d\" id=\"changepwd__csrf_token\" \/><\/form>\n<div class=\"spacer\"><\/div>"})

As an aside, FF Firebug correctly parses the returned data and displays ot correctly - which is why I dont understand why jQuery can't seem to handle it.

here is the bit of code that makes the call:

jQuery.ajax({
  type: 'POST',
  url: '/some_url?id='+this.id,
  timeout: 2000,
  success: function(result){ jQuery(result.id).html(result.payload); },
  error: function (xhr, ajaxOptions, thrownError){ alert('Error: '+ thrownError); }
});
like image 955
oompahloompah Avatar asked May 09 '26 05:05

oompahloompah


1 Answers

Probably useless to answer at this point, but I just thought I'd note that the issue does somehow seem to be with $.parseJSON().

If I remove all occurrences of \n, and replace all occurrences of \" with \', it works.

Alternatively, if I double escape them, it works.

\\n
\\"

...which would make sense since I believe jQuery simply does an eval() (or effectively the same thing), so I guess escaping the " is terminating the string and escaping the \n is introducing a newline character where it would be invalid.

like image 150
user113716 Avatar answered May 11 '26 19:05

user113716