-3

I want to pass javascript array(converted from php to js) present in php code to javascript function.

<?php

//php to javascript array conversion
$php_array = array('he','hi','hello');
$js_array = json_encode($php_array);
echo 'var groups = ". $js_array . ";\n';

?>

function codeAddress(groups)
{ alert("into code address function");

        for (var i=0;i<groups.length;i++)
    {
        alert(groups[i]);
    }
}
4
  • What is wrong with this code? What does it do, and what do you expect it to do instead? You can't expect to be able to just dump code here without explaining what exactly is wrong. Commented Jun 27, 2014 at 13:14
  • 2
    The syntax highlighting in the question shows what the issue is. You've mixed two types of quotes, " and '. So you're not actually setting your js variable to what you expect. Commented Jun 27, 2014 at 13:15
  • yes, adding " quote worked! but i am unable to call the codeAddress(groups) function from php. :( Commented Jun 27, 2014 at 13:23
  • Which is the correct behaviour - PHP is server-side, JS is client-side - the two can't really interact like that. Commented Jun 27, 2014 at 14:32

2 Answers 2

3
echo 'var groups = '. $js_array . ";\n";

Variable was not expanded inside single quotes. Don't put output of json_encode into quotes.

2
  • yes, adding " quote worked! but i am unable to call the codeAddress(groups) function from php. :( Commented Jun 27, 2014 at 13:28
  • PHP is executed on the server, its output is send to the browser, javascript is then executed in the browser. Just add codeAddress(groups); after defining the javascript function. Commented Jun 27, 2014 at 13:31
2

try something like this

    //php to javascript array conversion
    $php_array = array('he','hi','hello');
    $js_array = json_encode($php_array);
    echo 'var groups = '. $js_array;

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.