Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I maintain GET Url arguments across multiple pages with jQuery and PHP?

I have a site that uses a GET form to allow a user to specify a zipcode, and then provide sorted results by distance based on that entry. If no zipcode is present, then it simply displays all results.

My code works great. The problem is when I change from Page 1 to Page 2 I lose my query string.

For other technical reasons, I cannot use the POST method. Specifically I need to be able to save this query state somehow and check the url of the requested page, and the reappend that query string if it's empty.

Any thoughts on how to do this? The site uses a lot of jQuery, but I'm not sure if jQuery has a way to remember this string across multiple pages. The site uses PHP as well. I don't mind storing the results in a PHP session variable and then reconstructing the URL somehow, but I was hoping it would be a bit more straightforward than that. Thanks for your thoughts

Blue

like image 636
user658182 Avatar asked Oct 11 '22 12:10

user658182


2 Answers

I think the best option for this kind of persisting data is to use a session. Your code checks for two things, a GET value and a session value. We'll assume if both are present, you take the GET value. This allows the user to submit a new one and override the old one.

session_start();
$zip = '';
if($_GET['zip'])
{
    //validate zip as needed
    $zip = $_GET['zip'];
    $_SESSION['zip'] = $zip;
}
elseif($_SESSION['zip'])
{
    $zip = $_SESSION['zip'];
}
else
{
    //handle default case
}

Then anytime your PHP code needs to reference the zip code for queries, etc, use the value in $zip. This way you don't rely on the page itself to deal with the zip values - you store it serverside and use it any time you need it.

like image 193
Surreal Dreams Avatar answered Oct 18 '22 11:10

Surreal Dreams


You could try adding it to all <a href> elements, but then only <a> links will pass the query string to other pages. Anyway, you can do this:

$('a').each(function() {
    $(this).attr("href",
                 $(this).attr("href") + 
                 (location.search == '' ? '?' : '&') + 
                 location.search.substring(1));
});

The ampersand is to make sure that any query string data is separated from the new data, whilst the '?' is added if no query string exists at the moment. The substring(1) is used to remove the leading ? which already appears in location.search.

I just realised that this doesn't work if an <a> doesn't have a ? yet, but that shouldn't be too difficult to fix.

like image 39
pimvdb Avatar answered Oct 18 '22 10:10

pimvdb