Home:ALL Converter>Passing multiple PHP arrays to JavaScript on AJAX Success

Passing multiple PHP arrays to JavaScript on AJAX Success

Ask Time:2013-04-15T00:49:58         Author:AnchovyLegend

Json Formatter

I am having a hard time passing arrays from an PHP page to JavaScript using an AJAX request.

I will have to pass the information from multiple php arrays to javascript. I am aware I can use json_encode for this, however, I am having a hard time implementing this. The $name array don't seem to be getting passed, in addition, I will need all arrays to be passed to javascript not just $name.

I appreciate any suggestions with this.

Many thanks in advance!

This is what I tried for passing the $name array (code snippets):

PHP

while($row2 = mysqli_fetch_array($results2)){
    $name[$i] = $row2['prod_name'];
    $price[$i] = $row2['price'];
    $upc[$i] = $row2['upc'];
    $quantity[$i] = $row2['quantity'];
}
echo json_encode($name);

AJAX

$.ajax({
    url: "invoice-get-data.php?hotItems=1&getArrays=1",
    dataType: "json",
    success: function(data){
        alert(data[0]);
    }
});

Author:AnchovyLegend,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/16001598/passing-multiple-php-arrays-to-javascript-on-ajax-success
zavg :

Back-end:\n\nwhile($row2 = mysqli_fetch_array($results2)){\n $name[] = $row2['prod_name'];\n $price[] = $row2['price'];\n $upc[] = $row2['upc'];\n $quantity[] = $row2['quantity'];\n}\necho json_encode(array($name, $price, $upc, $quantity));\n\n\nFront-end:\n\n$.ajax({\n url: \"invoice-get-data.php?hotItems=1&getArrays=1\",\n dataType: \"json\",\n success: function(data){\n data = JSON.parse(data);\n alert(data[0]);\n }\n});\n",
2013-04-14T16:53:15
yy