Prakhar Prakhar - 4 months ago 67
PHP Question

laravel 5.2 valid ajax request

How can we check in Laravel 5.2 if a request is a valid ajax request. In codeigniter ,we could check it like $this->input->is_ajax_request(). Does, Laravel 5.2 has something similar?

Also, I would like to know that how can we validate a request for csrf token. Is it fine if I let my webpage render through the 'web' middleware generating a csrf token and then pass this token as ajax request parameter? Would Laravel take care of validating the token or is there an alternate way around this?

I have checked the laravel 5.2 documentation, and since this is the first time I am dealing with laravel framework, it seems like the documentation assumes that the reader already has a familiarity with earlier versions of the framework. To a new comer like me this is little overwhelming.

Thanks in advance. Please let me know if you need more inputs from me.

Prakhar

Answer

I think this may help you to undestand a very basic way of using AJAX with Laravel.

It's a really old piece of code, but it works jajajaja

Controller side:

/**
 * @param Request $request
 * @return \Illuminate\Http\JsonResponse
 */
public function getRamos(Request $request)
{
    $check = Ramo::find($request->input('ramo');
    $subramos = Subramo::where('ramo_id', $check->id)->get(['nombre_subramo']);
    if($request->ajax()){
        return response()->json([
            'subramos' => $subramos
        ]);
    }
}

In the front:

<script>
    $(document).ready(function(){
        $('#ramo').change(function(){
            var ramo, token, url, data;
            token = $('input[name=_token]').val();
            ramo = $('#ramo').val();
            url = '{{route('getRamos')}}';
            data = {ramo: ramo};
            $('#subramos').empty();
            $.ajax({
                url: url,
                headers: {'X-CSRF-TOKEN': token},
                data: data,
                type: 'POST',
                datatype: 'JSON',
                success: function (resp) {
                    $.each(resp.subramos, function (key, value) {
                        $('#subramos').append('<option>'+ value.nombre_subramo +'</option>');
                    });
                }
            });
        });
    });
</script>

Considering #ramo as a select input and in use of the styde/html package where the token is passed as a hidden input.

Comments