Solved

Javascript to read PHP array

Posted on 2010-11-16
19
819 Views
Last Modified: 2012-05-10
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
Comment
Question by:aguisa
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 10
  • 4
  • 3
  • +2
19 Comments
 
LVL 14

Expert Comment

by:sam2912
ID: 34145014
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
 

Author Comment

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



thanks,
0
 
LVL 6

Expert Comment

by:Codebot
ID: 34145107
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
Secure Your WordPress Site: 5 Essential Approaches

WordPress is the web's most popular CMS, but its dominance also makes it a target for attackers. Our eBook will show you how to:

Prevent costly exploits of core and plugin vulnerabilities
Repel automated attacks
Lock down your dashboard, secure your code, and protect your users

 
LVL 14

Expert Comment

by:sam2912
ID: 34145143
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
 

Author Comment

by:aguisa
ID: 34145230
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
 

Author Comment

by:aguisa
ID: 34145242
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
 

Author Comment

by:aguisa
ID: 34145252
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
 

Author Comment

by:aguisa
ID: 34145293
HOW DO I READ THE ARRAYS IN JAVASCRIPT?
0
 
LVL 14

Expert Comment

by:sam2912
ID: 34145319
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
 

Author Comment

by:aguisa
ID: 34145620
the thing is that I also need to return nrows.
0
 
LVL 34

Expert Comment

by:Beverley Portlock
ID: 34146049
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
 
LVL 14

Expert Comment

by:sam2912
ID: 34146299
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
 
LVL 11

Expert Comment

by:Bruce Smith
ID: 34147386
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
 

Author Comment

by:aguisa
ID: 34148001
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
 
LVL 11

Expert Comment

by:Bruce Smith
ID: 34148100
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
 

Author Comment

by:aguisa
ID: 34149102
I'll post the correct answer later.

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

0
 
LVL 11

Expert Comment

by:Bruce Smith
ID: 34161562
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
 

Accepted Solution

by:
aguisa earned 0 total points
ID: 34161931
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
 

Author Closing Comment

by:aguisa
ID: 34186496
hi
0

Featured Post

[Webinar] Learn How Hackers Steal Your Credentials

Do You Know How Hackers Steal Your Credentials? Join us and Skyport Systems to learn how hackers steal your credentials and why Active Directory must be secure to stop them. Thursday, July 13, 2017 10:00 A.M. PDT

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

734 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question