php - Issue with sending model object in json response laravel 5.6.12
Laravel 5.6.12
I am trying to get database model
$data = \App\Data::all();
return response()->json(
["data" => $data]);
and sending it to JavaScript learned from there Documentation
Now I want to get specific data from model object. I received it by JavaScript(jQuery) ajax. On success I recieved it. But I have to convert it into string using JSON.Stringify() and when I try to display it give me this data
{"data":[{"id":1,"name":"Ibrahim","fatherName":"Ahmed","created_at":"2018-04-05 04:02:31","updated_at":"2018-04-05 04:02:31"},{"id":2,"name":"Haris","fatherName":"Shabir","created_at":"2018-04-05 04:02:31","updated_at":"2018-04-05 04:02:31"}]}
I just need to know what type data format return response()->json() and why I need it to convert it to string and how can I access the only all the names in details. There is two rows in database model and there can be more. I put the output format on the fiddle for to access all the names fiddle
Ajax
function ajax(event) {
var x = "";
event.preventDefault();
$.ajax({
type: "POST",
url: " {{ route('ajax') }}",
data: {_token: "{{ Session::token() }}"},
dataType: 'JSON',
success : function (data) {
if (data)
{
data2 = JSON.stringify(data);
$("#demo").html(data2); // this give above whole output
}
},
error: function (xhr,ajaxOp,errors) {
$("#demo").html(errors);
}
});
}
This is ajax
Answer
Solution:
If you want to get all of the users, you'll need to loop over the array;
e.g.
Using your example you could try;
You shouldn't need to stringify the data.