Link to home
Start Free TrialLog in
Avatar of aguisa
aguisaFlag for Costa Rica

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.
Avatar of Samuel Liew
Samuel Liew
Flag of Australia image

Hi aguisa, you are looking for the function json_encode, which turns a PHP array into a JSON value.

echo json_encode($arr);

For more examples, see:
http://php.net/manual/en/function.json-encode.php

Avatar of aguisa

ASKER

My PHP Array happens to be a recordset, can I use it as well?, and could you provide a small example?



thanks,
Avatar of Codebot
Codebot

If you are using older version the you can use this
function array_to_json_string($arraydata) {
            $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
$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

Open in new window

Avatar of aguisa

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?

Avatar of aguisa

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 ."'}";




///////////////////JAVASCRIPT PART IS///////////////////////
                var xresult = "";
                while (x <= json.nrows){
                    xresult += result;
                    x++;
                }
                $("#detallecotizacion").html(result);



I want detallecotizacion to show array contents in a manageable way.

thanks
Avatar of aguisa

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").dialog("close");
Avatar of aguisa

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.
Avatar of aguisa

ASKER

the thing is that I also need to return nrows.
Avatar of Beverley Portlock
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.

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:

<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
?>

Open in new window


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
Avatar of aguisa

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_empresa":"1","2":"9246","id_random":"9246","3":"DLI0015","id":"DLI0015","4":"","id2":"","5":"DLINK DWM-152 3G ADAPTER","descripcion":"DLINK DWM-152 3G ADAPTER","6":"refe","referencia":"refe","7":"","nota":"","8":"0.00","exento":"0.00","9":"70796.46","gravado":"70796.46","10":"1.00","cantidad":"1.00","11":"0.00","descuento":"0.00","12":"0.00","devueltos":"0.00","13":"0.00","total":"0.00","14":"5","nfactura":"5","15":"0","tipo_factura":"0","16":"46834.2","costo":"46834.2","17":"0","norden":"0"},{"0":"34","key":"34","1":"1","id_empresa":"1","2":"9246","id_random":"9246","3":"DLI0016","id":"DLI0016","4":"","id2":"","5":" Cerca de alambre","descripcion":" Cerca de alambre","6":"refe","referencia":"refe","7":"","nota":"","8":"0.00","exento":"0.00","9":"18000.00","gravado":"18000.00","10":"1.00","cantidad":"1.00","11":"0.00","descuento":"0.00","12":"0.00","devueltos":"0.00","13":"0.00","total":"0.00","14":"5","nfactura":"5","15":"0","tipo_factura":"0","16":"15000","costo":"15000","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.
Try:

var array = new Array();
array = json_encode($rows);

Open in new window


Now you should have a populated javascript array from the json_encode($rows) result;
Avatar of aguisa

ASKER

I'll post the correct answer later.

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
Avatar of aguisa
aguisa
Flag of Costa Rica image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of aguisa

ASKER

hi