By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
460,034 Members | 971 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 460,034 IT Pros & Developers. It's quick & easy.

php array in javascript function

P: n/a
i've got an array created in php that I want to send over to a javascript function.

onclick = "return sjekk(<?echo $names; ?> )"

in my "sjekk" function, when I try to print an alert :

function sjekk(navn)
{
alert(navn); // or alert(navn[0])
return(false);
}

I get "function Array { [native code]}"

How do I print out the names I want?
Jul 20 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Obscurr wrote:
i've got an array created in php that I want to send over to a javascript
function.

onclick = "return sjekk(<?echo $names; ?> )"
If $names is the PHP array, you need to convert it to a string,
using the print_r(...) and str_replace(...) PHP functions for
example (see PHP manual for details). Then you can pass that
string to the sjekk(...) JavaScript method while enclosing that
string in single quotes (since you used double quotes for the
event handler value already.) Quickhack:

onclick="return sjekk('<?php
/*
* Replace newlines in the output of print_r(...) with
* space because JavaScript string literals must end
* before newline.
*/
preg_replace("(\r?\n|\r)", ' ', print_r($names))
?>');"

But why do you pass the PHP array to JavaScript in the first place?
When you can use server-side PHP you should stick to it because it
is more reliable as client-side JavaScript can be disabled or not
supported.
in my "sjekk" function, when I try to print an alert :

function sjekk(navn) {
alert(navn); // or alert(navn[0])
return(false);
}
I get "function Array { [native code]}"


In PHP

$a = array(...);
echo $a;

prints

Array

which in

onclick = "return sjekk(<?echo $names; ?> )"

prints

onclick = "return sjekk(Array )"

But `Array' is a (constructor) function (for the Array prototype) in
JavaScript, so for the JavaScript engine you pass a reference to this
function to your method. When trying to display it with alert(...),
the toString(...) method of the Function prototype is called to convert
it to a String object and the source code of the method is displayed.
HTH

PointedEars

Jul 20 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.