sujit prasad sujit prasad - 1 year ago 160
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

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

<script src=""></script>

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

type :"POST",
url :"http://localhost/laravel/public/form-data",
data :{ data1:data },

success :function(response)
alert("thank u");

Here is my Controller to receive ajax request

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


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

Here is my Route


I also have tried to change the URL of ajax with just only

Answer Source

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');
        url: '/form-data/',
        type: 'POST',
        data: {_token: CSRF_TOKEN},
        dataType: 'JSON',
        success: function (data) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download