pass a php array to a javascript function

pass a php array to a javascript function  using -'I,am,trying,to,get,a,PHP,array,variable,into,a,JavaScript,variable.




asked Sep 22, 2015 by mannumits1
edited Sep 22, 2015 by rajesh
0 votes

4 Answers

0 votes


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

In your code, you could use like the following:

drawChart(600/50, , ...)

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 = "";
var obj = JSON.parse(s);
answered Sep 22, 2015 by mannumits1
0 votes

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

          1 => "Tue", 
          2 => "Wed", 
          3 => "Thu",
          4 => "Fri", 
          5 => "Sat",
          6 => "Sun",


answered Sep 22, 2015 by rajeevr642
0 votes

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

answered Sep 22, 2015 by bhavin
0 votes

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(''), JSON.parse(''), JSON.parse(''), JSON.parse(''))

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" =>
           "documentation" =>

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": [

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.

        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.
answered Sep 22, 2015 by badhwar.rohit