i am using dataTables to display data from a MySQL database by using PHP, Ajax, and jQuery. The data i am showing are numbers and everything works fine.
Here is my php script
require_once '../core/init4ajax.php';
$loteria=$_POST['loteria'];
$lotto = new Lotto();
$ultimos_resultados=$lotto->last_results($loteria,20);
function objectToArray($d)
{
if (is_object($d)) {
// Gets the properties of the given object
// with get_object_vars function
$d = get_object_vars($d);
}
if (is_array($d)) {
return array_map(__FUNCTION__, $d);
} else {
// Return array
return $d;
}
}
$new_array = objectToArray($ultimos_resultados);
$result = array();
echo '[';
foreach ($new_array as $new_array2) {
echo '[';
foreach ($new_array2 AS $value){
/********The following piece of code is used to add a leading zero to single digit numbers********/
/*if (1 == strlen($value)) {
$zero=0;
$value = $zero.$value;
}*/
echo $value;
if($value!==end($new_array2)){ //referencias: http://stackoverflow.com/a/8780881/1883256
echo',';
}
}
echo ']';//referencias: http://www.mydigitallife.info/how-to-access-php-array-and-multidimensional-nested-arrays-code-syntax/
if($new_array2!==end($new_array)){
echo ',';
}else{ echo '';}
}
echo ']';
Here is the output sample of the php script:
[[2740,3,9,21,27,46,48],[2741,3,4,13,22,27,29], ... ,[2757,32,34,35,36,50,55]]
And here is the ajax code.
$(document).ready(function() {
$.ajax({
url: "ajax/default_chart_numbers_table.php",
type: "post",
data: {loteria: 'melate'},
success : function (resp){
// would look something like ['val1','val2', 'etc']
var column_data = $.parseJSON(resp);
//alert(column_data);
// adding data to datatables
for (var j=0;j<=column_data.length-1;j++){
// adding each row with its column data
//iterating values to add leading zeros to single digits:
$('#dataTables-melate').dataTable().fnAddData(column_data[j]);
}
},
error: function(jqXHR, textStatus, ex) {
console.log(textStatus + "," + ex + "," + jqXHR.responseText);
}
});
} );
I have realized that i want the single digit numbers to be lead by a zero, e.g. 4, should be shown as 04.
By adding the code in order to add a leading zero (this piece of code is already in my php code but commented):
if (1 == strlen($value)) {
$zero=0;
$value = $zero.$value;
}
Now the php code returns the array the way i want it:
[[2740,03,09,21,27,46,48],[2741,03,04,13,22,27,29], ... ,[2757,32,34,35,36,50,55]]
however, now from the ajax script i get the following error:
SyntaxError: JSON.parse: expected ',' or ']' after array element at line 1 column 9 of the JSON data
and the data is no longer displayed in the dataTables.
Why is this happening? How can i fix it?
I HAVE FIXED IT: I just had to add double quotes to those single edit numbers:
if (1 == strlen($value)) {
$zero=0;
$value = '"'.$zero.$value.'"';
}
And that did the trick! ☺