简体   繁体   中英

php code in jquery click function firing without click

so $user->turnon is always the second value which is "1" when loading page

<script>
    $(document).ready(function(){
        $(".turnof").click(function(e){
            var editcase = "<?php $USER->turnon = 0 ;?>";
        });
        $(".turnon").click(function(e){
            var editcase = "<?php $USER->turnon = 1 ;?>";
        });
    });
</script>

You can't call PHP from a JavaScript function directly like that. PHP code executes on your server, so it will evaluate before the page loads. Your code is the same as...

<?php
    $USER->turnon = 0;
    $USER->turnon = 1;
?>

<script>
    $(document).ready(function(){

        $(".turnof").click(function(e){
            var editcase = "";
        });

        $(".turnon").click(function(e){
            var editcase = "";
        });

    });
</script>

Since you're not using the echo function (or another printing function) in your PHP code, nothing is output to the page, so your click functions will just set your JavaScript variable editcase to be the empty string.

On the PHP side of things, you're just setting $USER->turnon to be 0, and then immediately changing its value to 1. This happens before the page loads.

You may be looking to perform an AJAX request, which allows you initiate requests to your server from a JavaScript function. The request to your server can be used to execute PHP code.

You should do it via Ajax, as stated in the comments.

<script>
    $(document).ready(function(){
        $(".turnof").click(function(e){
            $.ajax({
                url: "/ajax.php?turnon=0",
                context: document.body
            }).done(function() {
                alert('success');
            });
        });
        $(".turnon").click(function(e){
            $.ajax({
                url: "/ajax.php?turnon=1",
                context: document.body
            }).done(function() {
                alert('success');
            });
        });
    });
</script>

This is the ajax.php

//session start etc..
if (isset($_GET['turnon'])) {
    $USER->turnon = $_GET['turnon'] === '1' ? 1 : 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM