[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 840
  • Last Modified:

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.
0
aguisa
Asked:
aguisa
  • 10
  • 4
  • 3
  • +2
1 Solution
 
sam2912Commented:
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

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



thanks,
0
 
CodebotCommented:
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;
      }
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
sam2912Commented:
You can create an array, and loop through the recordset and add each record into the array.

Related question:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_24436681.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

0
 
aguisaAuthor Commented:
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?

0
 
aguisaAuthor Commented:
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
0
 
aguisaAuthor Commented:
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");
0
 
aguisaAuthor Commented:
HOW DO I READ THE ARRAYS IN JAVASCRIPT?
0
 
sam2912Commented:
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.
0
 
aguisaAuthor Commented:
the thing is that I also need to return nrows.
0
 
Beverley PortlockCommented:
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.

0
 
sam2912Commented:
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.
0
 
Bruce SmithSoftware Engineer IICommented:
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
0
 
aguisaAuthor Commented:
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.
0
 
Bruce SmithSoftware Engineer IICommented:
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;
0
 
aguisaAuthor Commented:
I'll post the correct answer later.

Thanks for all the suggestions, they were a good guide, but still lacked solution.

0
 
Bruce SmithSoftware Engineer IICommented:
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'!
0
 
aguisaAuthor Commented:
All the answers you gave me resulted in unrecognizable types from javascript to php.

I had to divide every field of the recordset into a diferent array, and then the result was ready to be read,

as follows

javascript:

                while (x <= nrows){
                    codigo = idx[x];
                    nombre = nombrex[x];
                    referencia = referenciax[x];
                    precio = preciox[x];
                    cantidad = cantidadx[x];
                    descuento = descuentox[x];
                    exento = exentox[x];
                    repetidos = repetidosx[x];
                    agregar_linea(codigo, nombre, referencia, precio, cantidad, descuento, exento, repetidos);
                    x++;


All the solutions you gave me, they all returned things like 'Array'  or  ' [Array, Array]', which were unable to be read , thats what I was asking for. ...   Anyway , thanks every one for your answers, as I said, they at least guided me into the best soluton, so thanks everyone
0
 
aguisaAuthor Commented:
hi
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 10
  • 4
  • 3
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now