I need to set a PHP $_SESSION variable using the jQuery. IF the user clicks on an image I want to save a piece of information associated with that image as a session variable in php.
I think I can do this by calling a php page or function and appending that piece of info to the query string.
Any ideas. I have found little help through google.
thanks mike
jQuery is a JavaScript library and JavaScript is a Client Side language and hence directly it is not possible to set Session variable in jQuery.
Before you can store any information in session variables, you must first start up the session. To begin a new session, simply call the PHP session_start() function. It will create a new session and generate a unique session ID for the user. The PHP code in the example below simply starts a new session.
PHP $_SESSION is an associative array that contains all session variables. It is used to set and get session variable values.
You can't do it through jQuery alone; you'll need a combination of Ajax (which you can do with jQuery) and a PHP back-end. A very simple version might look like this:
HTML:
<img class="foo" src="img.jpg" /> <img class="foo" src="img2.jpg" /> <img class="foo" src="img3.jpg" />
Javascript:
$("img.foo").onclick(function() { // Get the src of the image var src = $(this).attr("src"); // Send Ajax request to backend.php, with src set as "img" in the POST data $.post("/backend.php", {"img": src}); });
PHP (backend.php):
<?php // do any authentication first, then add POST variable to session $_SESSION['imgsrc'] = $_POST['img']; ?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With