php array in javascript function

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Obscurr

    php array in javascript function

    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?
  • Thomas 'PointedEars' Lahn

    #2
    Re: php array in javascript function

    Obscurr wrote:
    [color=blue]
    > i've got an array created in php that I want to send over to a javascript
    > function.
    >
    > onclick = "return sjekk(<?echo $names; ?> )"[/color]

    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.
    [color=blue]
    > 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]}"[/color]

    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

    Comment

    Working...