Laravel - Return 2 views in AJAX response

Viewed 734

I have a view with 2 @include directives which are subviews for updating data when AJAX call is executed. The firt @include is correctly updated in AJAX response but I need to return in the same call the second @include for updating data shown.

I'm following the approach of onchange event to update partial view as following, I believe the approach will be to return also the second partial view and loaded as following: $("#dashboardindicators").html(data);

Controller

if($request->ajax()){
                
    return view('pages.dashboard.dashboardindicators', compact('chart4_prop_null','chart4_progress','chart3_prop_null','chart3_progress',
    'chart2_prop_null','chart2_progress','chart1_prop_null','chart1_progress',
    'market_center_dropdown', 'mega_agent_dropdown', 'teams_dropdown'));

    

} else {
    return view('pages.dashboard.dashboard', compact('chart4_prop_null','chart4_progress','chart3_prop_null','chart3_progress',
                                            'chart2_prop_null','chart2_progress','chart1_prop_null','chart1_progress',
                                            'market_center_dropdown', 'mega_agent_dropdown', 'teams_dropdown'));
}

JS

<script>
    $(document).ready(function () {
    
    $('.dropdown_get').on("change", function(){

        KTApp.block("#dashboardindicators", {
                overlayColor: "#000000",
                type: "v2",
                state: "success",
                message: "Procesando..."
            }),
        
        $.ajax({
        url: "/dashboard",
        method: 'GET',
        data: {
            market_center_id: $("#kt_market_center_dropdown option:selected").val(),
            mega_agent_id: $("#kt_mega_agent_dropdown option:selected").val(),
            team_id: $("#kt_team_dropdown option:selected").val(),
        },
        success: function (data) {
            $("#dashboardindicators").html(data);
            setTimeout(function () {
                    KTApp.unblock("#kt_blockui_1_content")
                });
             
        }
        });
    });
});
</script>
1 Answers

If you need to return 2 views in an AJAX response, you can do that with the response()->json() method:

$dashboardIndicators = view('pages.dashboard.dashboardindicators', compact(...)->render();
$dashboard = view('pages.dashboard.dashboard', compact(...)->render();

return response()->json(['dashboardIndicators' => $dashboardIndicators, 'dashboard' => $dashboard]);

Then, in your success: function, access like so:

$("#dashboardindicators").html(data.dashboardIndicators);
$("#dashboard").html(data.dashboard);

Also, make sure to use the ->render() function to convert the view to HTML.

Related