dollar dollar - 2 months ago 25
jQuery Question

how to read ajax response with multiple objects in laravel 5.2

I am trying to get the multiple eloquent objects through controller json response when drop down is changed.

enter image description here

When cinema hall is changed then it should return 2 objects fetched from 2 different tables.

controller 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);
}


my jquery ajax code

$("#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.screen_id + '">' +screenobj.screen_name +'</option>');
});
});
});


The above code works fine when single eloquent object is sent i.e $screens , but as you can see in code there is another object i.e $showtime and i need to send the same with that request and read it in my jquery ajax code.

I tried in controller

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

return response()->json($screens,$showtime);
}


and in jquery code

$.get('/askspidy/admin/showtime/getscreen/' + cinema_id, function(data,data2)


but none of the solution worked.

Answer

You can return an array with indexes pointing to the different collections:

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

In JSON, this will be translated to a Javascript object with two properties, 'screens' and 'showtime':

$.get('/askspidy/admin/showtime/getscreen/' + cinema_id, function(data) {
    console.log(data.screens);
    console.log(data.showtime);
});
Comments