Reputation: 1
I would like to manipulate elements on a page based on user data (last name). I built a form, and uses post to update input data to php page. My thought was to get the $_POST value into the DOM: Then grab in JQuery:
Form page:
<form action="display.php" method="post">
<input type="text" name="test" />
<input type="submit" value="go!!" />
</form>
Display.php
<?php
//store post value in var
$var = $_POST['test'];
?>
(above html)
<body>
<?php
echo '<form action="" method="">';
echo '<input type="hidden" class="grab" name="name1" value="' . $_POST['test'] . '">';
echo '</form>';
?>
<script type="text/javascript" src="js/script.js"></script>
</body>
(in html)
script.js
var grab = $('input.grab').val();
document.write(grab);
I am a PHP newbie and realize that i am solving all my problems as a client side developer, not server side. Am I doing something terribly wrong? Or is there a better way
Upvotes: 0
Views: 166
Reputation: 19879
That's fine. Because JavaScript is a client-side language, this is a perfectly acceptable method of giving your JavaScript access to variables that are only available to the server.
You could also use something like:
<script>
var myVar = '<?php echo $_POST['var']; ?>';
console.log(myVar);
</script>
To prevent XSS and avoid issues with quotes in POST data, you should sanitize the output using htmlspecialchars:
<script>
var myVar = '<?php echo htmlspecialchars($_POST['var'], ENT_QUOTES, 'utf-8'); ?>';
console.log(myVar);
</script>
Otherwise, $_POST['var'] = 'example
will break your JS and open up an XSS vulnerability.
Upvotes: 1