简体   繁体   中英

defining a php variable inside js

I know you can do the opposite, and that you can't change a php value from js which is defined outside of js(at least as far as I know?), but what about a php variable which is defined inside of a js var. per say:

function captureID(clicked_id){
var clickedVar = (clicked_id);
    var alert_type = document.getElementById(clickedVar).getAttribute('class');
    var infoVar = document.getElementById(clickedVar).getAttribute('value');
    var usernameVar = "<?php 
    $fetch_username = mysql_query('SELECT info FROM alerts WHERE id = "clickedVar"');
    while ($row = mysql_fetch_array($fetch_username)){
        $username = $row['username'];   
    }

if (alert_type == 'b_alert'){
        var type = 'battle';
    } else if (alert_type == 'a_alert'){
        var type = 'award';
    } else if (alert_type == 'f_alert'){
        var type = 'friend';
    }
    alert(type);
    if (type == 'battle'){
        document.getElementById('battle_username').text(<?php echo $username; ?>)
    } else if (type == 'award') {

    } else if (type == 'friend'){

    }

}

and then again using the variable inside of the js script. is this a possibility? because it's not seeming to work. no distinct errors, just not working.

Its not possible to get the value of a js variable and input it into your sql.

As javascript is client side and PHP is server side.

yes it can work but IF you put this code insde a php file

look at my variables

    var $tab_title_input = $("#tab_title"), $tab_content_input = $("#tab_content");
    var tab_counter = <?= $this->nbList ?> +1; //$this->UserLists::count()+1;

& am working with it no problem ;)

You can call a PHP file from JavaScript and pass the variables you want via POST or GET. Or simply set a COOKIE.

Cookie would be sent to PHP at the very first next page request and PHP can act on it.

Simply put this JS inside your php file :

<script type="text/javascript">
    var javaScriptVar = "<?php echo $someVar; ?>"; 
</script>

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