简体   繁体   中英

PHP associative array null in Javascript function

I have a PHP webpage containing 6 textboxes as given below:

<html>
   <script type="text/javascript">

        function add()
        {
            //PHP associative array not storing properly in JS array

            var array = JSON.parse(<?php echo json_encode($elementsindex); ?>);//getting array

            //JS array elements not printing
            for(var i in array)
            {
                alert("key = "+i+" and value = "+array[i]);
            }

            for(var key in array)
            {
                if(array[key]===null || array[key]===0)//for loop not executing
                {
                    var valtoadd = 5;

                    array[key] = valtoadd;//add value to index IN ARRAY

                    var textbox = document.getElementById(key);
                    textbox.value = valtoadd;//add value to textbox 
                }
            }
        }
    </script>
   <body>
   <form method="POST" action="">
      <div id="operation">
            <input type="text" id = "5E" name="5E" value="">
            <input type="text" id = "4E" name="4E" value="" >
            <input type="text" id = "3E" name="3E" value="">
            <input type="text" id = "2E" name="2E" value="">
            <input type="text" id = "1E" name="1E" value="">
            <input type="text" id = "0E" name="0E" value="">
        </div>
        ....rest of the code
     </form>
        ..php code

I have a PHP code in the same page that invokes the Javascript function add() on a particular buttonclick() which is working perfectly:

   <?php
    include 'footer.php';

   if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['PUSH']))
    { 
        //I am creating an associative array
        $elementsindex = array("0E"=>0 ,"1E"=>0,"2E"=>0, "3E"=>0, "4E"=>0, "5E"=>0);

        echo '<script type="text/javascript">';
        echo 'add();'; //invoking JS function
        echo '</script>';
    }
    ?>

However in the Javascript function add(), the PHP array is not getting stored in var array. Also, the array elements are not printing in the alert box and the code never executes the for(var key in array) loop.

I am sure that the associative array is being passed correctly (the Javascript function is invoked successfully), but maybe not being received at the JS function because initially all the values in the key-value pair are zero (required for the project).

This code stores the $a into an object variable. I simply change the way to obtain the value.

var obj = <?php echo json_encode($a); ?>;
for (var i in obj)
{
    alert("key = " + i + " and value = " + obj[i]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM