jquery - ajax receives response from php but can not use with ajax

Solution:
If the response from your PHP is:
<{"response" : "2"}
This would be an incorrectly formatted JSON string. This would be created by the extra<
you have at the beginning of the document. I would advise you have the following PHP Opener:
<?php
This should correct the issue so the JSON Response would be:
{"response" : "2"}
It will be properly parse at that point.
Example
<?php
$id = (int)$_POST['reccount'];
$link = mysqli_connect("localhost", "root", "", "testsite");
header('Content-Type: application/json');
if($link === false){
die("{\"error\": \"Could not connect. " . mysqli_connect_error() . "\"}");
}
$sql = "SELECT * FROM paper WHERE ID=$id";
if(mysqli_query($link, $sql)){
$result = mysqli_query($link, $sql);
while($row = mysqli_fetch_array($result)) {
$data['response']= $row['response'];
$data['ansnum'] = $row['q_no'];
}
echo json_encode($data);
} else {
echo "{\"error\": \"Unable to execute $sql. " . mysqli_error($link) . "\"}";
}
mysqli_close($link);
?>
In my example, I cast the POST data to Integer to help ensure a malicious user does not get to send anything other than a digit. I also only send JSON data, even when sending an error. Using theheader()
helps define the data for the browser.
$.ajax({
type:"POST",
url:"<?php echo base_url();?>/shortfiles/loadans.php",
data: {reccount: reccount},
dataType:"JSON",
success: function(data){
console.log(data);
if(data.error !== undefined){
alert(data.error);
} else {
$('#respond').text(data.response);
}
}
});
Hope that helps.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: installation failed, reverting ./composer.json and ./composer.lock to their original content.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.