1

I am trying to save the PHP array and $_POST value in to javascript variable but it does not work.

This is how i am doing it.

<html>
 <script>
   var username = <?php echo $_POST['username']; ?>
   var password = <?php echo $_POST['password']; ?>
   //abc(username, password);
   document.write(username+' '+password);// does not work
</script>
<body>
    <form method="post">
        Username: <input type="text" name="username" /><br />
        Password: <input type="password" name="password" /><br />
        <input type="submit" value="login" />
    </form>
</body>
</html>

How can i achieve this?

If i pass a hard coded variable to JavaScript function, that works only. Let me show you how.

<script>
function func(v1, v2){
   document.write(v1+' '+v2);// does not work 
}
</script>
<?php
$a = 25;
$b = 30; 
echo '<script>func('.$a.','.$b.');</script>'

?>
2
  • What does "does not work" mean? You'll need to be more clear about the problem and what isn't working. Commented Nov 3, 2013 at 21:58
  • added some details to my question. Please check out now. Commented Nov 3, 2013 at 22:04

2 Answers 2

4

Supposing your variables $_POST['username'] and $_POST['password'] are foo and bar respectively, your JavaScript code is being generated probably like this:

var username = foo
var password = bar

You need to add quotes around your values to JavaScript parse them as strings too, otherwise it will think you are assigning foo and bar variables to them.

Also, you should use addslashes to escape possible "characters in your string and prevent it from breaking your JavaScript code.

var username = "<?php echo addslashes($_POST['username']); ?>"
var password = "<?php echo addslashes($_POST['password']); ?>"
Sign up to request clarification or add additional context in comments.

6 Comments

Don't forget the ending semicolons.
Semicolons in JavaScript are optional.
Thanks @ Guilherme Sehn, it worked. It was not working without semi columns. I added the semicolon and then terminator at the end and it worked.
Yes, however it's a best practice.
Clear and concise. +1
|
1

You need to add quotes:

var username = "<?php echo $_POST['username']; ?>"

Otherwise JavaScript will interpret $_POST[] value as an undefined variable.

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.