Add Input Select Option Without Reloading the Page in Laravel



THIS IS FOR LARARVEL 5.x!!

There are times when you want to let the users of your site to add their own records in the dropdown. 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 option to the dropdown and then repopulate the items on  that dropdown 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 validations to the new record.

First Step: The route

You need to reference the model you are using.

use App\WaterSource;

Route::get('/profiles/create/waterSource',function(){

    $data = WaterSource::orderBy('description')->get();

    return Response::json($data);

});




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


Second Step: The Dropdown and the add button

<div class="form-group">

    <label>State

        <select name="waterSource" id="WaterSource" class="form-control input-sm">

            <option value=""></option>

            @foreach($waterSources as $waterSource)

                <option value="{{ $waterSource->id }}">{{ $waterSource->name}}</option>

            @endforeach

        </select>

    </label>

</div>




<a href="#" class="small" data-toggle="modal" tabindex="-1" data-target=".modal-illness"> Add</a>




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 modal


<div class="modal fade modal-waterSource" id="myModal-waterSource" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" data-backdrop="static">

    <div class="modal-dialog">

        <div class="modal-content">

            <div class="modal-header">

                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>

                <h4 class="modal-title">Add New Water Source</h4>

            </div>

            <div class="modal-body">

                {!! Form::open(['url' => 'water_sources','class'=>'myForm-waterSource']) !!}

                <div class="form-group">

                    {!! Form::text('description',null,['class'=>'input form-control','id'=>'modal-waterSource','autofocus'=>'autofocus']) !!}

                </div>

            </div>

            <div class="modal-footer">

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

                {!! Form::submit('Submit',['class'=>'btn btn-primary btn-sm']) !!}

            </div>

            {!! Form::close() !!}

        </div>

    </div>

</div>




The modal composed of a form that will submit and redirect to your route then to your controllers create function.


Fourth Step: The Script

Just below your modal add this javascript.

<script>



    $(document).on('submit', '.myForm-waterSource', function(e) {

        $.ajax({

            url: $(this).attr('action'),

            type: $(this).attr('method'),

            data: $(this).serialize(),

            success: function(html) {

                $.get('{{ url('profiles') }}/create/waterSource', function(data) {

                    console.log(data);

                    $.each(data, function(index,subCatObj){

                        if (!$('#waterSource option[value="'+subCatObj.id+'"]').length) {

                            $('#waterSource').append('<option value="'+subCatObj.id+'">'+subCatObj.description+'</option>');

                        }

                    });

                    $('#myModal-waterSource').modal('hide');

                    $('#modal-waterSource').val('');

                });

            }

        });

        e.preventDefault();

    });

</script>


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

Labels: