Search code examples
javascriptphpajaxlaravelview

How can I return view and pass in data in Laravel with Ajax?


I have an issue with my Ajax function which is supposed to call a Laravel view with $paginatedResults data which is returns from another function. For some reason it returns error 500. I know for a fact that $paginatedResults returns the right data as if I var_dump it's correct.

public function ajaxSearch(Request $request)
{
    $data = $request->input('searchVal');
    $pageNr = $request->input('pageNr');
    $dataType = $request->input('dataType');
    $paginatedResults = $this->paginateTypeResults($data, $pageNr, $filetype);

    $loadData = view('search.searchresults')->with($paginatedResults)->render();
    echo response()->json($loadData);
}

Solution

  • This is json response

    return response()->json([
       'html' => view('search.searchresults', compact('paginatedResults'))->render()
    ]);
    

    After success

    $.ajax({
       //
       dataType: 'json',
       success: function(response) {
          $('.//here').html(response.html)
       }
    })