I 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')}}
.
Laravel 5 uses csrf token validation for security reasons....try this...
In routes.php
route post('form-data', 'FormController@postform');
In master layout file
<meta name="csrf-token" content="{{ csrf_token() }}" />
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);
}
});
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",
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With