Thanks for the question feeedback, I beleive you have 2 options here, it's up to you which you feel is more graceful!
- Utilise the Server side PHP/EE Session
For this solution, you'll need a special template that you'll call via AJAX, I normally use a template group called 'API', for example lets call the template 'location'.
On the template, we're going to create 2 modes, one that returns the saved field value and one that saves the field value. This is easy as what we can do is look for a post field and if present and correct set the sesion value, if there's no post then return the value.
For seculrity I'd add a check to ensure the request is an AJAX request (you can google this). Now, this template is going to be a PHP template but there's no reason you can't use EE tags and the plugins Nicholas suggests, but for simplicity I'm going to stick with native PHP.
So here's the process that I'd do :
Create JS that 'fetches' the saved value, if it's blank (not set yet, new session ect) then create the JS that 'sends' the value. Your JS will query the location object and get the value you want to save, and then AJAX Post it to your template.
In the template, use PHP to get the submitted value, be sure to clean it, and save it to the session :
//check AJAX request here
//are we getting or setting?
if ( empty ( $_POST ) ) {
//assume this is the get, make more complex if you wish!
if ( isset ( $_SESSION['savedvalue'] ) ) {
echo json_encode(array(
'savedvalue' => $_SESSION['savedvalue']
));
} else {
echo json_encode(array(
'savedvalue' => ''
));
}
} else {
//were gonna set the value!!
//use EE to fetch and clean the post
$postedValue = ee()->input->post('valuename', true);
//any extra validation here
$_SESSION['savedvalue'] = $postedValue;
}
Thats it, at least in principle, hopefully you get the idea of what I'm doing here and can run with it...
- Use a cookie on the client side
No need for a PHP template or anything fancy here, as we're not leaving the client side.
What we'll do is create similar JS to before but rather that making AJAX calls to the template (to push the value server side) we replace these calls with JS that sets the session cookie you want. You can use JS like this : http://blog.lysender.com/2011/08/setting-session-only-cookie-via-javascript/
There ya go, you should be able to get either to work for you, the beauty is that the AJAX requests have the PHP SESSION ID in them or at least send it back with the response so you don't need to worry about linking a session to a user. One thing to think about though is the logic to update the saved value if it ever changes, after all I might load your page on my laptop, leave it open, hop in the car, goto work and change location!
Drop us a comment if you have further questions, OR vote up/answer anything that helped you get what you needed...