1

I would like to pass a var from PHP to Javascript. I did this but it does not work. Can someone help me? If you tell me where I'm wrong I learn.

<script>
    var passo = <?php echo 'hello'; ?>;
</script>

<button type="button" onclick="funzionepassaggio(passo)" class="btn btn-info btn-lg" data-toggle="modal" data-target="#ModalSubmit"><?php echo "empty"; ?></button>

<script>
      function funzionepassaggio(pass) {
          alert("hello" + pass);
      }
    </script>

The answer is hello undefined.

I have one other question! The variable that I have to pass is located within a loop, and of course he always passes the last value! How can I do so that has passed the value that the variable at that time? This is the code:

for ($a = 0; $a < 2; $a = $a + 1) {
          ?>
            <td>
                <script>
                    var passo = "<?php echo $rigauno->nome; ?>";
                </script>
                <button type="button" onclick="funzionepassaggio(passo)" class="btn btn-info btn-lg" data-toggle="modal" data-target="#ModalSubmit"><?php echo "vuoto"; ?></button>
            </td>
        <?php }  ?>
1
  • If you are trying to pass some paramter to JavaScript function by setting php value to that paramter, then you can directly do it by onclick="funzionepassaggio(<?php $phpVariableHere ?> )" Commented Apr 1, 2016 at 10:08

3 Answers 3

2

you need to incude the quotes, so it will be valid string:

<script>
    var passo = "<?php echo 'hello'; ?>";
</script>

or better call json_encode that will convert whatever you pass as JSON:

<script>
    var passo = <?php echo json_encode($data); ?>;
</script>
Sign up to request clarification or add additional context in comments.

Comments

2

json_enocde variable which you want to pass

<script>
  var passo = <?php echo json_encode('hello'); ?>;
</script>

Comments

0
$pass='your string or your value ';
<button type="button" onclick="funzionepassaggio('<?php echo $hello; ?>')" class="btn btn-info btn-lg" data-toggle="modal" data-target="#ModalSubmit"><?php echo "empty"; ?></button>
<script>
  function funzionepassaggio(pass) {
      alert("hello" + pass);
  }
</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.