20

So I have an array of records retreived from a database. The array is in the format;

$rows[0]['id']=1;
$rows[0]['title']='Abc';
$rows[0]['time_left']=200;


$rows[1]['id']=2;
$rows[1]['title']='XYZ';
$rows[1]['time_left']=300;
//And so on upto 10-20 rows

What's the best way of transferring this array over to my javascript code? I'd like the javascript to be able to loop through all of the records, and using the 'id' attribute, update the div with that id with some information.

My javascript code is in an external .js file, but i'm able to execute php code in the HTML code of my page. So I could do something like this:

In my_file.js:

var rows=New Array();

In HTML code:

<html>
<head>
<script type="text/javascript" src="js/my_file.js"></script>

<script type="text/javascript">
<? foreach ($rows as $row):?>
<? extract($row);?>
rows[<?=$id;?>]['title']="<?=$title;?>";
//And so on
<? endforeach;?>
</script>
Ali
  • 261,656
  • 265
  • 575
  • 769

5 Answers5

29

I tend to use a JSON object for this:

  • On the server side, JSON encode your data: json_encode($data);
  • On the JavaScript side, I write a function that takes a JSON object as a parameter and unpack it.

When you unpack the object, you can print the array's contents into a <DIV> tag, or where ever you would like on the page (jQuery does a pretty sweet job of this).

Kenny Linsky
  • 1,726
  • 3
  • 17
  • 41
barfoon
  • 27,481
  • 26
  • 92
  • 138
  • 2
    How do you unpack the JSON object with javascript? Can you add some sample code for that and a sample of the unpacked object to your answer please? Thanks – Ali Dec 26 '08 at 05:17
  • Check this out: http://ditio.net/2008/07/17/php-json-and-javascript-usage/ – rg88 Dec 26 '08 at 05:34
  • MooTools also does JSON encode/decode: http://mootools.net/docs/core/Utilities/JSON – samvermette Feb 24 '10 at 05:40
12

If you're doing inline data, I've always been fond of doing

<script type="text/javascript">
window.sitescriptdata = {}; 
window.sitescriptdata.foo = ( <?php echo json_encode( $structure ); ?> );
</script>

For basic stuff, saves you doing an AJAX callback. Also, if you want to glue data to a DOM node, the "metaobject" way is something I really love.

<div id="foobar">
 <div><object class="metaobject">
        <param name="data" value="<?php echo htmlentities(json_encode($data), ENT_QUOTES );?>" />
 </object></div>
</div> 

Now this may not look great, but its an effective way of associating data directly with a DOM node without needing to know the exact unique path to that node. Very handy if you have many many datasets that need to be attached to specific screen elements.

I usually use http://noteslog.com/metaobjects/ plugin for jQuery, but its so simple I have on occasion written it myself ( there was a time I couldn't find the plugin, but new how it worked )

When done, there will be

$("div#foobar > div").get().data.($yourarrayhere)

Visible to your code.

Kent Fredric
  • 56,416
  • 14
  • 107
  • 150
1

In an AJAX example like here you can solve this problem on this way:

.php file (ajax return function)

$myArray = array("object_id"=>1, "object_title"=>"Testobject");
return json_encode($myArray);

.js file (javascript function)

...
if(g_httpRequest.readyState == 4)
{
var jsonRes = JSON.parse(g_httpRequest.responseText);
alert(jsonRes.object_title)
}
...
Marco
  • 11
  • 1
1

To follow up to your question (and my reply, I ran out of space on the comment reply), here is a very simplified subset of the code I use:

Javascript AJAX handler in jQuery:

$.ajax({
   type: "POST",
   url: "BACKEND.php",
   timeout: 8000,
   data: "var1=" + myVar,
   dataType: "json",
   error: function(){
     $("#DIVID").html("<div class='error'>Error!</div>");
   },  
   success: function(jsonObj){
     $("#DIVID").html(jsonObj.mydata);
   }
 });


PHP Array:
$data['mydata'] = $myData;
barfoon
  • 27,481
  • 26
  • 92
  • 138
  • Final question. I gave it a try and I now get an 'object' in javascript which contains each of my rows, so I think I would access it as myObj[0].title or myObj[1].title. The prob is, if I want to get the title of something by its ID, how can i find it. The id would be in myObj[1].id or myObj[0].id – Ali Dec 26 '08 at 06:05
  • 1
    Try adding a period Obj.1.id More info on JSON notation http://www.hunlock.com/blogs/Mastering_JSON_(_JavaScript_Object_Notation_) see: var myObject = { 'color' : 'blue', 'animal' : {'dog' : 'friendly' } }; document.writeln(myObject.animal.dog); // outputs friendly – barfoon Dec 26 '08 at 06:37
  • Argh, my apologies for the terrible formatting there. – barfoon Dec 26 '08 at 06:37
  • Actually i wanted to know, that if I have the ID of a row but not the array index how can I identify it without having to loop through all the rows. I.e: i want myObject[X].title where myObject[X].id=4. Here X is what I want. Btw, i'm accepting ur answer cuz u already helped a lot :) – Ali Dec 26 '08 at 06:51
0

im still fairly new too say maybe this method isnt the most secure, but you can always turn your javascript array into a string and then pass it through the URL for the php to GET.

so:

for(var i=0;i < jsarray.length;i++) 
{
var x = jsarray[i];
urlstring += "myvalue[]="+x+"&";
}

document.location.href = "mypage.php?"+urlstring;

and then the php would be:

$phparray = $_GET['myvalue'];

hope that helps

Lan
  • 1,874
  • 2
  • 20
  • 37