Reputation: 1264
EDIT
I simplified the array that I was trying to JSON encode in php script. The returnArr in php script now has only one key, value pair and still I am getting invalid character error:
PHP script:
$returnArr["a"] = "val";
er('Content-type:application/json;charset=utf-8');
echo(json_encode($returnArr));
I am trying to return an array(in the form of key=>value) to my ajax call from the server side php script. Ajax receives the response but is unable to parse the JSON data returned by server. Gives error "Invalid character" on the line where I am parsing the returned data inside ajax success function.
Below is my server side script:
$returnArr = Array();
header('Content-Type: application/json');
foreach($selectUpdatedRecord as $eachRow)
{
$key = $eachRow['cat_id'];
$htmlStr = '<td>'.$eachRow["cat_id"].'</td>
<td>'.$eachRow["cat_name"].'</td>
<td>
<select name="statCat-catId-'.$eachRow["cat_id"].'" disabled="disabled">
<option value="'.$eachRow["cat_status"].'" selected="selected">'.$eachRow["cat_status"].'</option>
<option value="Enabled">Enabled</option>
<option value="Disabled">Disabled</option>
</select></td>
<td>'.$eachRow["created_at"].'</td>
<td><button type="submit" id="save-cat-'.$eachRow["cat_id"].'" name="save-cat-'.$eachRow["cat_id"].'" class="btn btn-info save-ind">Save</button></td>
<td><input type="checkbox" class="select_cats" name="cat_edit_array" value="'.$eachRow['cat_id'].'"></td>
';
$returnArr[$key] = $htmlStr;
}
echo json_encode($returnArr);
FYI, the $key is numeric and the $htmlStr variable will hold some table cells with values. I would use the $key to identify some unique rows and populate the rows with the corresponding html content. the console.log() call is just a test to see whether parsing is successful. And here is the ajax function:
$.ajax({
type: "GET",
url: "ajax_catEdit_loader.php",
data:{'get_updatedData':sendDataToAjax},
success: function(returnedText) {
console.log(JSON.parse(returnedText)); //--->error on this line
error: function(xhr, status, error) {
alert("failed");
console.log("ajax failed: "+error);
}
});
I have tried to include the datatype: as JSON in the ajax call and omit the JSON.parse call but still same result.
Would really appreciate some help.
Upvotes: 1
Views: 4805
Reputation: 1181
The problem was indeed in JSON.parse, however, there is a bit more to it than that.
Problem-1: JSON.parse method is expecting string as argument. So instead when you provide an Array or Object, you'll get the error. Check the following example CODE:
var obj = {};
try {
JSON.parse( obj );
}
catch( err ) {
console.error( err );
}
Problem-2: Now, the second problem is NOT json_encode() in PHP as you've probably understood it. Because json_encode() PHP function is indeed returning String. However, since you are sending JSON MIME type header:
header('Content-Type: application/json');
jQuery is receiving it as a JSON object.
By default, PHP returns output as html, so if you remove the header, the error will not be there. So clear browser cache & try by removing the header or by using any one of the following headers:
header('Content-Type: text/plain');
// or the default one:
// header('Content-Type: text/html');
Problem-3: You also need to understand the dataType property of jQuery ajax function.
According to the documentation, dataType is defined as:
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).
So, when you are not specifying the dataType, jQuery is automatically getting it as JSON because of your MIME type header. Thus, even when you specify:
dataType: 'json',
the same problem doesn't go away. Now guess what will happen if we specifically tell jQuery to receive data as text:
dataType: 'text',
You've probably guessed it right. Once we mention that we want to receive the data as text, even if in PHP we send JSON MIME type header, jQuery will consider it as text and JSON.parse will execute without error.
Note: while you test by changing the header, remember that browser will cache the result. So you'll need to clear browser cache every time you test with a new header or call the script with an additional random query string like this:
url: "ajax_catEdit_loader.php?rand=" + Math.random(),
You can also check what type of data browser is receiving (as html, as text, as json etc.) from the Network panel of the browser's Developer Tool (Data type will be shown in the Type column).
Upvotes: 1