How to pass PHP array parameter to Javascript Function?

39,699

Solution 1

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 2

<input type="submit" value="Test Javascript" onclick='showMovies(<?php echo 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:

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

Solution 3

Try this

PHP Code

<script type="text/javascript" src="javascript.js"> </script>
<?php
  $movies = array("Bloodsport", "Kickboxer", "Cyborg", "Timecop", "Universal Soldier", "In Hell", "The Quest");
  $mov_str = implode(",", $movies);
?>

<input type="submit" value="Test Javascript" onclick="showMovies('<?php echo $mov_str; ?>');" />

In Javascript File

function showMovies(movies) {
  movies = movies.split(",");
  alert(movies.length);
 return false;
}

Output

7

I hope this will help you.

Solution 4

Encode as JSON before outputting.

<input type="submit" value="Test Javascript" onclick="showMovies(<?php echo json_encode($movies); ?>);" />

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.

Share:
39,699
Son of Man
Author by

Son of Man

Just started to learn programming

Updated on July 11, 2022

Comments

  • Son of Man
    Son of Man almost 2 years

    index.php

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


    javascript.js

    function showMovies(movies) {
     alert(movies.length);
    
     return false;
    }
    

    I am new to programming so Im having hard time fixing this one which is obviously simple for you guys.

    When I hit the submit button it says the that the array size is 1 which I think should be 7. How could this be?

  • Son of Man
    Son of Man almost 13 years
    what is json??? Is that something built-in in native javascript or is that a plugin I need to install?
  • Ignacio Vazquez-Abrams
    Ignacio Vazquez-Abrams almost 13 years
    Read documentation first, then come back with a sensible question.
  • Joel
    Joel almost 13 years
    Wow, Ignacio, that was rude. @Son of Man: You can do a quick search on Google for "JSON" to get a good idea of what JSON is.
  • Ignacio Vazquez-Abrams
    Ignacio Vazquez-Abrams almost 13 years
    Rude is expecting someone else to do all the research for you.
  • Son of Man
    Son of Man almost 13 years
    <input type="submit" quest"]);"="" hell","the="" soldier","in="" bloodsport","kickboxer","cyborg","timecop","universal="" onclick="showMovies([" value="Test Javascript ... That is what is shown if Firebug and the button is not working anymore... Pls help
  • ErikE
    ErikE almost 13 years
    Rude is treating honest ignorance as maliciousness.
  • Ignacio Vazquez-Abrams
    Ignacio Vazquez-Abrams almost 13 years
    @Son: At that point you need to fix your quotes as mentioned in the other answer. And don't trust Firebug to show you what your page really looks like.
  • Ignacio Vazquez-Abrams
    Ignacio Vazquez-Abrams almost 13 years
    @ErikE: Feel free to guide the asker to the Getting Answers page then.
  • Son of Man
    Son of Man almost 13 years
    You mean I have to mix my javascript with my php code??? I want to separate them... Pls help I am a beginner...
  • ErikE
    ErikE almost 13 years
    I doubt a sterile page on JSON would do the OP any good. He has a conceptual hole he is not aware of called server/client. He doesn't know enough to see this hole or even ask how to fix it. You with your godlike 100k rep should be able to figure this out as well as I did. So, are you going to send him to your favorite tutorial on the subject or just mock? He's likely to land at w3schools if you don't help him.
  • Ignacio Vazquez-Abrams
    Ignacio Vazquez-Abrams almost 13 years
    Printing an array in PHP results in "array". Ain't nothing server/client in that.
  • ErikE
    ErikE almost 13 years
    So you don't grasp his conceptual problem? Bizarre! Maybe you should do a search instead of expecting me to explain it to you. Seriously, though, don't be Evil. @Son start with this tutorial.
  • Ignacio Vazquez-Abrams
    Ignacio Vazquez-Abrams almost 13 years
    It's an output problem. He doesn't (didn't) know how to encode something in one language in a manner that the other language would understand.
  • ErikE
    ErikE almost 13 years
    Read my answer. It goes deeper than that.
  • Ignacio Vazquez-Abrams
    Ignacio Vazquez-Abrams almost 13 years
    It is perfectly valid to generate JavaScript code via PHP, which is what is being done in the question.
  • ErikE
    ErikE almost 13 years
    Of course. The JS can be in a separate file or in the HTML returned from the PHP script. But the actual values have to be encoded in JS in some place where JavaScript is expected, like an event attribute or a script tag. You can't actually put JavaScript in PHP or vice versa because neither would execute. You have to switch back and forth appropriately.
  • ErikE
    ErikE almost 13 years
    @Ignacio if you really thought you had to explain to me that you "can generate JavaScript via PHP" then you are really not getting it! Trust me, the way I explained it is what the OP needs. @son do you have any input for us?
  • Ignacio Vazquez-Abrams
    Ignacio Vazquez-Abrams almost 13 years
    Where does the value of the variable ever change?
  • ErikE
    ErikE almost 13 years
    @Ignacio what are you talking about? If you want to change a variable's value, do so. If you want the client to change data on the server, GET or POST and read the data.
  • ErikE
    ErikE almost 13 years
    @Ignacio By the way, you are absolutely correct that in the given question the OP was almost on track to spit out the movies PHP value and just needed to know how to convert it to an array. My apologies for arguing so vociferously when you were correct and I was wrong. Interestingly enough, the OP still marked my answer as the selected one... not sure why, but maybe I was on to something a bit elusive. Again, sorry about continuing to argue even though I was wrong.
  • Atul
    Atul about 5 years
    notice the ' instead of ", because JSON uses " >> This line works for me ...thanks