Using javascript to assign a php variable

2019-05-23 09:53发布

问题:

I purchased modalbox plugin from envato market place made in javascript i want to use it to implement my categories> subcategories> items. Anyhow i know JavaScript variable can be assigned a value using php however i need the opposite.

On my first step i let the user pick a category using basic links then onclick even takes them to second slide where i want to display the subcategories and items related to this category that was selected.

I tried two things:

1) setting onClick = "step2();<?php $chosen_cat = ' . $this->db->escape(trim($category)) . '?>"

Hoping i can simply assign the name of the selected category to a value and then just use $chosen_cat in step2() javascript method to display products however this breaks the javascript as there is a conflict in output;

2) I changed step2() to step2(category) and then used, onclick="step2(db->escape($category););" this passes the value to the step2() method however now i would need to call <-- I would need to print out that string to php however i have no idea how to solve this considering PHP -> JS is viable as its server to client relation but back..

The $this->db->escape() is a http://codeigniter.com/user_guide/database/queries.html codeigniter method.

My code:

<script type="text/javascript">

        function step1() {
            modalbox.show(new Element("div").insert(
                new Element("p", { "align": "justify" }).insert(
                    <?php 
                        $categories = $items;
                        $chosen_cat = '';
                    ?>
                    <?php 
                        $i = 0;
                        foreach($categories as $category => $itemarray) {
                            $i++;
                            if($i==27){
                                echo  $this->db->escape('<a class="category" onclick="step2();<?php $chosen_cat = ' . $this->db->escape(trim($category)) . '?>" href="#">'. trim($category) . '</a>');
                            }
                            else {
                                echo $this->db->escape('<a class="category" onclick="step2();" href="#">' . trim($category) . '</a>')  . '+';
                            }
                        }
                    ?>
                )
            ), {
                "title"     : "Step 1/3",
                "width"     : 800,
                "options"   : [{
                    "label"     : "Next »",
                    "onClick"   : step2
                }]
            });
        };

        function step2() {
            alert(<?php $this->db->escape($chosen_cat); ?>);
            modalbox.show([ new Element("div").insert(
                new Element("p", { "align": "justify" }).insert(
                    "If you open a modalbox when another one is opened, it will stretch to the new " +
                    "modalbox width and height and overwrite the content.<br /\><br /\>" +
                    "You can use HTML or Prototype Elements like a DIV or a TABLE."
                )
            ),
                new Element("p", { "align": "justify" }).insert(
                    "You can have multiple contents on a single modalbox by using an array like this:<br /\><br /\>" +
                    "<pre>modalbox.show([ content1, content2, ... ], options);</pre>"
                )
            ], {
                "title"     : "Step 2/3",
                "width"     : 800,
                "options"   : [{
                    "label"     : "« Previous",
                    "onClick"   : step1
                }, {
                    "label"     : "Next »",
                    "onClick"   : step3
                }]
            }); 
        };
        function step3() {
            modalbox.show([ new Element("div").insert(
                new Element("p", { "align": "justify" }).insert(
                    "If you open a modalbox when another one is opened, it will stretch to the new " +
                    "modalbox width and height and overwrite the content.<br /\><br /\>" +
                    "You can use HTML or Prototype Elements like a DIV or a TABLE."
                )
            ),
                new Element("p", { "align": "justify" }).insert(
                    "You can have multiple contents on a single modalbox by using an array like this:<br /\><br /\>" +
                    "<pre>modalbox.show([ content1, content2, ... ], options);</pre>"
                )
            ], {
                "title"     : "Step 3/3",
                "width"     : 800,
                "hideOnPageClick": false,
                "options"   : [{
                    "label"     : "« Previous",
                    "onClick"   : step2
                }, {
                    "label"     : "Finish",
                    "isDefault" : true,
                    "onClick"   : modalbox.hide
                }]
            });
        };

    </script>

Would it be possible to set a session variable with JavaScript in the onclick event say $_SESSION['category'] = 'category' in js style and then read that session with php and unset it i dont think this would create much of a security problem as session would exist for prolly less than a second.

回答1:

JavaScript is never going to set a PHP variable. JavaScript runs on the client and PHP on the server. If you need to change something on the server from JS, you have to use AJAX, or send a regular HTTP request.

Alternatively, you can have PHP generate the data that is needed at runtime on the client, usually by printing some JSON to become a JS variable

In your example, you would need something like the following (I'll use jQuery for simplicity)

... onclick="$.ajax('/category.php').done(function(data) {step2(data.category);})"

Which would be much nicer if it weren't JS within HTML

$('#my-button').click(function(){
    $.ajax('/category.php').done(function(data) {
        step2(data.category);
    });
});

I can't give you an AJAX tutorial, but the main thing is that you'll make an AJAX request when you need data from the server.