I have the following jQuery
and Ajax
codes
$("#grabIdCodeDetails").click(function() {
var idCodeForDetails = $("#idCode").val();
if (idCodeForDetails.trim() == "") {
errorFunction("Please key in an ID Code");
hidePreviousShownResult();
} else {
$.ajax({
type: "POST",
url: "fetchIdCodeDetailsFromDatabaseAjax.php",
data: {
idCodeForDetails: idCodeForDetails
},
success: function(fetchedDetails) {
var returnedData = JSON.parse(fetchedDetails);
alert(returnedData['needle']);
}
});
}
});
Following are the codes in fetchIdCodeDetailsFromDatabaseAjax.php
page
$resultArray = [];
array_push($resultArray, $DeviceName, $Start_Date, $Customer, $TotalPinCount, $NeedleType, $DeliveryDate);
$DeviceName = $resultArray[0];
$Start_Date = $resultArray[1];
$Customer = $resultArray[2];
$TotalPinCount = $resultArray[3];
$NeedleType = $resultArray[4];
$DeliveryDate = $resultArray[5];
echo json_encode(array(
'needle' => $NeedleType,
'deviceName' => $DeviceName,
'pinCount' => $TotalPinCount,
'startDate' => $Start_Date,
'endDate' => $DeliveryDate,
'customer' => $Customer
));
In the above $DeviceName, $Start_Date, $Customer, $TotalPinCount, $NeedleType, $DeliveryDate
have respective values. When I echo
, I can see the individual values.
But I am having Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>)
error while executing this. I read that this could be due to it is returning empty strings. But that is not the case. When I tried to inspect type of data returning on Ajax
success using alert(jQuery.type(fetchedDetails))
, it shows string. Does anyone know what is going wrong here?
2
Answers
I think there is some problem with your code. Simply just write:
You do not need array push etc.
For your front end try to console.log(fetchedDetails)
Alert won’t show details.
After that check your fetchedDetails and then use
JSON.parse(fetchedDetails)
or
JSON.parse(fetchedDetails.data)
You may have some status codes etc.
You have to return the JSON encoded array instead of echo. You can use typeOf() in jQuery to check the data type.