parsing php array to javascript

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • freefony
    New Member
    • Nov 2008
    • 59

    parsing php array to javascript

    Am trying to parse a php array into javascript but i found that only one element of the array was present in the javascript array. here is my code code
    Code:
    <?php
    include("../../connect.php");
    $qry="select * from stock";
    $rst=mysql_query($qry) or die("Error in Query.".$qry." ".mysql_error());
    while($row=mysql_fetch_assoc($rst)){
    	$item=$row['item'];
    	$list[$item]=$row['price'];
    }
    foreach($list as $key =>$value){
    	echo $key."-";
    	echo $value."<br/>";
    }
    echo $list['coke'];
    ?>
    <script type="text/javascript" language="javascript">
    list = new Array("<?php echo $list[$item]; ?>")
    alert(list);
    </script>
    the foreach loop worked just fine printing all the keys and values in the database but in the process of parsing it i seem to be doing something wrongly
    cos the alert is only printing the value the last key "5000"
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    the problem is that a Javascript array is somewhat different from a PHP array. a Javascript array uses only numeric values as key. or put in other words, there is no such thing as an associative array in Javascript.

    an associative array in Javascript is called: object. you have several options to define a (standard) object
    - using the Object Literal
    Code:
    var obj_name = {
        key1 : value1,
        key2 : value2
    // etc.
    }
    - create an object with “new”, applicable if you have a predefined set of keys
    Code:
    function MyObject(value)
    {
        this.key = value;
    }
    var obj_name = new MyObject("a value");
    - create a new empty object and append the values
    Code:
    var obj_name = new Object;
    obj_name.key1 = value1;
    obj_name.key2 = value2;
    // etc.
    and regarding the output. calling $list[$item] is exactly one value.

    Comment

    • freefony
      New Member
      • Nov 2008
      • 59

      #3
      i think i uderstand the 1st and last options but the array is being generated by values from a table in the database and i have no control over the size of the array and worse i dont think javascript have the foreach loop equivalent

      Comment

      • Dormilich
        Recognized Expert Expert
        • Aug 2008
        • 8694

        #4
        Originally posted by freefony
        and worse i dont think javascript have the foreach loop equivalent
        wrong.

        nevertheless, it doesn’t matter. since PHP long finished execution when JavaScript starts, you have to print each and every key - value combination by PHP (using method 1 or 3 (2 was for completeness))

        Comment

        • freefony
          New Member
          • Nov 2008
          • 59

          #5
          Code:
          echo "<script languege='javascript'>";
          foreach($list as $key=>$val){
           echo "var item=".$key;
           echo "var price=".$val;
          }
          echo "</script>";

          Comment

          • freefony
            New Member
            • Nov 2008
            • 59

            #6
            is there any chance that would work?

            Comment

            • gits
              Recognized Expert Moderator Expert
              • May 2007
              • 5390

              #7
              Originally posted by Dormilich
              Code:
              var obj_name = {
                  key1 : value1,
                  key2 : value2
              // etc.
              }
              wouldn't that be similar to:

              Code:
              echo 'var obj_name = '.json_encode($php_array);
              kind regards

              Comment

              • Dormilich
                Recognized Expert Expert
                • Aug 2008
                • 8694

                #8
                Originally posted by freefony
                is there any chance that would work?
                nope, you’d end up redeclaring 2 variables

                @gits: looks like that.

                Comment

                • gits
                  Recognized Expert Moderator Expert
                  • May 2007
                  • 5390

                  #9
                  i did ... and i thought ... even when i'm not a php-expert that for the current case:

                  Code:
                  echo 'var list = '.json_encode($list);
                  could do the job? it should create a string that is later on evaled by JavaScript as an object (or assoc array if you want to call it that) with all keys and values in the $list array?

                  kind regards

                  Comment

                  • freefony
                    New Member
                    • Nov 2008
                    • 59

                    #10
                    Hey the jason function is a powerful tool! but little problem tho i still cant get the javascript array.
                    Code:
                    //these two lines works perfectly
                    $mylist=jason_encode($list);
                    var_dump($mylist);
                    //output: string(64) "{"coke":"70","Emzor Paracetamol BP":"2","Paracetamol BP":"5000"}"
                    but the following codes return nothing what am i doing wrong?
                    Code:
                    echo "<script languege='javascript'>";
                    echo "var mylist=".json_encode($list);
                    echo "document.write(mylist)";
                    echo "var data=eval(mylist)";
                    echo "</script>";

                    Comment

                    • Dormilich
                      Recognized Expert Expert
                      • Aug 2008
                      • 8694

                      #11
                      1. you don’t have an Array
                      2. what do you expect document.write( mylist) to output?*

                      * from the JavaScript Point-of-View, it outputs the variable’s string representation (for object it’s the toString() method’s return value)

                      PS. had a look in Firebug, the object was created as desired
                      PPS. there’s a typo on line 1 and you really should use the type attribute there

                      Comment

                      • didoamylee
                        New Member
                        • Nov 2008
                        • 16

                        #12
                        Code:
                        <script type="text/javascript">
                        var a = new Array('<?php echo implode("','",$php_array); ?>');
                        </script>
                        That should do the trick.

                        Comment

                        • Dormilich
                          Recognized Expert Expert
                          • Aug 2008
                          • 8694

                          #13
                          Originally posted by didoamylee
                          That should do the trick.
                          it doesn't. because the PHP array is associative and javascript arrays are always numeric.

                          Comment

                          • freefony
                            New Member
                            • Nov 2008
                            • 59

                            #14
                            Ok guys! i got working
                            Code:
                            <?php
                            $qry="select * from stock";
                            $rst=mysql_query($qry) or die("Error in Query.".$qry." ".mysql_error());
                            while($row=mysql_fetch_assoc($rst)){
                            	$item=$row['item'];
                            	$list[$item]=$row['price'];
                            }
                            ?>
                            <script type="text/javascript" language="javascript">
                            var list=new Array('<?php echo json_encode($list); ?>');
                            document.write(list);
                            
                            </script>
                            this suits my purpose and would solve a lot of problems i ve been facing with jscript and php arrays thanks to u guys

                            Comment

                            • Dormilich
                              Recognized Expert Expert
                              • Aug 2008
                              • 8694

                              #15
                              but you know that you sacrifice your PHP array keys with this?

                              how to do print_r() in Javascript
                              Code:
                              var my_php_array = { //… } // from json_encode()
                              my_php_array.toString = function()
                              {
                                  var str = "";
                                  for (var key in this)
                                  {
                                      str += key+" => "+this[key]+"\n";
                                  }
                                  return str;
                              }
                              [I]div[/I].innerHTML = my_php_array;

                              Comment

                              Working...