Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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]);
    }
}
share|improve this question

closed as off-topic by bcmcfc, Cerbrus, Tichodroma, Ashkan Mobayen Khiabani, JOM Jun 27 at 15:28

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example." – Cerbrus, Ashkan Mobayen Khiabani
If this question can be reworded to fit the rules in the help center, please edit the question.

    
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. –  esqew Jun 27 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. –  bcmcfc Jun 27 at 13:15
    
yes, adding " quote worked! but i am unable to call the codeAddress(groups) function from php. :( –  user2961127 Jun 27 at 13:23
    
Which is the correct behaviour - PHP is server-side, JS is client-side - the two can't really interact like that. –  Vld Jun 27 at 14:32

2 Answers 2

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

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

share|improve this answer
    
yes, adding " quote worked! but i am unable to call the codeAddress(groups) function from php. :( –  user2961127 Jun 27 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. –  Marek Jun 27 at 13:31

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;
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.