0

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

3
  • What's that have to do with the fact that you're trying to make PHP spit out an array as a string?, Why not just pass as json object? json_encode($options) Commented Jun 18, 2015 at 4:19
  • @ksealey So, how do I make my php spit out an array as an array? Commented Jun 18, 2015 at 4:21
  • Turn that array into a string representation of a java array and assign it to a javascript variable, then pass that variable, or do as I noted in the edit above Commented Jun 18, 2015 at 4:23

3 Answers 3

2

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>";
Sign up to request clarification or add additional context in comments.

Comments

0

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); ?>;
}

Comments

0

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>";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.