GrahamMorbyDojo GrahamMorbyDojo - 28 days ago 9
Ajax Question

Laravel display AJAX call JSON response

Have some data returning from a AJAX call and cant get to output to screen on a live search page

Laravel Controller looks like

// Live Search
public function searching() {
$search_keyword = $_POST['search_keyword'];
$searchClients = DB::table('clients')->where('company', 'like', '%'.$search_keyword.'%')->get();
return response()->json($searchClients);

}


That works fine and data is coming back and looks like

0
:
{id: 58, company: "Havenkey Ltd", con: "2441", engaged: "n", industry: "", status: 27, location: 1444,…}
1
:
{id: 62, company: "V3 Recruitment Ltd", con: "", engaged: "n", industry: "", status: 27,…}


Front end is below with the search box and a a results div to display result sin

<div class="col-lg-8" style="padding-top: 30px;">
<i class="fa fa-dashboard"></i> <a href="{{URL::asset('/')}}">Dashboard</a> / Search Clients
<div class="col-md-12">
<br>
<div class="col-md-6 col-md-offset-3">
<form>
<div class="form-group">
{{ csrf_field() }}
<label for="search">Search</label>
<input type="text" class="search_keyword" id="search" name="search" class="form-control" placeholder="Enter Clients Name">
</div>
</form>

<div id="result">

</div>
</div>
</div>

</div>
<div class="col-lg-2" style="padding-top: 30px;">
@include('partials.notepad')
</div>


and JS looks like this

$(".search_keyword").keyup(function () {
//setup before functions
var typingTimer; //timer identifier
var doneTypingInterval = 5000; //time in ms, 5 second for example
var $input = $('#search');

//on keyup, start the countdown
$input.on('keyup', function () {
clearTimeout(typingTimer);
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});

//on keydown, clear the countdown
$input.on('keydown', function () {
clearTimeout(typingTimer);
});

//user is "finished typing," do something
function doneTyping () {
$.ajax({
type: "POST",
url: "/searching",
data: dataString,
cache: false,
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
success: function (data) {
if(data){
console.log('Here');
$('#result').html('');
$('#result').append('<select id="res"></select>');
$.each(data, function(i,val) {
$(document).find('#res').append(
$("<option>").text(val.company).val(val.id)
)
});
}else {
alert('im not working');
}
}
});
}
return false;
});


So all im trying to achieve here is outputting live search results which append the company name to a list which can be selected on click at some point

Answer Source

First of all, we need to initiate ajax call only when user is done with typing so it will avoid to initiate ajax call for each character typed in. So to achieve this mechanism,

//setup before functions
var typingTimer;                //timer identifier
var doneTypingInterval = 5000;  //time in ms, 5 second for example
var $input = $('#myInput');

//on keyup, start the countdown
$input.on('keyup', function () {
  clearTimeout(typingTimer);
  typingTimer = setTimeout(doneTyping, doneTypingInterval);
});

//on keydown, clear the countdown 
$input.on('keydown', function () {
  clearTimeout(typingTimer);
});

//user is "finished typing," do something
function doneTyping () {
  //here we will call the ajax function.
}

And there in your ajax call, change the success callback like mentioned below:

success: function (data) {
       if(data){
           console.log('Here');
           $('#result').html('');
           $('#result').append('<select id="res"></select>');
           $.each(data, function(i,val) {
                $(document).find('#res').append(
                $("<option>").text(val.company).val(val.id);
                });
           });
       }else {
           alert('im not working');
       }
}