0

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! ☺

Pathros
  • 10,042
  • 20
  • 90
  • 156
  • 1
    Why not use `json_encode()` in your PHP script? – Sirko May 17 '14 at 21:01
  • because it didn't work that way. Alex helped me with this [here](http://stackoverflow.com/a/23692858/1883256) – Pathros May 17 '14 at 21:05
  • Out of curiosity, why do you need leading zeros for each single digit number? – Mr. Meeseeks May 17 '14 at 21:24
  • 1
    @VincentWilkie Because when i look for a single digit number, other unnecesary results appear. For example, if i search for a number "5", the numbers such as 50, 51, ... 59, will appear as well. If i search for a number 10, only rows with that number will appear. That is why i want a leading zero. Should you have any other suggestion, i'll be glad to know! :) – Pathros May 18 '14 at 04:58
  • Is there any reason you can't use `echo json_encode($multi_dimensional_array)` in your PHP script? – Mr. Meeseeks May 18 '14 at 16:42
  • All right, i have just fixed it! I edited my script above for more detail ;) – Pathros May 19 '14 at 01:28

2 Answers2

1

Adding a leading zero changes a javascript "number" to a "string". So JSON.parse returns an error expecting numbers (eg: 4) but instead sees a string (eg: "04").

In the picture below, you can see that I have ran two commands that try to parse a string into JSON. In the first command, the second item in the first array is 03 and outputs a SyntaxError. In the second command, The 03 was changed to 3 and now it parses properly.

JSON.parse example

I would recommend researching how to add data to the datatable without leading zeros in order for the table to show up properly and then change how the numbers are viewed/displayed

I would also recommend researching json_encode() to echo json from PHP.

I use json_encode() to echo json from PHP all the time to make sure I get the proper data output when making AJAX calls.

Mr. Meeseeks
  • 1,841
  • 2
  • 21
  • 37
1

It has nothing to do with the leading zeros. This is because you treat the output as JSON, which it is not. It is an array of arrays. The error is caused by the line :

var column_data = $.parseJSON(resp);

Try test the output / supposed JSON with http://jsonlint.com. Example how it could work :

var column_data = [
     [2740,3,9,21,27,46,48],
     [2741,3,4,13,22,27,29],
     [2757,32,34,35,36,50,55]
];

var dataTable = $('#dataTables-melate').dataTable()

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:
  dataTable.fnAddData(column_data[j]);
}

see demo -> http://jsfiddle.net/jPLSf/

davidkonrad
  • 83,997
  • 17
  • 205
  • 265