0

I would like to pass on a $_POST['foo'] variable to a JavaScript variable while I am using a php if- statement. But its not working. Any suggestions on how to make it run?

<?php
if(isset($_POST['foo']))    
{    
?>
<script>
var jFoo= <?php echo json_encode($_POST['foo']); ?>;
</script>
<?
}


 else {
    ...
    }
    ?>

EDIT:

This is weird: I was actually trying to make the code run like this (this wasnt working):

if(isset($_POST['foo']))    
{    
?>
<script>
var jFoo= <?php echo json_encode($foo); ?>;
</script>
<?
}
else {
...
}

However, when I just did this, it worked:

<?php
if(isset($_POST['foo']))    
{    
?>
<script>
var jFoo= <?php echo json_encode($_POST['foo']); ?>;
</script>
<?
}
else {
...
}

Any ideas why?

7
  • 1
    Have you looked at the output HTML? Is it missing quote marks? Commented Sep 7, 2014 at 18:50
  • 1
    I don't see anything wrong with the code you posted. Why doesn't it work? What errors do you get? What is the output from your PHP script? Commented Sep 7, 2014 at 18:50
  • Posted variables are usually strings so you will need to change your code to var jFoo="<?php echo json_encode($_POST['foo']); ?>"; Commented Sep 7, 2014 at 18:50
  • @jeff That's completely incorrect. The JSON-encoding handles any quoting that is needed. Adding additional quotes actually breaks this. Commented Sep 7, 2014 at 18:50
  • @jeff $_POST variables can also be arrays Commented Sep 7, 2014 at 18:52

2 Answers 2

2

I made a simple change in your script and it works for me. I changed the code in line 9 from

<?php
if(isset($_POST['foo']))    
{    
?>
<script>
var jFoo= <?php echo json_encode($_POST['foo']); ?>;
alert(jFoo);
</script>
<?php
}
else {

}
?>

<form action="" method="post">
    <input type="text" name='foo' />
    <button type="submit">Submit</button>
</form>
Sign up to request clarification or add additional context in comments.

Comments

1

This code works normally:

        <form method="post" action="">
             <input type="text" name="foo"></input>
             <input type="submit" name="submit" value="submit">
        </form>
        <script type="text/javascript">
           <?php
              if(isset($_POST['foo'])) {
           ?>
           var jFoo = <?php echo json_encode($_POST['foo']); ?>;
           alert(jFoo); // test
           <?php } ?>
        </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.