Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ajax in laravel 5.3

I am new to Laravel and am using Laravel 5.3. I want to make a text field where it will automatically suggest some data and when I select a data it will add it to an array. I want to send that array to a controller for further use. For this the

view file is as follows:

<head>
    <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
    <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <script>
        $(document).ready(function() {
            var members = {!!  json_encode($member)  !!};
            console.log(members);
            var arr = [];
            $("#tags").autocomplete({
                source: members,
                select: function (event, ui) {
                    arr.push(ui);
                    console.log(arr);
                }
            });
            $("#submit").click(function(event){
                $.ajax({
                    type: "POST",
                    url: '/storeresearch',
                    data: {selectedMembers: arr},
                    success: function( msg ) {
                        console.log(msg);
                    }
                });
            });
        });
        </script>
</head>
<body>
<form id="hu" action="/storeresearch" method="POST">
    {!! csrf_field() !!}
    <label>Research Author</label>
    <input type="text" id="tags" name="researchsupervisor_1" value="">
    <input type="submit" name="submit" id="submit" class="btn btn-primary" value="Add">
</form>
</body>

My Controller file is as follows:

public function store(Request $request){
        if($request->ajax())
        {
            $mem = $request->all();
            return response()->json($mem,200) ;
        }
        else{
            return "not found";
        } 

And web.php is as followings:

Route::post('/storeresearch','ResearchController@store');

But it seems that there is no ajax call happening. In the controller it always enters the else section. What is the problem can anyone help?

like image 534
Mutasim Fuad Avatar asked Jan 04 '23 13:01

Mutasim Fuad


1 Answers

Your code mostly looks good. But you are missing to send a csrf token with AJAX call as you are using POST request.

You can send csrf token with AJAX call in this way:

<meta name="csrf-token" content="{{ csrf_token() }}">

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

More info: https://laravel.com/docs/5.3/csrf#csrf-x-csrf-token

When you hit the button, does it really fires an AJAX call? Please check that on network tab of browser.

like image 160
Parth Vora Avatar answered Jan 07 '23 17:01

Parth Vora