Question

I have a file named "test.php" with a link to "test2.php":

<a href="test2.php" id="test">Test</a>

In my test2.php, I check the $_SESSION variable:

<?php session_start();
var_dump($_SESSION);

When I click on the link in the "test.php" file, I want to add data in the $_SESSION variable, so here is my js:

$('#test').on('click', function(e) {
   $.post('test3.php', { myvar : 'myvalue' } );
});

And on the "test3.php" file, I have this piece of code:

<?php session_start();
    $_SESSION['myvar'] = $_POST['myvar'];

I don't understand why it's not working... In the "test2.php" file, the $_SESSION['myvar'] does not exist.

Thanks for your help!

Was it helpful?

Solution

The request to test3.php will be cancelled, because you're not preventing the default behaviour of following the link to test2.php.

Try the following;

$('#test').on('click', function(e) {
   $.post('test3.php', { myvar : 'myvalue' } );
   e.preventDefault();
});

You can then redirect to test2.php when the request completes;

$('#test').on('click', function(e) {
   var that = this;

   $.post('test3.php', { myvar : 'myvalue' } ).done(function () {
       window.location.href = that.href;
   });

   e.preventDefault();
});

OTHER TIPS

you have to change little bit of your code

<a href="javascript:void(0)" id="test">Test</a> 

and

$('#test').on('click', function(e) {
   $.post('test3.php', { myvar : 'myvalue' } ,function(){
window.location.reload('test2.php');//opening page here

});
});

this should work

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top