kate_hudson kate_hudson - 3 months ago 9
Ajax Question

Display result of search within view

I have a page where I display all my clients. It uses paginate and only displays 16 clients per page. As such I have provided realtime search functionality.

When a search is perform, the option selected from the results triggers the following

select: function (event, ui) {
$.ajax({
url: "/returnClient",
type: "GET",
datatype: "html",
data: {
value : ui.item.value
},
success: function(data) {
$('.container').fadeOut().html(data.html).fadeIn();
}
});
}


That essentially calls the following function

public function returnClient(Request $request)
{
if($request->ajax()){
$selectedClient = $request->input('value');
$client = Client::where('clientName', $selectedClient)->first();

$html = View::make('clients.search', $client)->render();
return Response::json(array('html' => $html));
}
}


If I output the client variable above, I can see all the details for this particular client. This is then being passed to the partial clients.search.
Within clients.search, if I do

{{dd($client)}}


I get Undefined variable: client. Why does it not get the parsed Object within the view?

Many thanks

Answer

The issue is that you are improperly passing $client to the view. The Views documentation shows how to properly pass data via an associative array. The API docs confirm that an array is what is expected.

Do this instead:

public function returnClient(Request $request)
{
    if($request->ajax()){
        $selectedClient = $request->input('value');
        $client = Client::where('clientName', $selectedClient)->first();

        $html = View::make('clients.search', ['client' => $client])->render();
        return Response::json(array('html' => $html));
    }
}

Also, as a point of habit you may want to consider using dump() instead of dd().

Comments