VVV
VVV

Reputation: 417

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.

Upvotes: 0

Views: 123

Answers (4)

Fady
Fady

Reputation: 211

Simply put this JS inside your php file :

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

Upvotes: 0

transilvlad
transilvlad

Reputation: 14532

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.

Upvotes: 0

ucefkh
ucefkh

Reputation: 2531

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 ;)

Upvotes: 0

Lawrence Cherone
Lawrence Cherone

Reputation: 46620

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.

Upvotes: 3

Related Questions