my json post request has a data key named "id", now how im going to pass it from routes to my controller?
my json post request
$.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');
as you can see from my json post request i have put a key value name id
my routes
Route::post('employees', [
'as' => 'employees', 'uses' => 'mot@getemployee'
]);
and my controller
public function getemployee($id){
$employees = employees::where("branch_no", $id)->lists('firstname', 'user_no');
return response()->json(['success' => true, 'employees' => $employees]);
}
as you can see, I have an argument $id, it supposedly, its where the key value named id from the json post request will be put and be used from the query stuff.
Since you're using $.post
in your jQuery code, the {id: ...}
parameter passed as a POST data, which means that instead of having:
public function getemployee($id){
You should have:
public function getemployee() {
$id = (int)$_POST['id']; //notice that int casting
@KhanShahrukh has a good point. Consider using the following instead of the traditional POST variable:
<?php
namespace App\Http\Controllers;
use Request;
....
....
class ... extends ... {
public function ...() {
if(Request::ajax()) { //Prevent direct access
$id = Request::input('id;);
Regarding the second issue (which mentioned in the comment), $(this)
won't refer to the object. In order to access the object's properties, you should add parameters to the function()
in your $.each
function. ( Manual )
So instead of:
$.each(response.employees, function(){
$('<option/>', {
value:$(this).user_no,
text:$(this).firstname
You should have:
$.each(response.employees, function(firstname, user_no){
$('<option/>', {
value: user_no,
text: firstname
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.