sklrboy sklrboy - 21 days ago 9
jQuery Question

Laravel 5 how to convert AJAX response JSON into PHP, so I can loop through it with foreach on the view?

I'm working on an ajax search function for my users table, and I've managed to get until I get back the content of the response json file, but I can't figure it out, how could I hand it's content over to the $users php array, so I could loop through it. My code in the following:
The JS:

$('.searchbar').keypress(function (e) {
if (e.which == 13) {
$.ajax({
dataType: "json",
url: '/results',
data: {keyword: $('.searchbar').value()},
success: function (result) {
console.log(result);
},
error: function(){
console.log("No results for " + data + ".");
}
});
}
});


The route:
Route::get('results', 'SearchesController@search');


The search function in SearchesController:

public function search(Request $request) {

$keyword = $request->get('keyword');

$users = \App\User::where("username", "LIKE","%$keyword%")
->orWhere("firstname", "LIKE", "%$keyword%")
->orWhere("lastname", "LIKE", "%$keyword%")
->orWhere("email", "LIKE", "%$keyword%")
->orWhere("phone", "LIKE", "%$keyword%")->get();

return \Response::json($users);

}


The view:

@foreach($users as $user)
<tr>
<td class='text-center'>{{$user->username}}</td>
<td class='text-center'>{{$user->firstname}}</td>
<td class='text-center'>{{$user->lastname}}</td>
<td class='text-center'>{{$user->email}}</td>
<td class='text-center'>{{$user->phone}}</td>
<td class='text-center'>{!! link_to_action('UsersController@edit', 'Edit', $user->id, ['class'=>'btn btn-warning', 'style'=>'margin-bottom:5px']); !!}
{!! Form::open(['action' => ['UsersController@destroy', $user->id], 'method' => 'DELETE']) !!}
{!! Form::submit('Delete', ['class'=>'btn btn-danger']) !!}
{!! Form::close() !!}</td>
</tr>
@endforeach


So shortly, the content of "\Response::json($users);" should end up on the view as $users. Or should I change my whole approach and find a solution to console.log everything with JS? Thanks in advance!

Answer

change

return \Response::json($users);

to

return view('results', array( 'users' => $users ));