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.

This question already has an answer here:

I am trying to get a PHP array variable into a JavaScript variable.

This is my code:

<html>
    <head>
        <script type="text/javascript">
              function drawChart(row,day,week,month,date)
              {
                  // Some code...
              }
        </script>
    </head>

    <body>
        <?php
            for($counter = 0; $counter<count($au); $counter++)
            {
                switch($au[$counter]->id)
                {
                    case pageID.'/insights/page_active_users/day':
                        $day[] = $au[$counter]->value;
                    break;
                    case pageID.'/insights/page_active_users/week':
                        $week[] = $au[$counter]->value;
                    break;
                    case pageID.'/insights/page_active_users/month':
                        $month[] = $au[$counter]->value;
                    break;
                }
            }
        ?>
        <script>
            drawChart(600/50, '<?php echo $day; ?>', '<?php echo $week; ?>', '<?php echo $month; ?>', '<?php echo createDatesArray(cal_days_in_month(CAL_GREGORIAN, date('m',strtotime('-1 day')), date('Y',strtotime('-1 day')))); ?>');
        </script>
    </body>
</html>

I can't get value of the PHP array.

How do I fix this problem?

share|improve this question
add comment

marked as duplicate by Benjamin Gruenbaum yesterday

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

5 Answers

Use JSON.

In the following example $php_variable can be any PHP variable.

<script type="text/javascript">
    var obj = <?php echo json_encode($php_variable); ?>;
</script>

In your code, you could use like the following:

drawChart(600/50, <?php echo json_encode($day); ?>, ...)

In cases where you need to parse out an object from JSON-string (like in an AJAX request), the safe way is to use JSON.parse(..) like the below:

var s = "<JSON-String>";
var obj = JSON.parse(s);
share|improve this answer
    
What would be the disadvantage of simply writing var obj = <?php echo json_encode($php_variable); ?>;? Won't PHP encode the JSON object securely in a way that it's parsable by the script? –  YMMD May 4 '12 at 14:43
    
Yes, that is the way. But my intention was to put across JSON.parse() as one safe way to parse from string. Thanks for pointing, I will edit my post. –  Thrustmaster May 5 '12 at 17:41
1  
var data = <?php echo json_encode($registos); ?>; returns the error: SyntaxError: Unexpected token < –  Nuno Nogueira Jan 28 at 17:40
    
i am getting this error, too (Unexpected token <) –  Remus Rigo Mar 29 at 14:07
    
@RemusRigo & Nuno: Just a guess, are you opening PHP tags within PHP tags? In any case, please post a new question. –  Thrustmaster Mar 30 at 14:13
add comment

you can convert php arrays into javascript using php's json_encode()* function

<?php $phpArray = array(
          0 => "Mon", 
          1 => "Tue", 
          2 => "Wed", 
          3 => "Thu",
          4 => "Fri", 
          5 => "Sat",
          6 => "Sun",

    )
?>

<script type="text/javascript">

    var jArray= <?php echo json_encode($phpArray ); ?>;

    for(var i=0;i<6;i++){
        alert(jArray[i]);
    }

 </script>
share|improve this answer
add comment
up vote 4 down vote accepted

In the following example you have an PHP array, then firstly create a JavaScript array by a PHP array:

<script type="javascript">
    day = new Array(<?php echo implode(',', $day); ?>);
    week = new Array(<?php echo implode(',',$week); ?>);
    month = new Array(<?php echo implode(',',$month); ?>);

    <!--  Then pass it to the JavaScript function:   -->

    drawChart(<?php echo count($day); ?>, day, week, month);
</script>
share|improve this answer
add comment

Data transfer between two platform requires a common data format. JSON is a common global format to send cross platform data.

drawChart(600/50, JSON.parse('<?php echo json_encode($day); ?>'), JSON.parse('<?php echo json_encode($week); ?>'), JSON.parse('<?php echo json_encode($month); ?>'), JSON.parse('<?php echo json_encode(createDatesArray(cal_days_in_month(CAL_GREGORIAN, date('m',strtotime('-1 day')), date('Y',strtotime('-1 day'))))); ?>'))

This is the answer to your question. The answer may look very complex. You can see a simple example describing the communication between server side and client side here

$employee = array(
 "employee_id" => 10011,
   "Name" => "Nathan",
   "Skills" =>
    array(
           "analyzing",
           "documentation" =>
            array(
              "desktop",
                "mobile"
             )
        )
);

Conversion to JSON format is required to send the data back to client application ie, JavaScript. PHP has a built in function json_encode(), which can convert any data to JSON format. The output of the json_encode function will be a string like this.

{
    "employee_id": 10011,
    "Name": "Nathan",
    "Skills": {
        "0": "analyzing",
        "documentation": [
            "desktop",
            "mobile"
        ]
    }
}

On the client side, success function will get the JSON string. Javascript also have JSON parsing function JSON.parse() which can convert the string back to JSON object.

$.ajax({
        type: 'POST',
        headers: {
            "cache-control": "no-cache"
        },
        url: "employee.php",
        async: false,
        cache: false,
        data: {
            employee_id: 10011
        },
        success: function (jsonString) {
            var employeeData = JSON.parse(jsonString); // employeeData variable contains employee array.
    });
share|improve this answer
add comment
example('<?=$phpvar1?>','<?=$phpvar2?>' );

<script>
function example(val,val2){
     //code
} 
</script>

try this ??

share|improve this answer
add comment

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