0

i want to change php $_SESSION with jquery events. in this below code $_SESSION['lang'] dont change

    $('[id^="lang_"]').click(function(){
        alert('<?php echo $_SESSION['lang']; ?>');
        lang_id = $(this).attr('id').split(/\_/);
        alert(lang_id[1]);
        switch( lang_id[1] ){
            case '1':
                //lang_id[1] is 1
                <?php unset($_SESSION['lang']); $_SESSION['lang'] = null;  $_SESSION['lang'] = '11111'; ?>
                break;
            case '2':
                //lang_id[1] is 2
                <?php unset($_SESSION['lang']); $_SESSION['lang'] = null;  $_SESSION['lang'] = '22222'; ?>
                break;
        }

i dont have any problem to get correct lang_ id. but $_SESSION['lang'] dont change anywhere

2 Answers2

4

I'm actually a little bit speechless. :)

Okay..

Javascript (and jQuery) run on the visitors browser.

PHP runs on the web server your website lives on.

You cannot run PHP Code inside of Javascript. You can output PHP Variables into a JS function to define specific values like var value='<?php echo $theValue ?>'; - but you cannot run PHP logic within the running of JS Code.

If you want to do this, you need your Javascript/jQuery to make an ajax call to a PHP page that does what you want.

$('[id^="lang_"]').click(function(){
    alert('<?php echo $_SESSION['lang']; ?>');
    lang_id = $(this).attr('id').split(/\_/);
    alert(lang_id[1]);
    switch( lang_id[1] ){
        case '1':
            setLanguage('11111');
            break;
        case '2':
            setLanguage('22222');
            break;
    }


function setLanguage(lang){
    $.post('setLanguage.php', {language:lang}, function(){
        alert('Language has been changed');

        //if you want to reload the current page
        //window.location=window.location.href;
    });
}

Then, your setLanguage.php page should look something like this

<?php 
      unset($_SESSION['lang']); 
      $_SESSION['lang'] = null;  
      $_SESSION['lang'] = $_POST['language']; 
?>

Keep in mind that while this changes the $_SESSION variable as desired, it will not impact the way your page looks/acts until it is refreshed (or you take other manual actions). Honestly, if you need to refresh the page to see the updates, then I might not even use ajax and just direct the user directly to setLanguage.php and have that page redirect them back to where they came from.

Dutchie432
  • 28,798
  • 20
  • 92
  • 109
0

if you write <?php ...?>, this code is executed on Serverside before the file is served to the client. That means both php statements are executed before the client gets the response. There's no way you can mix clientside code and serverside code, because the serverside code is executed before the response is send to the client.

blang
  • 2,090
  • 2
  • 18
  • 17