How to support GET Url arguments on multiple pages using jQuery and PHP?

I have a site that uses a GET form so that the user can specify a zipcode and then provide sorted results by distance based on this record. If zipcode is not present, it simply displays all the results.

My code works great. The problem is when I go from page 1 to page. I am losing the query string.

For other technical reasons, I cannot use the POST method. In particular, I need to be able to save this request state in some way and check the URL of the requested page and repeat this query line if it is empty.

Any thoughts on how to do this? The site uses a lot of jQuery, but I'm not sure that jQuery has a way to remember this line across multiple pages. The site also uses PHP. I don't mind storing the results in a PHP session variable, and then somehow restoring the URL, but I was hoping this would be a little more straight forward. Thanks for your thoughts

blue

+4
source share
3 answers

I think the best option for such persistent data is to use a session. Your code checks two things: the GET value and the session value. We assume that both are present, you take the GET value. This allows the user to send 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 should reference the zip code for requests, etc., use the value in $zip . This way, you don't rely on the page to deal with zip values ​​- you store it on the server and use it anytime.

+2
source

You can try adding it to all the <a href> elements, but only the <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)); }); 

Ampersand needs to ensure that any query string data is separated from the new data, while '?' added if there is currently no query string. substring(1) used to remove the leading ? which is already displayed in location.search .

I just realized that this does not work if <a> doesn’t already ? but it should not be too difficult to fix.

+1
source

What is the code you use for pagination?

If I understand the problem correctly, you need to add the search query and zipcode to the URLs "Go to page 2", etc.

Simplified version:

 <a href="results.php?page=2&<?php echo 'query=' . rawurlencode($_GET['query']); if (isset($_GET['zip'])) echo '&zip=' . rawurlencode($_GET['zip']); ?>">Next page</a> 
0
source

Source: https://habr.com/ru/post/1343993/


All Articles