dollar dollar - 3 months ago 19
PHP Question

How to read Json array in jquery in Laravel 5.2

I am using ajax-jquery to fetch multiple eloquent objects in laravel 5.2

This is what i am getting as response in jquery

{

"screens":
[{"screen_id":1,"screen_name":"Screen 1 ","screen_msg":"Hello","screen_status":"Active","cinema_id":1,"created_at":"2016-09-08 04:34:28","updated_at":"2016-09-08 04:34:28"}],

"showtime":
[{"show_id":6,"movie_id":1,"dimensional":"2D","cinema_id":1,"screen_id":1,"show_date":"2016-10-04","show_time":"00:57:00","show_status":"Active","created_at":"2016-09-08 12:21:06","updated_at":"2016-09-08 12:21:06"},
{"show_id":7,"movie_id":1,"dimensional":"2D","cinema_id":1,"screen_id":1,"show_date":"2016-10-04","show_time":"00:57:00","show_status":"Active","created_at":"2016-09-08 12:22:15","updated_at":"2016-09-08 12:22:15"}]

}


my controller function code

public function getscreen($id)
{
$screens=Movies_screen::where('cinema_id',$id)->get();
$showtime=Movies_showtimes::where('cinema_id',$id)->get();

return response()->json(['screens' => $screens, 'showtime' => $showtime]);
}


I am reading those json array in jquery as

$("#cinemahall").on("change click",function(){

var cinema_id=$("#cinemahall option:selected").val();
//ajax
$.get('/askspidy/admin/showtime/getscreen/' + cinema_id, function(data){

$("#screenname").empty();
$("#screenname").append('<option value=0>Select Screen</option>');

$.each(data,function(index,screenobj){
$("#screenname").append('<option value="' +screenobj.screens[0].screen_id + '">' +screenobj.screens[0].screen_name +'</option>');
});
});
});


In console i can see proper data without any error but i am unable to access each and every field of json response using

screenobj.screens[0].screen_name


Need help to figure out this issue.

Answer

Do data.screens[0].screen_name you don't need the loop

or

 $.each(data.screens,function(index,screenobj){
            $("#screenname").append('<option value="' +screenobj.screen_id + '">' +screenobj.screen_name +'</option>');
        });