Reputation: 441
I would like to set php session with ajax. there is my function to set session in session.php.
public static function set($key, $value) {
$_SESSION[$key] = $value;
}
and I have confirm javascript alert and if I click on yes, i want to set session. How can I set session simply?
EDIT 16.4.2012 15:31 GMT:+1
David: thanks for an answer, it looks clearly. I tried it, but doesn´t do anything at my pc. So I have: a.php
<script src="http://code.jquery.com/jquery-latest.js"></script>
<p>I would like to say: </p>
<script>
$("p").append("<strong>Hello</strong>"); //check jquery is working
$.get('a.php', function(data) {
// do something on success?
});
</script>
b.php (in same folder)
<script type="text/javascript">
alert('aaa');
</script>
<?php
echo "print by b.php";
?>
and I run a.php in browser
Upvotes: 1
Views: 6062
Reputation: 218827
You can have a simple PHP page which does nothing more than set the value (using the code you already have), and then have jQuery call that page:
$.get('setsessionvalue.php', function(data) {
// do something on success?
});
If you want to expand it, you can make the call more general by passing values on the query string:
$.get('setsessionvalue.php?key=someKey&value=someValue', function(data) {
// do something on success?
});
Then you'd pull those query string values from the $_GET
collection on the server just like any other page.
From the server-side code's perspective, it's not different than any other page. You just don't need to render a UI (and can render data if you want, probably easiest in JSON format). The JavaScript code is just calling that page like any other page.
It's worth noting, of course, that a user can call this page manually if they want to. So don't use this as any kind of "security" for session values. If a user goes to the URL:
setsessionvalue.php?key=someKey&value=someValue
then they would be able to set their session values manually. Even overriding the values you've already set (which they can see in the JavaScript code). I wouldn't be particularly comfortable exposing the structure of session values (especially their keys) to client-side code like that. It seems like a short distance away from having some security holes in your site.
Upvotes: 2