nameless nameless - 23 days ago 9
Javascript Question

PHP Javascript Change Browser Back Button behaviour Laravel

I know there are various threads that ask for nearly the same but none of them seems to really satisfy my needs....

On my site, I implemeneted a search form. A simple form with an input field, called

searchQuery
and a submit button. The form is sent with POST method.
I'm using Laravel btw.. The search result are then loaded into a view from the controller. Those are shown in a table. Now comes the interesting part: The found elements are clickable and you get on a page with more details about that element. Then the problem comes: When I now click the browsers back button or my back button on the mouse, I get a window asking to send the form information again and I have to confirm that.

This is not what I want, I want to just get back to the search results I had before....

Now I read a lot, but am still not knowing, how to do that.

I read before
onbeforeunload
where you can display a message, but thats not useful for me (I want to get back to the search results)...

So there are some alternatives that would be possible (if technically possible):


  1. just prevent the dialog asking to submit the information again and just submit it again without asking for

  2. Somehow go back in the history to the page before (cached maybe or something similiar, search results won't change in that time)

  3. if I wanted to, I could include the search them in the url like
    http://servername/search/searchquery
    , then pass this searchquery into the deatil view and have a button to go to that url that then does the search again or something like that. Then you could (maybe) override the browsers back button to "press" that button instead of going back in history...



Is one of these options possible and if yes how? Or is there any other way you can advise?

Answer

As per your comment in the question above, you can do it like this:

First of all your form should be like:

<form action="/search" method="GET">
    <input type="text" name="searchQuery" value="Type keywords here...">
    <input type="Submit" value="Search">
</form>

Then after submitting your form, the route / url would be like this:

http://localhost:8000/search?searchQuery=any_search_keyword
Route::get('search', 'SearchController@handleSearch'); // Laravel route

And you can handle your search in your controller like this:

function handleSearch() {
    $searchQuery = request()->get('searchQuery');
    // ... Handle your search here ...
}

In this way you can use GET method to handle searches, this also prevents the unnecessary submission dialog over and over again on going back and forth...

As per my understanding this would be the solution you're looking for

Comments