I was asked to perform ajax post request to the php script for some of the data(student name and student gender which are yyyyty and F respectively) from the last row. By default, I want to show all the data when performing the ajax post. Then, I want to echo the selected data using the ajax post request. My code is found below............ When I performed the ajax post i got the error which states
Status Code: 200
ErrorThrown: SyntaxError: Unexpected token { in JSON at position 1634
jqXHR.responseText:
[{"student_id":"1","student_name":"Ashfur","student_gender":"F","student_age":"19","student_religion":"Muslim","student_course_id":"1"},{"student_id":"2","student_name":"Irfan","student_gender":"M","student_age":"17","student_religion":"Islam","student_course_id":"4"},{"student_id":"3","student_name":"Alice","student_gender":"F","student_age":"21","student_religion":"Chinese","student_course_id":"2"},{"student_id":"4","student_name":"Mohit","student_gender":"M","student_age":"20","student_religion":"Christian","student_course_id":"6"},{"student_id":"5","student_name":"Susy","student_gender":"F","student_age":"27","student_religion":"Chirstian","student_course_id":"5"},{"student_id":"6","student_name":"Ida","student_gender":"F","student_age":"23","student_religion":"Islam","student_course_id":"3"},{"student_id":"7","student_name":"Abdul","student_gender":"M","student_age":"22","student_religion":"Islam","student_course_id":"1"},{"student_id":"8","student_name":"Ernest","student_gender":"M","student_age":"25","student_religion":"Chinese","student_course_id":"4"},{"student_id":"9","student_name":"Wei Ling","student_gender":"F","student_age":"23","student_religion":"Chinese","student_course_id":"2"},{"student_id":"10","student_name":"Ashtae","student_gender":"M","student_age":"23","student_religion":"Islam","student_course_id":"4"},{"student_id":"11","student_name":"Jasmine","student_gender":"F","student_age":"23","student_religion":"Chinese","student_course_id":"2"},{"student_id":"65656","student_name":"yyyyty","student_gender":"F","student_age":"65","student_religion":"anything","student_course_id":"009090"}]{"student_name":"yyyyty","student_gender":"F"}
My html file
<html>
<head>
<script type="text/javascript" src="/Cesium-1.34/ThirdParty/jquery-1.11.3.min.js"></script>
</head>
<div id="resulte"</div>
<script type="text/javascript">
showData();
function showData()
{
$.ajax({
type: "post",
url: "student.php",
dataType: "json",
data: {
lastOnly: true,
},
success: function(data){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('An error occurred... Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information!');
$('#resulte').html('<p>Status Code: '+jqXHR.status+'</p><p>ErrorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p><div>'+jqXHR.responseText + '</div>');
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('errorThrown:');
console.log(errorThrown);
},
});
};
</script>
</body>
</html>
In the php script
<?php
$conn = mysqli_connect('localhost','root','netwitness') or die ("Could not connect database");
$db = mysqli_select_db($conn,'abdpractice') or die ('Could not select database');
$result = mysqli_query($conn,"select * from student");
$json_array = array();
while ($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
echo json_encode($json_array);
if (!isset($_POST["lastOnly"])){
} else {
$response = [];
$response['student_name'] = $json_array[count($json_array)-1]['student_name'];
$response['student_gender'] = $json_array[count($json_array)-1]['student_gender'];
echo json_encode($response);
}
?>
I want to echo the whole data by default. when I performed the ajax post request I want to echo the selected data again... Please help me.
Thank you.
The error tell you what happens.
You have an invalid JSON:
[{"student_id":"1","student_name":"Ashfur","student_gender":"F","student_age":"19","student_religion":"Muslim","student_course_id":"1"},{"student_id":"2","student_name":"Irfan","student_gender":"M","student_age":"17","student_religion":"Islam","student_course_id":"4"},{"student_id":"3","student_name":"Alice","student_gender":"F","student_age":"21","student_religion":"Chinese","student_course_id":"2"},{"student_id":"4","student_name":"Mohit","student_gender":"M","student_age":"20","student_religion":"Christian","student_course_id":"6"},{"student_id":"5","student_name":"Susy","student_gender":"F","student_age":"27","student_religion":"Chirstian","student_course_id":"5"},{"student_id":"6","student_name":"Ida","student_gender":"F","student_age":"23","student_religion":"Islam","student_course_id":"3"},{"student_id":"7","student_name":"Abdul","student_gender":"M","student_age":"22","student_religion":"Islam","student_course_id":"1"},{"student_id":"8","student_name":"Ernest","student_gender":"M","student_age":"25","student_religion":"Chinese","student_course_id":"4"},{"student_id":"9","student_name":"Wei Ling","student_gender":"F","student_age":"23","student_religion":"Chinese","student_course_id":"2"},{"student_id":"10","student_name":"Ashtae","student_gender":"M","student_age":"23","student_religion":"Islam","student_course_id":"4"},{"student_id":"11","student_name":"Jasmine","student_gender":"F","student_age":"23","student_religion":"Chinese","student_course_id":"2"},{"student_id":"65656","student_name":"yyyyty","student_gender":"F","student_age":"65","student_religion":"anything","student_course_id":"009090"}]{"student_name":"yyyyty","student_gender":"F"}
The last part of the JSON is invalid: {"student_name":"yyyyty","student_gender":"F"}
You could use tools like https://jsonformatter.curiousconcept.com/ to see if your JSON is valid or not.
As Lawrence Cherone said, you could use json_encode.
$myFinalJSON = json_encode($myFirstJSON);
If you want both the results to be returned in a single json response then you have to combine both the arrays
while ($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
//echo json_encode($json_array);
if (!isset($_POST["lastOnly"])){
} else {
$response = [
'student_name' = $json_array[count($json_array)-1]['student_name'],
'student_gender' = $json_array[count($json_array)-1]['student_gender']
];
}
$json_array[] = $response;
echo json_encode($json_array);
Send AJAX request on window load so that all the records will be displayed and when you fire a button to fetch last data you will get the last one from your records.
NOTE : Usually to fetch specific record we send a search key which is used to specify WHERE clause condition and based on that search key we execute our Sql/Mysql query.
Here, I have not send any search key and each time all records get fetched unccessarily ( causes performance issues ). Try avoiding this but just to clarify, in your case i just used a single button to trigger if-else condition and fetched all records every time just to demonstrate ajax request based on condition with php.
Below is the code
HTML file
<form method='post'>
<button id='last'>Fetch Last</button>
</form>
<div id="result"></div>
JS File
$(window).load(function() {
let val = 'all';
showData(val);
});
$('#last').on('click', function() {
let val = $(this).prop('id');
showData(val);
});
function showData(data)
{
$.ajax({
type: "post",
url: "student.php",
dataType: "json",
data: {
lastOnly: data,
},
success: function(data){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('An error occurred... Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information!');
$('#resulte').html('<p>Status Code: '+jqXHR.status+'</p><p>ErrorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p><div>'+jqXHR.responseText + '</div>');
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('errorThrown:');
console.log(errorThrown);
},
});
};
PHP File
$conn = mysqli_connect('localhost','root','netwitness') or die ("Could not connect database");
$db = mysqli_select_db($conn,'abdpractice') or die ('Could not select database');
$result = mysqli_query($conn,"select * from student");
$response = array();
while ($row = mysqli_fetch_assoc($result))
{
$response[] = $row;
}
if (isset($_POST["lastOnly"]) && $_POST["lastOnly"] === 'last'){
$size = count($json_array);
$response['student_name'] = $json_array[$size-1]['student_name'];
$response['student_gender'] = $json_array[$size-1]['student_gender'];
echo json_encode($response);
} else {
echo json_encode($response);
}
Also one thing to be noted that is -
Use .done()
and .fail()
methods to handle ajax response instead of using success
and error
.
Hope, you will get some help from this explanation. :) :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.