• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 668
  • Last Modified:

Posting to a session variable from <a href>

Hi fellow experts,

At the top of the code I have this
if ($_GET['fav']){ $aFav = $_GET['fav']; }

and I have this link under all images.
<a href="http://www.domain.com/gallery/?fav=<?php echo $aFav; ?>2x" title="Favorite this image" class="open" rel="nofollow"></a>

on clicking the images it will add a new variable to the url string

http://www.domain.com/gallery/?fav=2x1x4x7x 
etc

This looks untidy so I would like to know how can I use the <a href> to post the image number to an array but not change the URL from domain.com/gallery/

I would also want to be able to detect if the same image has been added twice so if  2x is in there twice i would like it to not add it as it is already there.

please ignore the 1x 2x naming of the links, this is just for testing until I hook it up to a database.

Thanks for your help

Shane
0
ShaneJones
Asked:
ShaneJones
  • 8
  • 8
  • 2
6 Solutions
 
JorisWCommented:
The easiest way would be to use a redirect (see code snippet for example).
The downside to this method is that after the page is redirected, you no longer know the value of $aFav. However since you are storing that value you can just make note of the latest one added, and use that after the redirect

Other solutions would be to use javascript (for example a hidden POST form, or a XMLHTTPRequest)
<?php
if (isset($_GET['fav']))
{
	$aFav = $_GET['fav'];
	
	/* Do something with $aFav */
	
	$host  = $_SERVER['HTTP_HOST'];
	$uri   = rtrim($_SERVER['PHP_SELF'], '/\\');
	header("Location: http://$host$uri");
	header('Status: 303 See Other');
	exit; 
}
?>
Normal Content

Open in new window

0
 
dwaynecharringtonCommented:
You could use JavaScript to achieve this.

  1. Create a JavaScript function that makes a POST call to the server using XMLHTTP Request.
  2. Attach the function to the link using the onclick handler to the hyper link.
  3. When the link is clicked, the function is called and the predefined data in the function is sent to the server.
0
 
ShaneJonesAuthor Commented:
Thanks for the response. Do you have any examples of how to do this? I normally learn easier by seeing code.

@dwaynecharrington: do you have any more information on step 1? 2 and 3 seem easy enough.

Also how do I get the date to php from JavaScript?

Thanks

Shane
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
JorisWCommented:
Simple example of using XMLHttpRequest:
The following script assumes that your fav id will never contain any special characters.
// HTML
<a href="http://www.domain.com/gallery/?fav=<?php echo $aFav; ?>2x" title="Favorite this image" class="open" rel="nofollow" onclick="favLinkClick('<?php echo $aFav; ?>2x');return false;"></a>
 
// Javascript
function favLinkClick(favId) 
{
	var http = getHTTPObject(); 
	http.open("GET", "http://www.domain.com/gallery/?fav="+favId, true);
	http.send(null);
}
 
function getHTTPObject()
{
	var xmlhttp;
	/*@cc_on
	@if (@_jscript_version >= 5)
		try {
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (E) {
				xmlhttp = null;
			}
		}
	@else
		xmlhttp = false;
	@end @*/
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		try {
			xmlhttp = new XMLHttpRequest();
		} catch (e) {
			xmlhttp = null;
		}
	}
	return xmlhttp;
}

Open in new window

0
 
JorisWCommented:
Note that my above example is not ideal since it will fetch the entire document for each click.
You could make a second page which is also capable of adding favorites and returns nothing to little.
Also note that the above example also works if javascript is disabled, since it has the href to fall back onto
0
 
dwaynecharringtonCommented:
The following JavaScript requires jQuery to function, so give it a download.
http://jquery.com

// When a hyperlink with the id "favimage" is clicked
$("a#favimage").click(function()
{
 
// New date object
 HoldDate = new Date();
 
// Post to PHP script. With data inside { }'s
$.post("script.php", { fav: "thedatatobesent", date: HoldDate.getDate() + "/" },
 
// The function that is fired when the requested action is completed.
// Data now holds the data that the PHP script sent back.
function(data){
alert("Data Loaded: " + data);
});
 
 return false;
});

Open in new window

0
 
ShaneJonesAuthor Commented:
Hi there,

jQuery will not work as I am already using mootools,,,, declaring the jquery script breaks the gallery that is on the page.

Cheers
0
 
JorisWCommented:
You can run jquery in noConflict mode, this removes the window.$ which is the one conflicting with mootools.

You will then have to use jQuery('a#favimage') instead of $('a#favimage')
jQuery.noConflict();

Open in new window

0
 
ShaneJonesAuthor Commented:
Ok here is my code so far.

When I put the code that is in Dwayne's response a few points up it just kills the gallery.

http://test.shanedj.com/deborahtarr/gallery/ you can see the gallery there.

What I have now done is created a function that displays the image ID as an alert for the time being.

how now to get that into PHP as a variable to play with.

Thanks for you help so far.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Gallery of Work</title>
<link rel="stylesheet" href="../css/jd.gallery.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../css/main.css" type="text/css" />
<script src="../scripts/mootools.v1.11.js" type="text/javascript"></script>
<script src="../scripts/jd.gallery.js" type="text/javascript"></script>
<script src="../scripts/jd.gallery.set.js" type="text/javascript"></script>
<script src="../scripts/jquery.js" type="text/javascript"></script>
 
<script type="text/javascript">
  jQuery.noConflict();
	
	function startGallery() {
	var myGallery = new gallery($('myGallery'), {
	timed: false
	});
	}
	window.addEvent('domready', startGallery);
	
	function addTo(id){
	alert(id);
	
	}	
</script> 
 
</head>
 
<body>
<div id="myGallery">
    <div class="imageElement">
      <h4>Swans</h4>
      <p>Some Swans by the canal.</p>
<a href="javascript:addTo(1);" title="Favorite this image" class="open" rel="nofollow"></a>
      <img src="../images/brugges2006/1.jpg" class="full" />
    </div>
    <div class="imageElement">
      <h4>Castle</h4>
      <p>Orange lit castle.</p>
      <a href="javascript:addTo(2);" title="Favorite this image" class="open" rel="nofollow"></a>
      <img src="../images/brugges2006/2.jpg" class="full" />
    </div>
</div>
 
</body>
</html>

Open in new window

0
 
JorisWCommented:
If you use jquery:
function addTo(id) 
{
	 jQuery.post(".", { fav: id, date: new Date().getTime() }, 
		 function() 
		 {
		 	/* Optionally do something when request is complete */ 
		 }
	 );
}

Open in new window

0
 
ShaneJonesAuthor Commented:
Cool seems to be getting somewhere, am guessing that "." means the current page.

How can I call this info and echo it on the page?

<?php echo $_SESSION['fav'] ?>

doesn't seem to work?
0
 
JorisWCommented:
Yes, "." is the current page

You probably want $_REQUEST['fav'], that way it does not matter if you use get or post
0
 
ShaneJonesAuthor Commented:
Still not echoing it?

http://test.shanedj.com/deborahtarr/gallery/

Is there something else I am missing in the code?

<?php 
session_start();
 
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Gallery of Work - Deborah Tarr</title>
<link rel="stylesheet" href="../css/jd.gallery.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../css/main.css" type="text/css" />
<script src="../scripts/mootools.v1.11.js" type="text/javascript"></script>
<script src="../scripts/jd.gallery.js" type="text/javascript"></script>
<script src="../scripts/jd.gallery.set.js" type="text/javascript"></script>
<script src="../scripts/jquery.js" type="text/javascript"></script>
 
<script type="text/javascript">
  jQuery.noConflict();
	
	function startGallery() {
	var myGallery = new gallery($('myGallery'), {
	timed: false
	});
	}
	window.addEvent('domready', startGallery);
	
	function addTo(id){
	jQuery.post(".", { fav: id, date: new Date().getTime() }, 
         function() 
         {
            alert(id);
         }
         );
	}	
</script> 
 
</head>
 
<body>
 
<?php echo $_REQUEST['fav']; ?>
 
<div id="myGallery">
    <div class="imageElement">
      <h4>Swans</h4>
      <p>Some Swans by the canal.</p>
<a href="javascript:addTo(1);" title="Favorite this image" class="open" rel="nofollow"></a>
      <img src="../images/brugges2006/1.jpg" class="full" />
    </div>
    <div class="imageElement">
      <h4>Castle</h4>
      <p>Orange lit castle.</p>
      <a href="javascript:addTo(2);" title="Favorite this image" class="open" rel="nofollow"></a>
      <img src="../images/brugges2006/2.jpg" class="full" />
    </div>
</div>
 
</body>
</html>

Open in new window

0
 
JorisWCommented:
It is being echo'd just not where you think. This javascript loads the a second page in the background using a XMLHttpRequest.

If you have firefox you can install the firebug extension (http://getfirebug.com/), which allows you to see what happens in XMLHttpRequests

If i were you I would move the code that handles adding the favorites to a second page, and fill in the name of that page in your addTo function (instead of ".")
0
 
ShaneJonesAuthor Commented:
Yeah I use firebug, just seen that working. Clever tool that :)

Can it be echo'd on the page tho. or can I even add the word added anywhere?


0
 
JorisWCommented:
You would do that in the addTo function (where you had alert(id) in your previous snippet), since the page no longer reloads if you add a favorite because of the XHR.
0
 
ShaneJonesAuthor Commented:
Am going to close this question and restart a new one so as to distribute the points so far.


0
 
ShaneJonesAuthor Commented:
Thanks for your help so far, i will open another question for further help and include it in the JS section too this time.
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 8
  • 8
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now