Search code examples
javascriptsynchronousonsubmit

How to change this function execution order


I have this search function , which should refresh the page first (clean what was in the page)and then show the results.

What happens is that the page shows the results first and then refreshs the page.


searchForm.addEventListener("submit" , function(event)
    {
        window.location.reload(); //should do this first
        event.preventDefault(); 
        searchedName.innerText = searchBar.value;  
        changeLogoImage(searchedName);
        giveCompanieSymbol(searchedName);
        TurnVisible(companyLogo);
        TurnVisible(overviewDataContainer);
        TurnVisible(separadoresAnalise);
        TurnVisible(personaliseParagrafo);
    }
)

I can't think of a easy/simple solution to do this without creating another function or separated events. Isn't there an easier way to say to this function :

"First reload the page , then show the results." ?

I thought this is what would happen If I place the reload() in the first line of the function but doesn't seems to be the case.


Solution

  • You can't refresh the page and then make modifications to it, because the environment in which your code was running (along with your code) has been torn down and discarded by the process of reloading the page.

    Instead, either:

    1. Modify the page in place rather than refreshing it.

      or

    2. Encode the search information in query string parameters and assign teh URL to window.location to load the new page, and read and apply those query string parameters on page load.

      or

    3. Use sessionStorage to store them temporarily and then, again, apply them on page load.

    #1 is a common approach these days. Given it's search information, #1 is also quite a normal way to do this.