I have a "Student" object/model created in PHP and I use its setter methods to set its fields with the values on each cell from CSV per row. I'm having troubles parsing the array of students to a JSON object.
read_student_csv.php
echo json_encode(getPopulatedStudentCSV());// doesn't seem to parse correctly
function getPopulatedStudentCSV(){
$studentList = [];
$csvFile = $_FILES["csvFile"]["tmp_name"];
$student_csv_temp_file_location = $_FILES["csvFile"]["tmp_name"];
$row = 1;
$handle = fopen($student_csv_temp_file_location, "r");
if ($handle !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$rowCellCount = count($data);
//echo "<p> $rowCellCount fields in row: $row: <br /></p>\n";
$row++;
$student = new Student();
for ($cell=0; $cell < $rowCellCount; $cell++) {
if($row != 2){
if($cell == 0) //student number
{
$student->setStudentNo($data[$cell]);
}
else if($cell == 1) //student last name
{
$student->setLastName($data[$cell]);
}
else if($cell == 2) //student first name
{
$student->setFirstName($data[$cell]);
}
else if($cell == 3) //student middle name
{
$student->setMiddleName($data[$cell]);
}
}
}
$studentList[] = $student;
}
fclose($handle);
}
return $studentList;
}
jsfile
function displayCSVPreview(){
var csvFile = $('#browseFiles')[0].files[0];
var formData = new FormData();
formData.append('csvFile', csvFile);
//alert("FormData: "+formData);
$.ajax({
url: 'script/read_student_csv.php',
type: 'POST',
data: formData,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function (students) {
console.log("Students : " + students);
console.log("Length: "+ students.length);
for(var i = 1; i < students.length; i++){
$('#studentcsvpreviewtable').append(
"<tr>"+
"<td>" + students[i] +"</td>" +
"<td>" + students[i]['lastName'] + "</td>" +
"<td>" + students[i]['firstName'] + "</td>" +
"<td>" + students[i]['middleName'] + "</td>" +
"</tr>"
);
}
},
error: function (x, e) {
handleError(x,e);
}
});
}
student[i]
returns every single character of the value returned by the response from read_student_csv.php's getPopulatedStudentsCSV()
function.
If I do student[i]['lastName']
, I get an "undefined" value.
I don't know how to properly parse the $studentList[]
to a JSON with keys and values. json_encode()
doesn't seem to do it correctly.
The two lines below returns
console.log("Students : " + students);
console.log("Length: "+ students.length);
Students : [{"studentNo":null,"lastName":null,"firstName":null,"middleName":null},{"studentNo":"12345","lastName":"Doe","firstName":"John Sam","middleName":"Man"},{"studentNo":"23456","lastName":"Nuggets","firstName":"Ashton","middleName":"Alvin"}]
Length: 256
Shows length of 256 because I think it counts every single character from the output. Which isn't correct.
I'd appreciate any suggestion.
Thank you.