php - pass a data key value from a json post request to routes to controller -
my json post request has data key named "id", how im going pass routes 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 can see json post request have put key value name id
my routes
route::post('employees', [ 'as' => 'employees', 'uses' => 'mot@getemployee' ]); and controller
public function getemployee($id){ $employees = employees::where("branch_no", $id)->lists('firstname', 'user_no'); return response()->json(['success' => true, 'employees' => $employees]); } as can see, have argument $id, supposedly, key value named id json post request put , used query stuff.
since you're using $.post in jquery code, {id: ...} parameter passed post data, means instead of having:
public function getemployee($id){ you should have:
public function getemployee() { $id = (int)$_post['id']; //notice int casting @khanshahrukh has point. consider using following instead of 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 second issue (which mentioned in comment), $(this) won't refer object. in order access object's properties, should add parameters function() in $.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
Comments
Post a Comment