Search code examples
javascriptjqueryajaxlaravel-5jquery-form-validator

Form validation and all subsequent code doesn't execute


I have an update form,that i call inside a modal on my main page,(with an onclick event,the click triggers a call with xmlhttprequest for the edit page containing the form with the stored data values). The thing is,everything works fines,the update works,post works,retrieving data in the first place works,except for the form validation,and ajax use to post the data. Please notice that on my main page,i have a create call,that creates a new instance,and it works just fine,with the form validation and the ajax post,so it can't be some required jQuery or any other script.

This is my form:

<form id="eventFormUpdate" method="POST" class="form-horizontal" action="Event/{{$event->id}}/Update">
    <input type="hidden" name="_method" value="PATCH" id="hidden-update">
    <div class="form-group">
        <label class="col-xs-3 control-label">Nom</label>
        <div class="col-xs-5">
            <input type="text" class="form-control" name="nameUpdate" value="{{$event->name}}"/>
        </div>
    </div>

    <div class="form-group">
        <label class="col-xs-3 control-label">Date de début</label>
        <div class="col-xs-5 dateContainer">
            <div class="input-group input-append date" id="startDatePickerUpdate">
                <input type="text" class="form-control" name="starting_dateUpdate" value="{{$event->starting_date}}"/>
                <span class="input-group-addon add-on"><span class="glyphicon glyphicon-calendar"></span></span>
            </div>
        </div>
    </div>

    <div class="form-group">
        <label class="col-xs-3 control-label">Date de fin</label>
        <div class="col-xs-5 dateContainer">
            <div class="input-group input-append date" id="endDatePickerUpdate">
                <input type="text" class="form-control" name="ending_dateUpdate" value="{{$event->ending_date}}"/>
                <span class="input-group-addon add-on"><span class="glyphicon glyphicon-calendar"></span></span>
            </div>
        </div>
    </div>

    <div class="form-group">
        <label class="col-xs-3 control-label">Assigné à</label>
        <div class="col-xs-5 selectContainer">
            <select name="assigned_toUpdate" class="form-control">
                <option value="4" selected >First</option> <!--fix this by checking if is the selected data or not-->
            </select>
        </div>
    </div>

    <div class="form-group">
        <label class="col-xs-3 control-label">Description</label>
        <div class="col-xs-5">
            <textarea id="descUpdate" class="form-control" name="descriptionUpdate" placeholder="Veuillez entrer une description">{{$event->description}}</textarea>
        </div>
    </div>

    <div class="form-group">
        <div class="col-xs-5 col-xs-offset-3">
            <button type="submit" class="btn btn-default" id="update-event-submit">valider</button>
        </div>
    </div>
</form>

And here is my script that handles the form validation and the ajax posting

<!-- event update script -->
<script>
$(document).ready(function() {
    $('#startDatePickerUpdate')
            .datepicker({
                format: 'yyyy/mm/dd'
            })
            .on('changeDate', function(e) {
                // Revalidate the start date field
                $('#eventFormUpdate').formValidation('revalidateField', 'starting_dateUpdate');
            });

    $('#endDatePickerUpdate')
            .datepicker({
                format: 'yyyy/mm/dd'
            })
            .on('changeDate', function(e) {
                $('#eventFormUpdate').formValidation('revalidateField', 'ending_dateUpdate');
            })
            .find('[name="assigned_toUpdate"]')
            .selectpicker()
            .change(function(e) {
                /* Revalidate the pick when it is changed */
                $('#eventFormUpdate').formValidation('revalidateField', 'assigned_toUpdate');
            })
            .end();

    $('#eventFormUpdate')
            .formValidation({
                framework: 'bootstrap',
                icon: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    nameUpdate: {
                        validators: {
                            notEmpty: {
                                message: 'Le nom est obligatoire.'
                            }
                        }
                    },
                    starting_dateUpdate: {
                        validators: {
                            notEmpty: {
                                message: 'La date de début est obligatoire.'
                            },
                            date: {
                                format: 'YYYY/MM/DD',
                                min: new Date(new Date().setDate(new Date().getDate()-1)),
                                max: 'ending_date',
                                message: 'La date de début est non valide.'
                            }
                        }
                    },
                    ending_dateUpdate: {
                        validators: {
                            notEmpty: {
                                message: 'La date est oligatoire.'
                            },
                            date: {
                                format: 'YYYY/MM/DD',
                                min: 'starting_date',
                                message: 'La date de fin est non valide.'
                            }
                        }
                    },
                    descriptionUpdate: {
                        validators: {
                            notEmpty: {
                                message: 'La description est obligatoire.'
                            }
                        }
                    },
                    assigned_toUpdate: {
                        validators: {
                            notEmpty: {
                                message: 'Veuillez séléctionner un utilisateur.'
                            }
                        }
                    }
                }
            })
            .on('success.field.fv', function(e, data) {
                if (data.field === 'starting_dateUpdate' && !data.fv.isValidField('ending_dateUpdate')) {
                    // We need to revalidate the end date
                    data.fv.revalidateField('ending_dateUpdate');
                }

                if (data.field === 'ending_dateUpdate' && !data.fv.isValidField('starting_dateUpdate')) {
                    // We need to revalidate the start date
                    data.fv.revalidateField('starting_dateUpdate');
                }
            })

            .submit(function(){
                return false;
            })

            .submit(function(){
                console.log('gonnastartsub');
                var $form = $("#eventFormUpdate"),
                        url = $form.attr('action');
                console.log('got vars');
                $.post(url, $form.serialize()).done(function () {
                    console.log('am in');
                    $("#modal-closeUpdate").click();
                    console.log('posted');
                });
            });
});
$("#descUpdate")
        .focus(function() {
            if (this.value === this.defaultValue) {
                this.value = '';
            }
        })
        .blur(function() {
            if (this.value === '') {
                this.value = this.defaultValue;
            }
        });

Update

This is my controller

public function update(Request $request,$id)
{
    $event = event::find($id);

    $event->name = $request->name;
    $event->description = $request->description;
    $event->starting_date = $request->starting_date;
    $event->ending_date = $request->ending_date;
    $event->assigned_to = $request->assigned_to;
    $event->save();

}

And this My routes call:

    Route::patch('Event/{eventID}/Update', 'EventsController@update');

One last thing,at first the script was on my main page,and it didn't work so i tried to put it in in the called page with xmlhttprequest,and still doesn't work. The only thing i can think of is,when i call the new page(the form to edit and update data) the script is already loaded in the main page,so it doesn't find the ids of the elements to handle,that's why it does not work,or at least this is the only reason i could find . Any suggestions please?


Solution

  • Well first of all you have an error in your datepickers min and max,they don't match the field names you have set,set them to this

     max: 'ending_dateUpdate'
     min: 'starting_dateUpdate'
    

    Second,the field names in your form,don't match those on your controller page,so it can't really update if it can't find the data,this should be your controller page:

    public function update(Request $request,$id)
    {
        $event = event::find($id);
    
        $event->name = $request->nameUpdate;
        $event->description = $request->descriptionUpdate;
        $event->starting_date = $request->starting_dateUpdate;
        $event->ending_date = $request->ending_dateUpdate;
        $event->assigned_to = $request->assigned_toUpdate;
        $event->save();
    
    }
    

    Hope it helps .