Question

This question already has an answer here:

I have PHP code as in the following.

<?php
    echo "<SCRIPT LANGUAGE='javascript'>add dd_Employee('".$id1."','".$fname1."',".$sal1.");</SCRIPT>";
    echo "<SCRIPT LANGUAGE='javascript'>add dd_Employee('".$id2."','".$fname2."',".$sal2.");</SCRIPT>";
    ....

?>
...

And my JavaScript code contains

var details=new Array();

function addEmployee(id,fname,salary){
    var temp=new Array(id,fname,salary);
    details[details.length]=temp;
    alert(temp);
}

function displayEmployee(){
    for (var i=0;i<details.length;i++)
        var temp_details=details[i];

    //Display the id,name,sal
    var id=temp_details[0];
    var name=temp_details[1];
    var sal=temp_details[2];

    alert(id);
    alert(name);
    alert(sal);
}

Now the problem is whatever assigned by the PHP will visble only in AddEmployee. Which means it is working fine. But inside displayEmployee the value assigned by PHP will not work. Is there any flaw in my logic?

Was it helpful?

Solution

Just populate your global data structure directly rather than passing it through a JavaScript function. You are likely running into a variable scope problem since you are allocating memory in addEmployee.

Example:

<?php
print "details[details.length] = new Array('$id1', '$name1', '$salary1');\n";
?>

OTHER TIPS

It looks like you're missing some curly braces in your for loop. Right now, you've got a 1-line for loop that does nothing but assign a value to your temp variable, which is re-declared on every iteration. I can't remember what the scope rules are for JavaScript in this situation, but it's generally bad practice to do this (if it's intentional). Try something like this for your displayEmployee() method.

function displayEmployee(){
    for(var i=0; i<details.length; i++) {

        var temp_details = details[i];

        //Display the id, name, and sal.
        var id = temp_details[0];
        var name = temp_details[1];
        var sal = temp_details[2];

        alert(id);
        alert(name);
        alert(sal);
    }
}

That should fix your immediate problem. If you have control over all of your code, I'd recommend turning the employee data into an object so it's more manageable. To do this, you should use this PHP code:

<?php
    echo '<script>
              addEmployee('.json_encode(array(
                  'id'     => 'id1',
                  'name'   => 'fname1',
                  'salary' => 1024,
              )).');
              addEmployee('.json_encode(array(
                  'id'     => 'id2',
                  'name'   => 'fname2',
                  'salary' => 2048,
              )).');
         </script>';
?>

And then alter your JavaScript code to look like this:

var details = [];

function addEmployee(employeeObj){
    details[details.length] = employeeObj;

    alert(employeeObj);
}
function displayEmployee(){
    for(var i=0; i<details.length; i++) {
        alert(details[i].id);
        alert(details[i].name);
        alert(details[i].salary);
    }
}

I haven't tested this code, but it should run.

You have an error in your JavaScript call generated by PHP

echo "<SCRIPT LANGUAGE='javascript'>add dd_Employee('".$id1."','".$fname1."',".$sal1.");</SCRIPT>";

should be

echo "<SCRIPT LANGUAGE='javascript'>addEmployee('".$id1."','".$fname1."',".$sal1.");</SCRIPT>";

And if you want to change it to OOP?

<?php
    $employeeList[] = array('sdf3434', 'Bob', 123.34);
    $employeeList[] = array('wer335dg', 'Joe', 223);
?>
<html>
    <head>
        <script>
            function Employees() {
                this.list = new Array();
            }
            Employees.prototype.add = function (id, fname, sal) {
                this.list.push(new Array(id, fname, sal));
            };
            Employees.prototype.display = function () {
                for(var i=0, t = this.list.length;i<t;i++) {
                    var emp = this.list[i];
                    alert(emp[0]);
                    alert(emp[1]);
                    alert(emp[2]);
                }
            };
            var employees = new Employees();
            <?php
                foreach ($employeeList as $employee) {
                    list($id, $fname, $sal) = $employee;
                    printf("employees.add('%s', '%s', %f);\n", $id, $fname, $sal);
                }
           ?>
        </script>
    </head>
    <body>
        <a href="#" onclick="employees.display();">click</a>
    </body>
</html>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow