-1

i want to set php session value from javascript i know it is not possible to do from javascript so i made this code

javascript:

 window.open("test.php?s=1");

php:

session_start();
    if(!empty($_GET['s'])) {
        $_SESSION['test']= $_GET['s'];
    }

it is working and all but only problem is that it opens new window and user have to close it

is it possible to do something like that without opening new window? i know it is possible to do with xmlhttp.open but it didn't really worked for me + i have no idea how to use it, tried to understand it by searching info in google but couldn't so i figured out that this way i am doing is the simples for me just need to do it without opening new window

2 Answers2

-1

You can use ajax for this:-

    $.ajax({url: "test.php", data: 's=1', success: function(result){
        //if need to code else don't
    }});
  • But how can i get like same SESSION value from php to javascript using AJAX? I was looking for that but didn't really get how can anyone please show example? – Artis Laizans Aug 17 '18 at 21:47
  • $.ajax({url: "test.php", data: 'action=get_s', success: function(result){ alert(result); }}); php:- if( isset($_GET['action']) && $_GET['action'] == 'get_s') { echo $_SESSION['test']; exit; } – Sanjeev Chauhan Aug 18 '18 at 11:25
  • please vote up, if it helps you and make it correct. – Sanjeev Chauhan Aug 20 '18 at 09:43
-2

How about using AJAX?

JS:

var params = {"s":1};
$.ajax({
    data:  params,
    url:   'set_global.php',
    type:  'post',
    success:  function (response) {
        
    }
});

PHP:

session_start();
if(!empty($_POST['s'])) {
    $_SESSION['test']= $_POST['s'];
}
varo90
  • 56
  • 1
  • 9
  • Works perfectly! thank you, i always thought that AJAX is hard and was afraid of using it, you just proved that i was wrong – Artis Laizans Aug 17 '18 at 16:58
  • Can you please show me an example of getting php value like SESSION to javascript using AJAX? I was looking in google for that but couldn't understand how.. – Artis Laizans Aug 17 '18 at 21:49
  • @ArtisLaizans Check this: https://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript – varo90 Aug 18 '18 at 10:33