mercredi 17 octobre 2018

How to validate onkeyup event without again and again sending post request to route in larravel

validate Activity function with Ajax code

$(document).on('keyup','#activity_name',function () {
            var error_activity = '';
            var activity = $('#activity_name').val();
            var _token = $('input[name="_token"]').val();
            $.ajax({
                type : 'post',
                url : '',
                data :{activity:activity, _token:_token},
                success:function (result) {
                    if(result == 'unique'){
                        $('#activity_status').html('<lable class="text-sucess" style="color: blue"></lable>');
                        $('#activity').removeClass('has-error');
                        $('#activity_btn').attr('disabled',false);
                    }
                    else
                    {
                        $('#activity_status').html('<lable class="text-danger">Try Another!</lable>');
                        $('#activity').addClass('has-error');
                        $('#activity_btn').attr('disabled','disabled');
                    }
                }
            });
        });

My input field and here he is always call an event Onkeyup when ever i enters a single word in my input field and on each word he is sending a post request.

<div class="form-group">
                <label for="checkbox">Group</label>
                <select class="form-control form-control-sm"  id="activitygroup" name="activitydeleverable">
                    <option>Select</option>
                    @foreach(App\Groups::all() as $group_name)
                        <option value=""></option>
                    @endforeach
                </select>      
            </div>
            <button type="submit" id="activity_btn" onclick="insertactivity()" class="btn btn-info">Insert</button>

here is my Controller Function

function checkactivity(Request $request){
    $data = Activities::whereName($request->activity)->first();
    if (!is_null($data)){
        echo 'not_unique';
    }
    else
    {
        echo 'unique';
    }
}

My code is work perfect, but i have a problem. On each single word my onkeyup Event Ajax send a post request to db and check data is available in db or not. but i have to stop this to doing again and again Post request. it's may do slow my system so i have to solve this please solve this logical issue i have to stop this Post requests or need only one post request. You can see no of request in image



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire