Add Select Option, Without Reloading the Page in Laravel

THIS IS FOR LARARVEL 5.x!!

There are times when you want to let the users to add their own records in the database and display it in your dropdown select option.

You can have another menu for adding items specific to that dropdown. But what if you have plenty of inputs and you came up with that dropdown and realizes that you haven’t added the option you want to select. Well you can add it on that separate page but you have to re-type all those things you already encoded. Well that’s kind of tedious to do.

As a solution, why not letting the user add dropdown select option and then repopulate the items in  dropdown select option without reloading the entire page. By doing such thing will lessen the burden of the user to retype all inputs before it.

Note: this tutorial doesn’t cover up any validation to the new record.

First Step: The route

You need to reference the model you are using.

We create a GET route to retrieve all data and return it as Json data object.

Second Step: The dropdown select option and the add button

Since you don’t need to go to separate page to add new item, you can add a button than will open a modal. In this example I used bootstrap modal.

Third Step: the Twitter bootstrap modal

Add Select Option Without Reloading the Page in Laravel

The modal composed of a form that will submit, and redirect to your route then to your controller’s create function.

Fourth Step: The Script

Just below your modal code add this JavaScript.

The script will submit the form without reloading the page. It will go to the route that we created, then the route return a Json data object, and this script will repopulate the dropdown select option with the newly created items. Pretty cool.

 

Sharing is caring!