Hunza Ali
Hunza Ali

Reputation: 189

Trying to save PHP $_POST variable into javascript but it does not work

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>'

?>

Upvotes: 1

Views: 350

Answers (2)

Guilherme Sehn
Guilherme Sehn

Reputation: 6787

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']); ?>"

Upvotes: 4

XCS
XCS

Reputation: 28157

You need to add quotes:

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

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

Upvotes: 1

Related Questions