sujit prasad sujit prasad - 2 months ago 22
Javascript Question

Using Ajax and returning json array in laravel 5

enter image description hereI am new to "AJAX" and I have been trying to send a request "ONSELECT" using "AJAX" and receive a "JSON" response in "laravel 5".

Here is my View

<select>
<option data-id="a" value="a">a</option>
<option data-id="b" value="b">b</option>
<option data-id="c" value="c">c</option>
</select>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>

<script type="text/javascript">
$('select').change(function(){
var data = $(this).children('option:selected').data('id');

$.ajax({
type :"POST",
url :"http://localhost/laravel/public/form-data",
dataType:"html",
data :{ data1:data },

success :function(response)
alert("thank u");
}),
});
</script>


Here is my Controller to receive ajax request

public function formdata(){
$data = Input::get('data1');

//somecodes

return Response::json(array(
'success' => true,
'data' => $data
));
}


Here is my Route

Route::post('form-data',array('as'=>'form-data','uses'=>'FormController@formdata'));


I also have tried to change the URL of ajax with just only
form-data
and
{{Url::route('form-data')}}
.

Answer

Laravel 5 uses csrf token validation for security reasons....try this...

  1. In routes.php

    route post('form-data', 'FormController@postform');
    
  2. In master layout file

    <meta name="csrf-token" content="{{ csrf_token() }}" />
    
  3. var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
    $.ajax({
        url: '/form-data/',
        type: 'POST',
        data: {_token: CSRF_TOKEN},
        dataType: 'JSON',
        success: function (data) {
            console.log(data);
        }
    });