I am trying to perform an Ajax request from view to a controller which returns JSON Data. Everything is working fine however the Ajax response is too slow.
This is my Ajax Request in view:
$(document).on('keyup', '#search', function () {
$("#phoneBody > tr").remove();
var query = $(this).val().toLowerCase();
var expression = new RegExp(query, "i");
$.getJSON("phonetest/" + query, function (data) {
$.each(data, function (key, value) {
if (value.name.search(expression) != -1 ||
value.extn.search(expression) != -1 ||
value.mobile.search(expression) != -1 ||
value.dept.search(expression) != -1 ||
value.desig.search(expression) != -1 ||
value.emp_cd.search(expression) != -1)
{
$('#phoneBody').append('<tr><td class="name">' + value.name +
'</td><td class="extn">' + value.extn + '</td><td>' +
value.email + '</td><td>' + value.voip + '</td><td>' +
value.mobile + '</td><td>' + value.floor + '</td><td>' +
value.dept + '</td><td>' + value.desig + '</td></tr>');
}
});
});
});
This is my controller method:
public function phonetest(Request $request)
{
if ($request->ajax()) {
$crawler = Goutte::request('GET', "http://1.1.1.1/test.NSF/names?OpenView&count=2000");
$emp_arr = $crawler->filter('tr')->each(function ($node) {
$rec['name'] = $node->filter('a')->eq(0)->text();
$rec['extn'] = $node->filter('td')->eq(1)->text();
$rec['voip'] = $node->filter('td')->eq(2)->text();
$rec['mobile'] = $node->filter('td')->eq(3)->text();
$rec['floor'] = $node->filter('td')->eq(4)->text();
$rec['dept'] = $node->filter('td')->eq(5)->text();
$rec['desig'] = $node->filter('td')->eq(6)->text();
$rec['emp_cd'] = $node->filter('td')->eq(7)->text();
$email = DB::table('employee1')
->where('emp1_code', $rec['emp_cd'])
->pluck('emp1_email_addr')
->first();
$rec['email'] = strtolower($email);
//dd($rec);
return $rec;
});
$emp_arr = array_values(array_filter($emp_arr));
return json_encode($emp_arr);
}
}
Everything works fine. However, the response is too slow. It takes literally 1 second for each character I type. How can I improve the same?
One approach would be to create the initial array while the view loads for the first time and then make Ajax requests to the array subsequently.
Solved
I put the JSON in session while page load. Subsequent Ajax requests are served from this JSON stored in Session. This is working as of now and Ajax responses are superfast. Will monitor the performance over time in case JSON becomes big in size.