in my head tag, I declared this
<meta name="csrf-token" content="{{ csrf_token() }}" />
and then my script
$(document).ready(function(){
$.ajaxSetup({ headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } });
$.post("/employees", {id : "1"}, function(response){
if(response.success)
{
var branchName = $('#branchname').empty();
$.each(response.employees, function(){
$('<option/>', {
value:$(this).user_no,
text:$(this).firstname
}).appendTo(branchName);
});
}
}, 'json'); //end of json post request
}); //end of document ready
and my html select tag that used when displaying the json response
<select id="branchname"></select>
my route that use by the json post request
Route::post('employees', [
'as' => 'employees', 'uses' => 'mot@getemployee'
]);
and my controller that used in route.
public function getemployee(){
$branch_no = "1";
$employees = mot_users::where("branch_no", $branch_no)->lists('firstname','lastname', 'user_no');
return response()->json(['success' => true, 'employees' => $employees]);
}
Problem: Yes it did successfully response but seems the data is empty/undefined because my select box is empty yet occupied by several option tags like
<select id="branchname">
<option></option>
<option></option>
<option></option>
<option></option>
<option></option>
<option></option>
<option></option>
<option></option>
<option></option>
</select>
and I tried like
$.each(response.employees, function(){
alert($(this).user_no); //hoping to get the id that was on the json data response.
});
instead of
$.each(response.employees, function(){
$('<option/>', {
value:$(this).user_no,
text:$(this).firstname
}).appendTo(branchName);
});
but it gives me "undefined".
Questions: whats wrong with my code? am I missing something? why the select tag with an id branchname is empty? how can I pass the id post data key from route to my controller for querying stuff so that I dont have to manually set $branch_no variable instead use whats the json post request sent to the routes to controller?
PS: im newbie in laravel 5 so I'm just on the part on figuring things out. Any help, suggestions, recommendations, ideas, clues that could fix my issue would be greatly appreciated. Thank you.