Giovanni Riga Giovanni Riga - 1 year ago 61
Ajax Question

Laravel 5.3 Ajax - Retrieve data sent in the ajax request from the controller

index.html



<form id="my-form">
<select id="my-select">
<option value="1">Tom</option>
<option value="2">Jerry</option>
</select>
<input type="submit" value="send data!">
</form>




Controller.php



public function getValue(Request $request)
{
return User::find($request->input('select_id'));
}


ajax.js



$(function () {

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

var showUser = $('#show-user');

$('#my-form').on('submit', function () {

var select_id = $('#my-select').val();

$.ajax({
method: "POST",
url: "ajax",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {
"select_id": select_id
},
error: function (data) {
//something went wrong with the request
alert("Error");
},
success: function (data) {
inner = "";
data.forEach(function (el, i, array) {
inner += "<div>" + el.name + "</div>";
});
showUser.html(inner);
}
});
event.preventDefault();
});


});

web.php



Route::post('ajax','[email protected]');


Update:



@Mahdi Youseftabar -> Thanks for it, according to the documentation I should use input() to get the request!

Problem 1: Error: 500 (TokenMismatchException);

What I did?

Add meta to :

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


I set the headers:

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

$.ajax({
...
headers: {
'X-Auth-Token' : token
},
...
});


What I need to do?




  • Retrieve the id sent in the ajax request from the controller [SOLVED]

  • Validate the token by the ajax request** Error 505 (Problem 1) [SOLVED]

  • Return from the controller is Empty [SOLVED]

  • Output the Users into the
    <div class="showUser"></div>
    [SOLVED]



Github Documentation of my project:
(Many to many relationships - Laravel 5.3, Ajax)
https://github.com/39ro/StudentSchoolProject

Answer Source

your problem is in route :

Route:post('ajax','[email protected]');

you use post method in your jQuery but in route you define that route method 'get' ...

in this case when you request with ajax, laravel respond you a empty response

another issue is in getting your user_id from request, you should use this in your controller:

return User::find($request->input('user_id');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download