最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Ways to pass php post data to javascript - Stack Overflow

programmeradmin2浏览0评论

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=".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.

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.

Share Improve this question asked Aug 3, 2012 at 15:43 tom ctom c 3292 gold badges4 silver badges13 bronze badges 4
  • What do you mean by "handled externally"? You want to create an extra script file for each request? Inline scripts are just fine for that task. – Bergi Commented Aug 3, 2012 at 15:48
  • I will. This is just a test I'm running. – tom c Commented Aug 3, 2012 at 15:48
  • Can you explain why you would need to directly ship the $POST values to JavaScript? – Bergi Commented Aug 3, 2012 at 15:50
  • For this experiment I'm running, when I enter a number into the sugar, fat and protein boxes, they generate a graphical meter that shows how those values correspond to daily recommended intakes. Ultimately if I kept working on this it would send the post data to a database and then generate the intake meters from data retrieved in a database array (which I think would also require a similar solution). – tom c Commented Aug 3, 2012 at 15:56
Add a comment  | 

6 Answers 6

Reset to default 9

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.

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

These variables will have to be printed and visible somewhere if you want to get them to your JavaScript.

JSON-encoding them and printing them so that they're saved in a local JavaScript variable is what I've always been using:

<?php
    function passToJavascript($variableName, $variable){
        if($variable = json_encode($variable))
            echo '<script>var '. $variableName .' = '. $variable .';</script>';
    }

    $foo = array(
        'bar1' => 1,
        'bar2' => 2,
        'bar3' => 3
    );

    passToJavascript('foo', $foo);
?>

Will print in your HTML:

<script>var foo = {"bar1":1,"bar2":2,"bar3":3};</script>

And that way you can pass whatever variable you want, may that be a string, a number, an array or even an "associative array".

I feel like the best way to pass php variables over to javascript variable is to json_encode them first. If you are passing a php array over to javascript you can't simple say

var1 = <?php echo $var1; ?>

you should do it like the follwing.

<?php
    $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
?>

<script type="text/javascript">
    var arr = "<?php echo json_encode($arr) ?>";
</script>

You could write your vars in inputs and then reach these inputs with javascript

<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">
            //You already linked jquery so I use it, you could do without if necessary.
            $(document).ready(function(){
                var sugar = $('#sugar').val();
                var fat = $('#fat').val();
                var protein = $('#protein').val()
            });
        </script>
            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>
    <body>
        <input type="hidden" id="sugar" value="<?php echo $sugar ?>" />
        <input type="hidden" id="fat" value="<?php echo $fat?>" />
        <input type="hidden" id="protein" value="<?php echo $protein?>" />
    </body>
</html>

That way your javascript can all reside in a static file.

you could try sending your variables with GET instead of POST, and then you can access them directly from javascript like this: http://javascript.about.com/library/blqs1.htm

There is no way to access POST variables from javascript, as far as i know. You would have to use something like you are doing

发布评论

评论列表(0)

  1. 暂无评论