parsererror Requested JSON parse failed

Solved
New Member
2 0 0

I have used scriptTag Api to embed script in my store front, then I'm sending an ajax request from that script to my server and I'm sending json data but error said "parsererror" (Requested JSON parse failed). This error occurs every time, I have validate my json here https://jsonlint.com/ and it says "Valid JSON".

here's ajax code which is at shopify
$.ajax({
    url: url,
    type: "GET",
    dataType: 'jsonp',
     contentType: "application/json",
     headers: {
         "Access-Control-Allow-Origin": "*",
         "Access-Control-Allow-Headers": "origin, content-type, accept"
     },
    data: {
        'product_id':productId
     },
     success: function(data) //never comes here
     {
         console.log(data);
     },
     error: function (jqXHR, exception) {
          var msg = '';
          console.log(jqXHR);
          if (jqXHR.status === 0) {
              msg = 'Not connect.\n Verify Network.';
          } else if (jqXHR.status == 404) {
              msg = 'Requested page not found. [404]';
          } else if (jqXHR.status == 500) {
              msg = 'Internal Server Error [500].';
          } else if (exception === 'parsererror') {
              msg = 'Requested JSON parse failed.';
          } else if (exception === 'timeout') {
              msg = 'Time out error.';
          } else if (exception === 'abort') {
              msg = 'Ajax request aborted.';
          } else {
              msg = 'Uncaught Error.\n' + jqXHR.responseText;
          }
          console.log(msg);
     },
});

 

and here's the code which is on my server

 

$responseArray = array(
      'htmldata' => $data
);
header("Cache-Control: no-transform,public,max-age=300,s-maxage=900");
header('Content-Type: application/json');
$jsonResponse = json_encode($responseArray);
echo $jsonResponse;

0 Likes
Shopify Partner
77 0 18

I may be wrong, but it looks like your questions is not specific to the Shopify platform, correct?

A script registered via a ScriptTag behaves like any other piece of JavaScript code.

So, without more context, I would assume the issue you are facing is related to the correct use of jQuery / php.

I would recommend posting on other forums (e.g. StackExchange) to get help with general programming questions.

Bart Coppens | Limoni Apps | Building apps for Shopify since 2016
0 Likes
Highlighted

Success.

Shopify Partner
5 1 1

Try dataType: 'json', instead jsonp, as the php is not returning the function callback in the output.

0 Likes
New Member
2 0 0

Thanks @Patrick_Phelan,
    Since I can control the server side, so i returned a callback function in php.

0 Likes