5

I have this simple while loop which retrieves data from a mysql query and displays several links on my homepage.

I would like to avoid using the php get function and add query strings to my urls

I am thinking of using session variables but I need help and I'm pretty sure this can't be done.

When a visitor clicks a link from the several ones displayed by the while loop, that particular variable would be set in a session.

In my code, the session will always send the last var.

Can this be done?

    <? session_start(); // Start Session Variables

    $result = mysql_query("my query");

    while($slice = mysql_fetch_assoc($result)){
        $url = $slice['url'];
        $name  = $slice['name']; ?>

        <a href="<? echo $url; ?>"><? echo $name; ?></a>

    <? } 

    $_SESSION['name'] = $name; // Store session data  ?>
4
  • 1
    You can set session variables (session just works), however you need to decide which $name you want to set. As long as the user has not clicked any link you don't know, so I wonder how you want to solve this. What is the criteria of the click? Commented Dec 23, 2011 at 11:19
  • If he does not click any links maybe I could set up a default value. But that is not really important because all my links will be from that loop. So if he wanted to go to another page he would have to click one of the links. Ty for your reply Commented Dec 23, 2011 at 11:22
  • You wish to avoid "the php get function"? Commented Dec 26, 2011 at 13:35
  • Yes, I want to avoid query strings in my urls for seo purpose. And I cannot rewrite the urls cause the variables change all the time, so the urls would change more the 100 times a day which is very bad for seo Commented Dec 27, 2011 at 11:12

7 Answers 7

1
+150

What you wish to do can be done by using a javascript function which will make an AJAX request sending the clicked name to the server. The server side code will then store the required session variable

 <? 
     session_start(); // Start Session Variables

    $result = mysql_query("my query");
    $name = '';
    while($slice = mysql_fetch_assoc($result)){
        $url = $slice['url'];
        $name  = $slice['name']; ?>

        <a href="<? echo $url; ?>" onclick='setSession(<? echo $url;?>);'><? echo $name; ?></a>

    <? } 

Now the setSession will make an AJAX call passing the value obtained. This can be then saved as session url by a simple server side code

The javascript code to present on the same page as your page having links

<script type='text/javascript'>
    function getXMLHTTPRequest() {
    try {
    req = new XMLHttpRequest();
    } catch(err1) {
      try {
      req = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (err2) {
        try {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (err3) {
          req = false;
        }
      }
    }
    return req;
    }



      var http = getXMLHTTPRequest();
       function setSession(value) {
    var myurl = "session.php";  // to be present in the same folder
     var myurl1 = myurl;
      myRand = parseInt(Math.random()*999999999999999);
      var modurl = myurl1+"?rand="+myRand+"url"+value ; // this will set the url to be sent

      http.open("GET", modurl, true);
      http.onreadystatechange = useHttpResponse;
      http.send(null);
    }


    function useHttpResponse() {
       if (http.readyState == 4) {
        if(http.status == 200) {
          var mytext = http.responseText;
          // I dont think u will like to do any thing with the response
          // u can redirect the user to the req page (link clicked), once the session url has been setted
            }
         }
         else {
             // don't do anything until any result is obtained
            }
        } 
</script>

PHP server side code to be present to set the required url as session value

<?php
session_start();
if($_SESSION['url']!=""){
unset($_SESSION['url']);   
$_SESSION['url'] = $_REQUEST['url'];  
}
else {
$_SESSION['url'] = $_REQUEST['url'];  
}
?>
Sign up to request clarification or add additional context in comments.

5 Comments

Ty very much, this is really interesting, will set it to see if it works.
hmm.. Let me know if u face some problem somewhere
Can you please tell me how I can get the setSession value on the other page? Ty
setSession will be a javascript function making the AJAX request, i will edit my answer a bit for you
PHP code given has to present on the page session.php in the same folder
1

I don't think you can do what you are talking about in a simple fashion... The best way to pass the data is in the url, to be retrieved with $_GET.

You could use your while loop to echo individual forms, and set a hidden variable in each form to the value of your $name. Then you'd have to output a link that called a javascript function to submit that particular form. On the next page, you'd be able to grab the value for $name from the $_POST variable that was submitted by the hidden value in the form from the previous page...

But that would require javascript to function, and would just be an odd way to go about it.

something like:

echo '<form action="'.$url.'" method="post" name="myform1" id="myform1">';
echo '<input type="hidden" name="value" id="value" value ="'.$name.'">';
echo '</form>';
echo '<a onclick="document.forms['myform1'].submit();">'.$name.'</a>;

then on the next page ($url), you would get the value of the hidden variable using php, like so:

$name = $_POST['value'];

Again though, an odd way to go about it...

1 Comment

Interesting:) ty very much. I know the simple way is through the url, but I am using wordpress and have pretty permalinks, putting a variable that would change all the time would destroy my SEO
1

I can not tell you how you can solve your problem, because it's not clear from your question how the script will determine if a specific link has been clicked.

However, I see a flaw in your code. You're setting the session variable always to the last entry after the loop:

 $_SESSION['name'] = $name; // Store session data

$name contains the name of the last mysql result row. This is obviously not what you want to do.

If you provide more information/code in your question how you can determine that a specific link has been clicked, it should be possible to show you how you can set the session variable properly.

2 Comments

That is the problem :(, i don;t know how to determine that a specific link has been clicked. Ty
All the pages you have, are they generated in the same PHP file (have one entry point in PHP) or are they across multiple PHP files? I ask because you can set the session variable when the link has been clicked and the PHP get's invoked. In the menu you would only need to read it out (not set it). If you can add to your question how you organize the pages, this should be possible to answer.
0

Declare name before while loop

<? session_start(); // Start Session Variables

$result = mysql_query("my query");
$name = '';
while($slice = mysql_fetch_assoc($result)){
    $url = $slice['url'];
    $name  = $slice['name']; ?>

    <a href="<? echo $url; ?>"><? echo $name; ?></a>

<? } 

$_SESSION['name'] = $name; // Store session data  ?>

now the last values is accessible in name.

Comments

0

So you want to store a value in the session scope when a user clicks a link. How you solve this should depend on what should happen when the user clicks. Are the clicks causing navigation and a new get request, or is it simply registering the name value in the session?

If the information is only needed on the client, you should consider using sessionStorage. https://developer.mozilla.org/en/DOM/Storage#sessionStorage

Using jQuery you could set a value to sessionStorage like this:

$('a').click(function(){
  sessionStorage.setItem('name', $(this).attr('data-name');
});

...and access it later on:

sessionStorage.getItem('name');

Keep in mind that sessionStorage is not supported by older browsers. If older browsers are important, you could use cookies instead. Cookies are sent to the server with each request, so if you set it with javascript on the click event, the value will be included in the next request, thus you can read it form the $_COOKIE array.

document.cookie = 'name=' + $(this).attr('data-name');

$value = $_COOKIE['name'];

You could fallback for older browsers by using feature detection:

if(sessionStorage){ /* do the session storage part */ }
else{ /* do the cookie part :) */ }

If you need to send the value to the server immediately you should consider using an ajax request, like Prashant Singh mentions in his answer.

My axamples use custom data attributes. I'm not sure about the content of your name values, and it's not clear how your markup looks like. You could use the name attribute if the names from mysql fits the attrbute semantically. Alternatively you could use the rel attribute, if the name describes a relation between the list and the target of the links.

Comments

0

For this you need two files

  1. index.php or any other file you are using to display links.

  2. set-session.php or any other file where you set your session variable.

    php code on index.php file will be :

    <?php session_start();
    $result = mysql_query("my query");
    while($slice = mysql_fetch_assoc($result)){
    $url = $slice['url'];
    $name  = $slice['name']; ?>
    
    <a class="myUrl" href="<?php echo $url; ?>"><?php echo $name; ?></a>
    <?php } ?>
    

jQuery code on your index.php file

$("a.myUrl").click(function()
{
    // Get the name from the link
    var linkName = $(this).text();

    // Send Ajax request to set-session.php, 
    // with linkName set as "name" in the POST data
    $.post("/set-session.php", {"name": linkName});
});

php code on your set-session.php file will be :

<?php  $_SESSION['name'] = $_POST['name']; // Store session data  ?>        

2 Comments

Ty very much, this is really interesting, will test to see if it works.
you can also use jquery ajax method for sending data to set-session.php file code $.ajax({ type: "POST", url: "set-session.php", data: "name="+linkName, success: function(html){ $("#results").append(html); } });
0

Using cookie is the cheapest/easiest way to achieve what you need -in my opinion.
Just set a cookie to the url of the link clicked; you can then retrieve it on the destination page.
But that doesn't answer this question: Why do you need to know the URL being clicked on? Once the user clicks on the link, they should automatically be taken to the page being referenced. And once on the page, you can obtain the URL of the page through the global $_SERVER[REQUEST_URI] variable. Unless it's absolutely needed, I would suggest saving your server memory for other features.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.