Jump to content

Ajax updating instantly/PHP session variables??


galvin

Recommended Posts

Very new to AJAX and curious about something.  I know that AJAX's advantage is that it doesn't reload the whole page.  I currently have a text field where a user can enter text and I got the AJAX working so that onKeyUp, it runs a PHP file that inlcudes the code below...

 

	$_SESSION['correct'] = $_SESSION['correct'] + 1;
	 echo "YES!";

 

I'm getting the value "YES!" back to my original page instantly just fine (Thank you, AJAX).  But my problem is with the $_SESSION['correct] variable.  The PHP file increases the value of it by 1, but back on my main page, I have...

 

echo $_SESSION['correct'];

 

...and the problem is that this number doesn't update instantaneously (like the AJAX stuff does), and it doesn't update until I do a page refresh (F5).

 

For example, I'm on my main page and $_SESSION['correct'] = 3.  I then perform the AJAX action which increases $_SESSION['correct'] by one (so it's now 4), but my main page still only shows it as 3.  If I hit F5, it then changes to 4.  I need to have that $_SESSION variable update immediately as well.

 

So I'm just curious if there is something I could add to my code to make $_SESSION['correct'] update instantaneously on my main page. 

 

In a nutshell, I need to have the AJAX code for one part of the page, but I also need to have the page reloaded as well, to update $_SESSION variables. 

 

Any insight on proper logic I should be using to tackle this issue? (if what I wrote makes any sense :) )  Should I just force a page reload?  If so, how do I do that with PHP?

 

Thanks,

Greg

 

 

 

In your php response page, try to send the $_SESSION[] variable along with the response and then display that in a div. That should work i think. New to ajax myself, but im guessing that the reason its still only showing the old value is because you havnt made that part of information 'refresh' as such.

 

As an example to send it with your message:

 

<?php
         $response = 'YES!';
         $comma = ',';
         $response2 = $_SESSION['correct'];

          print $response;
          print $comma;
          print $response2;
?>

 

Obvoisly this will need to be sent ONCE you have already updated the $_SESSION[] to + 1.

 

Then get your values from that request and split them into an array:

 

javascript page:

function(str)
{
    responseArray = str.split(',');

    response1 = responseArray[0];
    response2 = responseArray[1];

    alert(response1 + ':' + response2);
}

 

That should alert the correct values...

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.