aguisa
asked on
Javascript to read PHP array
Hi. I have a PHP program which I want to return an ARRAY that can be read using JAVASCRIPT json.
Can anyone tell me what is the best way to do this?
Thsnk.
Can anyone tell me what is the best way to do this?
Thsnk.
ASKER
My PHP Array happens to be a recordset, can I use it as well?, and could you provide a small example?
thanks,
thanks,
If you are using older version the you can use this
function array_to_json_string($arra ydata) {
$output = "";
$output .= "{";
foreach($arraydata as $key=>$val){
if (is_array($val)) {
$output .= "\"".$key."\" : [{";
foreach($val as $subkey=>$subval){
$output .= "\"".$subkey."\" : \"".$subval."\",";
}
$output .= "}],";
} else {
$output .= "\"".$key."\" : \"".$val."\",";
}
}
$output .= "}";
return $output;
}
function array_to_json_string($arra
$output = "";
$output .= "{";
foreach($arraydata as $key=>$val){
if (is_array($val)) {
$output .= "\"".$key."\" : [{";
foreach($val as $subkey=>$subval){
$output .= "\"".$subkey."\" : \"".$subval."\",";
}
$output .= "}],";
} else {
$output .= "\"".$key."\" : \"".$val."\",";
}
}
$output .= "}";
return $output;
}
You can create an array, and loop through the recordset and add each record into the array.
Related question:
https://www.experts-exchange.com/questions/24436681/PHP-recordset-to-array.html
Related question:
https://www.experts-exchange.com/questions/24436681/PHP-recordset-to-array.html
$result = mysql_query("SQL QUERY HERE");
$rows = array(); // create empty array
while($row = mysql_fetch_assoc($result)) // fetch rows
$rows[] = $row; // append row to array
ASKER
I have now the Recordset in Javascript, but if I want to see its contents, it shows:
["Array","Array"]
How can I extract its contents using the JAVASCRIPT side?
["Array","Array"]
How can I extract its contents using the JAVASCRIPT side?
ASKER
I used the following code in PHP:
$nrows = mysql_num_rows($conf);
$x= 0;
$rows = Array();
while ($row = mysql_fetch_array($conf)){
$rows[] .= $row;
}
$retval .= json_encode($rows);
echo "{'retval':'" . $retval . "','nrows':'".$nrows ."'}";
///////////////////JAVASCR IPT PART IS///////////////////////
var xresult = "";
while (x <= json.nrows){
xresult += result;
x++;
}
$("#detallecotizacion").ht ml(result) ;
I want detallecotizacion to show array contents in a manageable way.
thanks
$nrows = mysql_num_rows($conf);
$x= 0;
$rows = Array();
while ($row = mysql_fetch_array($conf)){
$rows[] .= $row;
}
$retval .= json_encode($rows);
echo "{'retval':'" . $retval . "','nrows':'".$nrows ."'}";
///////////////////JAVASCR
var xresult = "";
while (x <= json.nrows){
xresult += result;
x++;
}
$("#detallecotizacion").ht
I want detallecotizacion to show array contents in a manageable way.
thanks
ASKER
Sorry, the javascript part is something like this instead:
$.ajax({
type: "GET", //HTTP GET
url: "ln_new_envoices.php",
data: "funcion=16&ndoc="+ndoc,
dataType: "json",
success: function(json) {
var nrows = json.nrows;
var result = 0;
var x = 0;
result = json.retval;
$("#dgcargardocumento").di alog("clos e");
$.ajax({
type: "GET", //HTTP GET
url: "ln_new_envoices.php",
data: "funcion=16&ndoc="+ndoc,
dataType: "json",
success: function(json) {
var nrows = json.nrows;
var result = 0;
var x = 0;
result = json.retval;
$("#dgcargardocumento").di
ASKER
HOW DO I READ THE ARRAYS IN JAVASCRIPT?
Firstly, I don't think you can do this:
$retval .= json_encode($rows);
echo "{'retval':'" . $retval . "','nrows':'".$nrows ."'}";
It should simply be this:
echo json_encode($rows);
To return another JSON value (nrows), possibly need to perform another different AJAX call.
$retval .= json_encode($rows);
echo "{'retval':'" . $retval . "','nrows':'".$nrows ."'}";
It should simply be this:
echo json_encode($rows);
To return another JSON value (nrows), possibly need to perform another different AJAX call.
ASKER
the thing is that I also need to return nrows.
Your problem here is that PHP is a SERVER side scripting language whereas Javascript is CLIENT side. By the time javascript starts executing on your desktop machine, the PHP script has finished execution and all its variables have been junked by Apache.
This leaves you with two chioces.
1) Output the array from PHP into the HTML so that when javascript starts executing it can read the array values as part of the HTML/Javascript mix on the client machine
2) Use AJAX. This will allow javascript to create a NEW instance of PHP and run scripts on the server and pass the results back to javascript, but it does not change the fact that the original PHP script that created the page is long gone and all its variables with it. Also when your AJAX's PHP finishes and passes its result back to javascript then that PHP's instance and all its variables will be chucked away as well.
This leaves you with two chioces.
1) Output the array from PHP into the HTML so that when javascript starts executing it can read the array values as part of the HTML/Javascript mix on the client machine
2) Use AJAX. This will allow javascript to create a NEW instance of PHP and run scripts on the server and pass the results back to javascript, but it does not change the fact that the original PHP script that created the page is long gone and all its variables with it. Also when your AJAX's PHP finishes and passes its result back to javascript then that PHP's instance and all its variables will be chucked away as well.
Your original question has already been answered by me, and bportlock has been kind enough to provide additional information. We suggest creating another question if you still need assistance with your coding.
In order to get your php arrays into a javascript array, you could (from php) echo something like the following to your page:
Now the contents of your php array are stored in your javascript array called 'array'. Also keep in mind that you could place this php code in a separate .php file and you could call it via AJAX as opposed to just page load.
I hope this is what you're asking.
Cheers
<script type="text/javascript">var array = new Array();</script>
<?php
// some loop structure here to iterate through each index in your php array
echo("<script type='text/javascript'>this.array[" . $counter . "] = '" . $x . "';</script>");
// end the loop
?>
Now the contents of your php array are stored in your javascript array called 'array'. Also keep in mind that you could place this php code in a separate .php file and you could call it via AJAX as opposed to just page load.
I hope this is what you're asking.
Cheers
ASKER
I've managed to get in the HTML document, the following result: (this is a the html content of a div where I put the results)
[{"0":"33","key":"33","1": "1","id_em presa":"1" ,"2":"9246 ","id_rand om":"9246" ,"3":"DLI0 015","id": "DLI0015", "4":"","id 2":"","5": "DLINK DWM-152 3G ADAPTER","descripcion":"DL INK DWM-152 3G ADAPTER","6":"refe","refer encia":"re fe","7":"" ,"nota":"" ,"8":"0.00 ","exento" :"0.00","9 ":"70796.4 6","gravad o":"70796. 46","10":" 1.00","can tidad":"1. 00","11":" 0.00","des cuento":"0 .00","12": "0.00","de vueltos":" 0.00","13" :"0.00","t otal":"0.0 0","14":"5 ","nfactur a":"5","15 ":"0","tip o_factura" :"0","16": "46834.2", "costo":"4 6834.2","1 7":"0","no rden":"0"} ,{"0":"34" ,"key":"34 ","1":"1", "id_empres a":"1","2" :"9246","i d_random": "9246","3" :"DLI0016" ,"id":"DLI 0016","4": "","id2":" ","5":" Cerca de alambre","descripcion":" Cerca de alambre","6":"refe","refer encia":"re fe","7":"" ,"nota":"" ,"8":"0.00 ","exento" :"0.00","9 ":"18000.0 0","gravad o":"18000. 00","10":" 1.00","can tidad":"1. 00","11":" 0.00","des cuento":"0 .00","12": "0.00","de vueltos":" 0.00","13" :"0.00","t otal":"0.0 0","14":"5 ","nfactur a":"5","15 ":"0","tip o_factura" :"0","16": "15000","c osto":"150 00","17":" 0","norden ":"0"}]
It was obtained by utilizing the
json_encode($rows)
function approach.
Now, in Javascript, how do I translate it to an Array so it can be used easily, like:
array["id"] or array["descripcion"], which are fields in the query result.
[{"0":"33","key":"33","1":
It was obtained by utilizing the
json_encode($rows)
function approach.
Now, in Javascript, how do I translate it to an Array so it can be used easily, like:
array["id"] or array["descripcion"], which are fields in the query result.
Try:
Now you should have a populated javascript array from the json_encode($rows) result;
var array = new Array();
array = json_encode($rows);
Now you should have a populated javascript array from the json_encode($rows) result;
ASKER
I'll post the correct answer later.
Thanks for all the suggestions, they were a good guide, but still lacked solution.
Thanks for all the suggestions, they were a good guide, but still lacked solution.
If you gave us some more of your source code, we might be able to help you a lot more. If you can get your results into a html div then you can certainly put them into a JavaScript array. Just post the code of the page where you're getting the results and we'll help you get them into a JavaScript array. We don't want you to be 'lacking a solution'!
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
hi
echo json_encode($arr);
For more examples, see:
http://php.net/manual/en/function.json-encode.php