Kraken
Kraken

Reputation: 24213

Pass array from php to javascript method

In my php i make a db call, and the result is

$options = mysqli_fetch_array($result);

Now, I want to make a javascript method call and pass this function. My javascript method looks like

function myFunction(options){
//iterate over each option
}

and what I am doing is

<?php echo "<script>myFunction('".$options."')</script>";

This gives me error on my server that I am doing array to string conversion.

I thought javascript determined the datatype on runtime and hence I'll be ok with this. can someone please tell me the correct way of doing this?

Thanks

Upvotes: 0

Views: 62

Answers (3)

Umair Ayub
Umair Ayub

Reputation: 21241

Firstly, declare your JS function.

function myFunction(options){
 options = JSON.parse(options);

 for(var i=0; i<= options.length; i++){
    console.log(options[i]);
  }
}

And in your PHP side, convert array into JSON and pass it to JS function

$json = json_encode($options);

# Echo JavaScript and JSON without single quotes
<?php echo "<script>myFunction(".$json.")</script>";

Upvotes: 0

Deepak Nirala
Deepak Nirala

Reputation: 836

You can not pass a php array into javascript function as array. However you can pass it as stated by Grokify or you can pass it directly assign into your a javascript variable if your function is on same page by giving into php environment.

function myFunction(){
    var options = <?php echo json_encode($options); ?>;
}

Upvotes: 0

Grokify
Grokify

Reputation: 16334

To have PHP print out an array JavaScript can use, you can convert the array to JSON string and then echo that directly.

# Convert PHP array to JSON array
$json_options = json_encode($options);

# Echo JavaScript and JSON without single quotes
<?php echo "<script>myFunction(".$json_options.")</script>";

Upvotes: 2

Related Questions