Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')}}.

like image 927
sujit prasad Avatar asked Feb 19 '15 06:02

sujit prasad


2 Answers

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);
        }
    });
    
like image 76
sunil sah Avatar answered Oct 07 '22 16:10

sunil sah


You made error in code ,please write it properly.

$.ajax({
    type    :"POST",
    url     :"http://localhost/laravel/public/form-data",
    dataType:"json",
    data    :{ data1:data },
    success :function(response){
    alert("thank u");
    }
});

Update

I just saw your Returning datatype is json , so use

 dataType:"json",

or

 dataType:"jsonp",
like image 44
Pratik Avatar answered Oct 07 '22 18:10

Pratik