Reputation: 377
I am a beginner in Javascript and Jquery and I am trying to get data from the server, access them and display them without reloading the page with Ajax and Laravel 5.
So here is what I do:
My controller:
public function get_media_details(){
$media_id = $_POST['media_id'];
$media_details = Media::find($media_id);
print_r ($media_details);
}
My JS function:
function show_media_detail(media_id){
$.ajax({
url: "get_media_details",
type:"POST",
data: { media_id: media_id },
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
success:function(data){
console.log(data);
},
error:function(){
console.log("No data returned");
}
});
}
And the result of console.log(data):
"App\Media Object
(
[table:protected] => media
[fillable:protected] => Array
(
[0] => name
[1] => feed_url
)
[connection:protected] =>
[primaryKey:protected] => id
[perPage:protected] => 15
[incrementing] => 1
[timestamps] => 1
[attributes:protected] => Array
(
[id] => 1
[name] => TechCrunch
[description] => Breaking technology news and analysis.
[link] => http://techcrunch.com/
[feed_url] => http://techcrunch.com/feed/
[thumbnail] => Rll0vnSkWk3bvTTWdthYzagXGnLHt9EHpU3Qe8XK
)
etc...
But know I am trying to access specific value of this object, like for example, the name of my media.
I tried many things and searched a lot, but I keep failing miserably... Any help would be greatly appreciated !
Thank you
Upvotes: 2
Views: 1270
Reputation: 4557
change this
print_r ($media_details);
to
return $media_details;
in js file
... success:function(data){
for (var x in data){
console.log(data.description); // should output description
}
....
Upvotes: 2