jQuery.parseJSON() not decoding a valid Json string on a Windows server

I have this wordpress javascript function code running and working on a Linux server along with a php function “get_form_data”.

jQuery.ajax({  
              type: "POST",  
              url: MyAjax.ajaxurl, 
              data: {action: "get_form_data", id: id, cat_id: cat_id},

              success: function(r) {

                            //alert(r);
                            var response = jQuery.parseJSON(r);
               }
});

I migrated the wordpress site to a Windows 8 Server with IIS and PHP and now it’s throwing an error in the parseJSON line like this (it’s only happening in the Windows environment):

Read More

SyntaxError: JSON.parse: unexpected character at line 2 column 1 of the JSON data

The string received from the PHP function is being retrieved without any problem and the Ajax code gets to the success state right before the string is parsed (by enabling the commented alert line), but once the Json parse function tries to decode it, it crashes. The Json string is encoded by the PHP function with json_encode().

This is the string received by the Ajax function, it’s a valid string as far as I know.

[“New Day”,”2″,”One Song”,”John”,”2014-12-08 13:04:56″,”1843″,”22″]

Related posts

Leave a Reply

4 comments

  1. Somehow, the $.parseJSON and $.parseJSON functions don’t work for me on IIS 7 with php but they do work on Apache. It always crashed on me on IIS. I tried different things to convert the json encoded string in javascript retrieved from the PHP function and tried to filter out slashes and break lines to no avail. The online json viewers showed that it was a valid json string.

    What worked for me was using the old fashioned eval (“(” + r + “)”) and it worked the same as the json parse function with the disadvantage that apparently is not safe to use it, but I had no other solution.

  2. That seems to be a valid JSON array to me. I tested it in this way with no issues:

       var rawJson = '["New Day","2","One Song","John","2014-12-08 13:04:56","1843","22"]';
    
    var json = JSON.parse(rawJson);
    
    for(i = 0; i < json.length; i++) {
        console.log(json[i]);
    }
    

    JSON parse converts a string to JSON, so I threw single quotes around your array to make it a string.

    Perhaps you could try this:

    jQuery.ajax({
        url: MyAjax.ajaxurl, 
        data: {action: "get_form_data", id: id, cat_id: cat_id},
        dataType: "json",
        success: function(data) {
            // r should be the returned array
            for(i = 0; i < data.length; i++) {
                console.log(data[i]);
            }
        }
    });
    
  3. Split the Return Data:

    In c# asmx:
    string _json = “”;

    _json = getJsonFunction(_dataSet.Tables[0]);
    _json += ‘`’ + getJsonFunction(_dataSet.Tables[1]);

    in Jquery:
    Data = JSON.parse(res.d.split(‘`’)[0]);