Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a PHP $_SESSION['var'] using jQuery

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

like image 213
mmundiff Avatar asked Mar 03 '09 19:03

mmundiff


People also ask

Can we set session value in jQuery?

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.

How can we set session and session in PHP?

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.

What is $_ session variable in PHP?

PHP $_SESSION is an associative array that contains all session variables. It is used to set and get session variable values.


1 Answers

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']; ?> 
like image 81
Luke Dennis Avatar answered Sep 19 '22 08:09

Luke Dennis