Skip to content Skip to sidebar Skip to footer

How To Pass Php Array Parameter To Javascript Function?

index.php

Solution 1:

<inputtype="submit"value="Test Javascript"onclick='showMovies(<?phpecho json_encode($movies); ?>);' />

Notice the json_encode, which encodes objects or arrays for Javascript (JSON stands for JavaScript Object Notation) and also notice the ' instead of ", because JSON uses ".

Although, this soulution would be better:

<scripttype="text/javascript">document.getElementByID('submitButton').onclick = function() {
        var movies = <?phpecho json_encode($movies); ?>;
        showMovies(movies);
    };
</script>
...
<inputtype="submit"value="Test JavaScript"id="submitButton">

Solution 2:

Try this

PHP Code

<scripttype="text/javascript"src="javascript.js"></script><?php$movies = array("Bloodsport", "Kickboxer", "Cyborg", "Timecop", "Universal Soldier", "In Hell", "The Quest");
  $mov_str = implode(",", $movies);
?><inputtype="submit"value="Test Javascript"onclick="showMovies('<?phpecho$mov_str; ?>');" />

In Javascript File

functionshowMovies(movies) {
  movies = movies.split(",");
  alert(movies.length);
 returnfalse;
}

Output

7

I hope this will help you.

Solution 3:

Encode as JSON before outputting.

<inputtype="submit"value="Test Javascript"onclick="showMovies(<?phpecho json_encode($movies); ?>);" />

Solution 4:

Your PHP variables only live on the server. They are completely separate from the JavaScript variables on the client. The only mechanism for passing values from the server to the client is through the contents of the web page (or through specially requested behind-the-scenes web content through AJAX).

This means that to make your JavaScript receive PHP values, you have to write JavaScript with those values embedded inside of it. You must mix the PHP with the JavaScript at least a tiny bit to get the stuff that runs on the client to have any data from the server.

This is how all web server-side scripting works in all languages.

JavaScript simply cannot know what goes in your movies variable unless you stuff it full of values, in JavaScript.

I recommend you to @levu's answer to see a good way to get your PHP variable's values into JavaScript.

Solution 5:

You can pass array in js by json_encode() php function.. json_encode() will make array into string. you can get array back by saprating that string in js.

Post a Comment for "How To Pass Php Array Parameter To Javascript Function?"