Use date without creating page loop

Asked

Viewed 29 times

-1

I have a page that makes queries by dates, with the date selected the page returns me the result, until then ok, but then the client requested to keep the date as a history so that he did not need to choose the same date every time.

The code I made was this:

$('#dataCons').on('blur', function() {
                var cod = $(this).val();
                window.location="admagendamento.php?dataEsc="+cod;
                sessionStorage.setItem("dataEsc", cod);                                      
            });

This is when I choose the date in the field, besides the search it still stores the date in the sessionStorage, but in a next page load when I check if there is already a date inside the sessionStorage, and if there is executed the search with that saved date the page enters in loop, see the code:

$(document).ready(function() {
            var dataEsc = sessionStorage.getItem("dataEsc");
            if (dataEsc){
                window.location="admagendamento.php?dataEsc="+dataEsc;    
            }

How do I stop the page from looping?

  • I believe that if you save this data in a cookie would be much nicer.

1 answer

0


Your code loops because you’re using window.location which, as the name suggests, changes the "location" of the window to a new address.

I don’t think it’s a good idea to use this method for this kind of operation. It would be more interesting to use Ajax to fill part of the page with the desired information, but it would force you to change some things on your page.

To solve this your problem just check whether dataEsc exists in the URL before checking the sessionStorage. Ex:


$(document).ready(function() {
    var params = (new URL(document.location)).searchParams;
    if(params.has("dataEsc") === false) {
        var dataEsc = sessionStorage.getItem("dataEsc");
        if (dataEsc){
            window.location="admagendamento.php?dataEsc="+dataEsc;    
        }
    }
(...)

ps: I did not test the code above, because I am on cell phone.

  • Yes it solved, I had not thought of that possibility, I thank

Browser other questions tagged

You are not signed in. Login or sign up in order to post.