php - Get results from objects in jquery -
i have controller:
public function show(request $request) { if($request->ajax()) { $id=$request->get('id'); if($id) { $show=crud::where('id',$id)->get(); echo json_encode(array('status' => true, 'show'=>$show)); die; } } echo json_encode(false);die; }
and jquery:
$(document).on('click', '.show', function (e) { e.preventdefault(); var id = $(this).data('id'); $.ajax({ type: "post", url: "{{url('/crud/show')}}", data: {id:id}, success: function (data) { var res = $.parsejson(data); //console.log(res.show); if(res.status == true) { //console.log(res.show.name); var result = 'name:'+res.show.name+'<br>'+ 'phone:'+res.show.phone+'<br>'+ 'class:'+res.show.class+'<br>'+ 'address:'+res.show.address+'<br>'+ $('#result').html(result); } } }); });
res.show.name
, res.show.address
etc. not giving values. if use raw sql query there no problem. guess raw sql query gives result in array while eloquent method gives result in object. making difference?how should deal this? console.log(res.show);
gives if click on show class.
[object]0: object address: "maharishi" class: 123 id: 7 name: "maharjan" phone: "123456789" __proto__: object length: 1 __proto__: array[0]
while console.log(res.show.name);
displays undefined.
console.log(res.show.name);
displays undefined.
how console.log(res.show[0].name);
?
you calling crud::where('id',$id)->get();
gives collection of "crud" object id. collection serialized json array. so, first element of array first.
or better, since know design 1 object has id, crud::where('id',$id)->first();
can res.show.name
.
finally, controller this:
public function show(request $request) { $response = ['status' => false]; if ($request->ajax()) { if ($id = $request->id) { if ($show = crud::where('id', $id)->first()) // same crud::find($id); { $response = ['status' => true, 'show' => $show]; } } } return response()->json($response); }
(same functionality, more idiomatic framework)
Comments
Post a Comment