php array in javascript function

O

Obscurr

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?
 
T

Thomas 'PointedEars' Lahn

Obscurr said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top