SitePoint Sponsor

User Tag List

Results 1 to 7 of 7
  1. #1
    SitePoint Member
    Join Date
    Jul 2008
    Posts
    1
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    PHP array to Javascript Array

    Hello,

    I hope I am writing this in the correct thread.

    I have pasted relevant code below.


    /* convert PHP array ($levels) to Javascript array ($param) */
    for($x = 0; $x < count($levels); $x++)
    {
    $array .= "[" . $levels[$x][0] . ", ". $levels[$x][1] . "]" ;
    if($x+1 < count($levels))
    $array .= ", ";
    }
    $param = "new Array( " . $array . ")";
    /* end convert PHP array to Javascript array */


    echo '<form name="SubjectForm">';
    echo 'Subject <br><select name = "subject" onChange="addOptions('. $param . ') ">';
    echo '</form>;'

    The output of the multi-dimensional array conversion becomes something like this:
    new Array( [Math, Algebra I], [Math, Algebra II], [Math, Arithmetic], [Math, Calculus], [Math, Pre-Algebra], [Math , Pre-Calculus], [Math, Statistics], [Math, Trigonometry], [Science, Biology], [Science, Chemistry], [Science, Earth Science], [Science, Physics])

    I created a literal declaration of an array and I want to pass it to the addOptions function which is called with an onChange event handler. But when I pass this $param variable, the addOptions function doesn't work.

    However if I manually create a parameter that is an array similar to:
    echo 'Subject <br><select name = "subject" onChange="addOptions( new Array( [1, 2], [3, 4]) ">';

    Then the addOptions function works. So I guess my question is, what am I doing wrong with my conversion of the PHP array to the JS array that is making the addOptions not work?

    Thank you very much ahead of time for any help. Take care.

  2. #2
    SitePoint Addict
    Join Date
    Oct 2006
    Posts
    210
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'm not a JavaScript expert so I'm not sure if your problem is with JavaScript syntax or the data values you're using. But below is a PHP junction that generates a JavaScript array constant from a PHP array structure. The following code shows an example PHP array and how the JavaScript code using the array constant can be created. Note that the makeJavaScriptArray() function is in production use but the other code is just sample code and could be buggy.

    PHP Code:
    $phpArray = array();
    $phpArray['string'] = 'text string';
    $phpArray['number'] = 1234;
    $phpArray['boolean'] = FALSE;
    $subArray = array();
    $subArray[] = 'text string';
    $subArray[] = 1234;
    $subArray[] = TRUE;
    $phpArray['array'] = $subArray;
    $javaScriptCode 'javaScriptVariable = ' htmlentitiesmakeJavaScriptArray$phpArray ) );

    //
    //  makeJavaScriptArray - Returns a JavaScript array constant created from the provided PHP nested array.
    //                        this function is typically called to create a response to an Ajax request. 
    //
    //  Note: While this function will protect the JavaScript code from special characters, the calling code
    //        still needs to encode any HTML entities before sending the result to the browser.
    //

    function makeJavaScriptArray$phpArray )
    {
        
    $arrayConstant '{';
        
    $delimiter '';
        
        foreach (
    $phpArray as $fieldName => $fieldValue)
        {
            if (
    is_bool$fieldValue ))                                    // Boolean data type
                
    if ($fieldValue$fieldConstant 'true';
                else 
    $fieldConstant 'false';
            
            elseif (
    is_numeric$fieldValue ))                            // Numeric data type
                
    $fieldConstant $fieldValue;
            
            elseif (
    is_string$fieldValue ))                            // String data type
                
    $fieldConstant "'" addSlashes$fieldValue ) . "'";
                
            elseif (
    is_array$fieldValue ))                            // Array data type
                
    $fieldConstant makeJavaScriptArray$fieldValue );
                
            else                                                        
    // Unknown data type
                
    $fieldConstant '';
            
            if (
    $fieldConstant '')
            {
                
    $arrayConstant .= $delimiter " '$fieldName': $fieldConstant";
                
    $delimiter ',';
            }
        } 
    Hope this helps....
    mikem

  3. #3
    rajug.replace('Raju Gautam'); bronze trophy Raju Gautam's Avatar
    Join Date
    Oct 2006
    Location
    Kathmandu, Nepal
    Posts
    4,013
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If i have understood what you are trying to do, the following example should help you there:
    PHP Code:
    $arr = array(1,2,3,4,5,6,7);
    $script '<script>var newArr = new Array(' implode(','$arr) . ');</script>';
    echo 
    $script
    HTML Code:
    <script>
    function doOnchange(arr){
    	alert(arr.length);
    }
    </script>
    <form name="frm">
    	<select name="sel1" onchange="doOnchange(newArr);">
    		<option>1</option>
    		<option>2</option>
    		<option>3</option>
    	</select>
    </form>
    Mistakes are proof that you are trying.....
    ------------------------------------------------------------------------
    PSD to HTML - SlicingArt.com | Personal Blog | ZCE - PHP 5

  4. #4
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    json_encode. If you don't have the extension enabled, there is a workaround in the comments of that page.

  5. #5
    SitePoint Addict ArunB's Avatar
    Join Date
    Jun 2008
    Location
    Hyderabad
    Posts
    252
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Use json_encode.

    If you have a PHP array with name $arrSample, then convert it to JSON string by using code below:

    $jsonString = json_encode($arrSample);
    then echo it.

    On the client side, use eval or JSON.parse(to use this function, you need to download JSON2.js from http://www.json.org/).

    evaluate the JSON string in JavaScript using

    jsonObj = eval( '(' + <<JSON String>> + ')');

    Now jsonObj is the JavaScript version of PHP array.

  6. #6
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You don't need to use eval on the client side. JSON is a valid subset of Javascript, so you can simply do:
    PHP Code:
    var json = <?php echo json_encode($foo); ?>;

  7. #7
    SitePoint Addict ArunB's Avatar
    Join Date
    Jun 2008
    Location
    Hyderabad
    Posts
    252
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yes, you need to eval it when it is coming in response to an Ajax request.


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •