kate_hudson kate_hudson - 2 months ago 5x
Ajax Question

Keeping select values across pages

I have a couple of routes

Route::get('/route_one', 'IndexController@index');
Route::get('/route_two', 'IndexController@index');

They call the same controller function because these pages need the same array of data. This function is as follows

public function index()
$user = Auth::user();
if( $user ) {
$fileData = $this->fillArrayWithFileNodes(new DirectoryIterator( public_path(). '/images'));
$currentPath= Route::getFacadeRoot()->current()->uri();

if(!empty($fileData)) {
return view('index', compact('fileData', 'currentPath'));
} else {
return view('auth.login');

Now the index view is pretty straight forward, but it does has this part

@if($currentPath == 'route_one')
@if($currentPath == 'route_two')

So depending on what route is called, a different sidebar is displayed. Now the sidebars essentially contain a load of select inputs like the following

<div class="col-lg-3">
<div class="form-group">
<select id="year" class="form-control">
<option value=""></option>
@foreach($fileData["route_one"] as $year => $products)
<option value="{{ $year }}">{{ $year }}</option>

Both sidebars have different selects. When select options are selected, an ajax call is made to display an image. This all works fine.

This is my problem. I have a link to get to route_one or route_two. As the page refreshes when the link is clicked, the selects are at their default state. What I would like to do somehow is keep the last state of the select inputs. I am not storing this data within a database which may be an issue?

Furthermore, route_two relies on the select options from route_one. So when route_two is selected, I need to pass it route_ones options.

What would be the best way to achieve what I am after?



Think what you are trying to accomplish here: remember the old input values.

You could send the form when clicking the link and flash the data in your controller or use JavaScript saving input values to the browser's storage.

Simple example using plain JavaScript

// Get all select-elements
var inputs = document.querySelectorAll('select');

// Loop through them
for (var i = 0; i < inputs.length; i++) {
    // Set the old input value
    inputs[i].value = localStorage.getItem(inputs[i].name);

    // Start listening changes
    inputs[i].addEventListener('change', store);

// The function to call when the value has changed
function store(event) {
    // Set the new value to the browser's storage
    localStorage.setItem(event.target.name, event.target.value);

In that example your form elements are required to have unique name attributes. Of course it can be switched out using e.g. id attribute.