Search code examples
jsonajaxresponse

Ajax Response Json data, are not always valid


My website is using ajax calls to add products to cart. Each time a customer presses "Add to Cart" button, there's an ajax request called. The Json data response is sometimes not valid or not formed correctly.

Using firefox developer tools, here's the response data in both ways:

Normal json response: The correct json response

Not valid json data response: Not valid json data response

1) What kind of issue is this?
2) Why is this happening in some cases and not other cases? Could it be the data itself causing this? 3) Possible solutions to this?


Solution

  • In general there are two possible cases where browser can't parse JSON data:

    1. Wrong Content-Type header
    2. Malformed JSON string

    In your case, as it sometimes works and sometimes doesn't it's probably the second one. There must be some characters in your response that are escaped in your server side code which are not valid in browser. All server side language have options when converting objects to JSON strings. you can check the invalid response in a JSON linter like https://jsonlint.com/ to see which part causes the problem then search for options to disable this behaviour in your server side code.