Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ways to pass php post data to javascript

So I was wondering, if I have a simple php form that posts information to a certain variable, how can I pass that posted variable to javascript and be able to manipulate the data? The only way I've figured out is by using inline javascript with php but I feel there must be a cleaner and more elegant way to do it where the variables don't show up so blatantly in the source code and are handled externally.. Here's what I'm playing around with right now:

<form action="index2.php" method="post">
    <input name="sugar" class="form" type="text" value="" />
    <input name="fat" class="form" type="text" value="" />
    <input name="protein" class="form" type="text" value="" />
    <input type="submit" value="submit" />
</form>

Which is followed by:

<?php 
$sugar = $_POST['sugar'];
$fat = $_POST['fat'];
$protein = $_POST['protein'];
?>

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        var sugar = "<?php echo $sugar ?>";
        var fat = "<?php echo $fat ?>";
        var protein = "<?php echo $protein ?>";
    </script>
    <script src="test.js" type="text/javascript"></script>
</head>

Does anyone have any suggestions for alternatives I could follow? I haven't been using javascript for too long so it would be nice to know my options when dealing with a situation such as this.

like image 830
tom c Avatar asked Aug 03 '12 15:08

tom c


2 Answers

The easiest way to do this would be simply to send a Javascript object containing all the data you sent. This can easily be accomplished by JSON-encoding $_POST:

var data = <?php echo json_encode($_POST) ?>;

You can then access, for instance, data.fat if you sent a fat value in your POST request.

like image 169
lonesomeday Avatar answered Sep 28 '22 12:09

lonesomeday


Without using _GET as well and storing the variables in the URL you have the best solution for your requirements currently.

like image 44
Ryan McDonough Avatar answered Sep 28 '22 12:09

Ryan McDonough