Search bar - Add content Dynamicly with Ajax and JQuery - javascript

I'm trying to make a search bar which is loading dynamicly content.
However I wish the real content loading start after the user end typing.
I tried this version but it does not work because it does not take into count each event "keyup".
let old_search = ""
let search = ""
$("#search_input").on('keyup paste',function(){
$("#loader_active").show()
$('#videos').empty()
let old_search = $("#recherche").val()
setTimeout(function (){
search = $("#search_input").val()
console.log(old_search + ">" + search)
if (search == old_search){
console.log("loading")
start = 0;
limit = 20;
load(search, start, limit);
start += limit;
}
}, 1000);
});
function load(search, start=0, limit=20) {
$("#loader_active").show()
let form_data = new FormData();
form_data.append('search', search);
form_data.append('start', start);
form_data.append('limit', limit);
$.ajax({
url: "http://website.com/ajax/videos.php",
contentType: false,
dataType: "json",
processData: false,
cache: false,
data: form_data,
type: 'POST',
success: function (data) {
$(data).each(function(index, value) {
showVideo(value) // show video creates divs with jquery containing the data from the json received by the ajax call
})
$("#loader_active").hide()
}
})
}
Does any body know any solution ?

What you can do is to make your function reset a trigger that will fire after x amount of time. Something like:
function myCoolFunction(myParameters) {
//Clear the timeout every time this happens
clearTimeout(window.myTimeout);
//Create a new timeout
window.myTimeout = setTimeout(function() {
//Do Something after 1 second
}, 1000);
}
$(".selector").on('keyup paste', function (){
myCoolFunction(myParameters);
});
This will execute 1 second after the last 'keyup/paste'. :D

Related

Upon success response with data from Ajax call, process additional function as well

I am trying to call function upon successful response from ajax call.
Here both functions:
function waggle() {
var element = $(this);
var tmpClass = element.attr('class');
element.removeClass();
setTimeout(function() {
element.offsetWidth = element.offsetWidth;
element.addClass(tmpClass).addClass('start-now');
}, 10);
}
function auto_load(){
$.ajax({
type: 'POST',
data: {room_id:'$r_room_id',site_id:'$r_site_id'},
url: 'cart_counter.php',
success: function(data){
$('#cart_buble').html(data);
waggle();
}
});
}
This does update #cart_buble div as expected with the number in the cart however doesn't execute waggle function which is responsible for calling css transition effect.
Both functions are working fine seperately.
I think this variable is the problem here.
This kind of function declaration can change the data stored in this variable up to where the function is executed.
Try this way
function waggle() {
var element = $(...); // <--- Query your element instead of using `this`
var tmpClass = element.attr('class');
element.removeClass();
setTimeout(function() {
element.offsetWidth = element.offsetWidth;
element.addClass(tmpClass).addClass('start-now');
}, 10);
}
function auto_load(){
$.ajax({
type: 'POST',
data: {room_id:'$r_room_id',site_id:'$r_site_id'},
url: 'cart_counter.php',
success: function(data){
$('#cart_buble').html(data);
waggle();
}
});
}

Javascript, make ajax call after 3 seconds

I have a working javascript block that basically takes user input, and upon each keystroke makes an Ajax POST call.
This works perfectly but I'd like to change it to only fire the ajax 3 seconds after the user starts typing, as opposed to every keystroke. Ideally I'd like to fire it after 3 seconds and if they start typing again it would start over, but the initial delay is most important.
I tried to do a set interval around it but it's didn't make the ajax call, so I'm wondering if there's different approach I need to take.
how can I make this ajax only call 3 seconds after typing in the input starts?
$('#productInput').on('input', function() {
let _this = $(this);
let optSelector = `option[value='${_this.val()}']`;
if (_this.val() === '') {
return;
} else if ($('#returnedProducts').find(optSelector).length) {
//html stuff
} else {
const searchResult = $(this).val();
$.ajax({ url: '/account/autocomplete',
data: {
search_result:searchResult
},
"_token": "{{ csrf_token() }}",
type: "POST",
success: function (response) {
$("#returnedProducts").empty();
var result = response.hits.hits;
for (let i = 0; i < result.length; i++) {
$("#returnedProducts").append($("<option/>",
{
//option stuff
}
));
}
}
});
}
});
Have a persistent variable that holds a setTimeout. On input, clear the current timeout (if there is one), and set another timeout to trigger in 3 seconds (unless another input event occurs). You may also consider putting the ajax call (at least) into its own function, for the sake of less indentation hell:
let timeout;
$('input').on('input', () => {
clearTimeout(timeout);
console.log('timeout set');
timeout = setTimeout(() => console.log('action running'), 3000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input>
let timeout;
$('#productInput').on('input', function() {
clearTimeout(timeout);
let _this = $(this);
let optSelector = `option[value='${_this.val()}']`;
if (_this.val() === '') {
return;
} else if ($('#returnedProducts').find(optSelector).length) {
//html stuff
} else {
const searchResult = $(this).val();
timeout = setTimeout(ajaxCall, 3000, searchResult);
}
});
function ajaxCall(search_result) {
$.ajax({
url: '/account/autocomplete',
data: { search_result },
"_token": "{{ csrf_token() }}",
type: "POST",
success: successHandler
});
}
function successHandler(response) {
$("#returnedProducts").empty();
var result = response.hits.hits;
for (let i = 0; i < result.length; i++) {
$("#returnedProducts").append($("<option/>", {
//option stuff
}));
}
}

Repeated Ajax calls using SetTimeout javascript, unexpected execution

I list of users in a html table that is dynamically created on page load. Each row has an inline button and each button has onclick="functionName(userId)", calls the following functions:On click show the bootstrap model pop up and then after starts calling ajax. The problem is stopping the ajax calls after user has closed model,and if user clicks on another row/user pass the current userId. for some reason, sometimes ajax calls stop and sometimes dont. Previous userId is also being saved somewhere which is resulting double or triple calls in a given interval. Thank you for your insights.
//This function gets called from each row passing its userId:
var timer = null;
function RTLS(id) {
$('#RTLSModal').modal('show');
window.clearTimeout(timer);
$('#RTLSModal').on('hidden.bs.modal',
function() {
window.clearTimeout(timer);
timer = 0;
$('#RTLSModal .modal-body').html("");
$('#RTLSModal').data('bs.modal', null);
});
$('#RTLSModal').on('shown.bs.modal',
function () {
GetRealTimeScans(id);
});
}
function GetRealTimeScans(id) {
var html = '';
$.ajax({
url: '/api/v1/computers/GetRealTimeKeys?computerId=' + id,
typr: "GET",
contentType: "application/json;charset=UTF-8",
dataType: "json",
success: function (scans) {
if (scans.length > 0) {
$.each(scans,
function (index, value) {
//create html
});
$('#RTLSModal .modal-body').html(html);
} else {
html += '<div class=""><h3 style="text-align: center;">No one around</h3></div>';
$('#RTLSModal .modal-body').html(html);
}
},
complete: function () {
timer = setTimeout('GetRealTimeScans('+id+')', 10000);
}
});
}
So abort the Ajax call so it stops
var timer = null;
var ajaxCall;
function cleanUp () {
if (timer) window.clearTimeout(timer);
if (ajaxCall) ajaxCall.abort()
}
and when you make the call
cleanUp()
ajaxCall = $.ajax({})
.done( function () {
ajaxCall = null
timer = window.setTimeout(function(){}, 10000)
});
And when you bind the events to the modal, you need to remove the previous event handler.
$('#RTLSModal')
.off('hidden.bs.modal shown.bs.modal')
.on('hidden.bs.modal', function() {})
.on('shown.bs.modal', function() {});

Keep setTimeout function running after browser becomes idle

The following code is used for keeping track of updates from a database.
Problem is it will stop running after some time (probably when the browser becomes idle).
$(function() {
function Update() {
var postData = "";
$.ajax({
url: 'functions/ajax_api.php?dashboarddata',
type : 'post',
data: postData,
success: function(resp) {
$('#entradasmas7').html($('#entradasmas7' , resp).html());
$('#entradasmenos7').html($('#entradasmenos7' , resp).html());
// Call Update again after 30 seconds.
setTimeout(function() { Update(); }, 30000);
}
});
}
// Call postData the first time to start it off.
Update();
});
How can I make it run continually regardless of browser state, or call it back when the window becomes active?
In case of error it will not restart the timer, so there are 2 solution:
A.: add error handler and put the setTimeout(function() { Update(); }, 30000); code into the handler, because in case of error nothing restarts the timer.
disadvantages: callings are not exact 30sec later in case of long time response
$(function() {
function Update() {
var postData = "";
$.ajax({
url: 'functions/ajax_api.php?dashboarddata',
type : 'post',
data: postData,
success: function(resp) {
$('#entradasmas7').html($('#entradasmas7' , resp).html());
$('#entradasmenos7').html($('#entradasmenos7' , resp).html());
// Call Update again after 30 seconds.
setTimeout(function() { Update(); }, 30000);
},
error: function() {
setTimeout(function() { Update(); }, 30000);
}
});
}
// Call postData the first time to start it off.
Update();
});
B.: use setInterval instead of setTimer: but you have to schedule only onece, and you have to abort the previous ajax call if the next tick is coming:
$(function() {
var xhr = null;
function Update() {
var postData = "";
if(xhr!=null) { xhr.abort(); } // avoid paralell call of ajax_api.php, so we stop the previous one
xhr = $.ajax({
url: 'functions/ajax_api.php?dashboarddata',
type : 'post',
data: postData,
success: function(resp) {
$('#entradasmas7').html($('#entradasmas7' , resp).html());
$('#entradasmenos7').html($('#entradasmenos7' , resp).html());
}
});
}
// Call postData the first time to start it off.
Update();
setInterval(function() { Update(); }, 30000);
});

stop the setInterval if the content returned is not empty

So I am retrieving some data via POST using ajax, every 5 seconds, what I am trying to achieve is if the php file ouputs something, then stop the setInterval somehow or set it to 9999999.
Here is what I've tried:
var interval = DEFINEDFROMMYQL;
$(function() {
setInterval(function() {
$.ajax({
type: "POST",
url: "url/file.php",
data: "whatever=2",
success: function(html) {
$("#new").html(html);
if(html.lenght > 0) {
var interval = 99999999999999;
}
}
});
}, interval);
});
I'm a newbie, so any help will be appreciated.
You can use clearInterval() to stop the timer started by setInterval and correct the typo html.lenght to html.length
// var interval = DEFINEDFROMMYQL;
$(function() {
yourInterval = setInterval(function() {
$.ajax({
type: "POST",
url: "url/file.php",
data: "whatever=2",
success: function(html) {
$("#new").html(html);
if(html.length > 0) {
///var interval = 99999999999999;
clearInterval(yourInterval);
}
}
});
}, interval);
});
You can handle this a couple of different ways, but based on your question ("stop the setinterval somehow") let's switch the implementation to a setTimeout and also refactor the code in to a function we can recall. So...
var interval = DEFINEDFROMMYQL;
$(function() {
// establish a function we can recall
function getDataFromServer(){
// this encapsulates the original code in a function we can re-call
// in a setTimeout later on (when applicable)
$.ajax({
type: "POST",
url: "url/file.php",
data: "whatever=2",
success: function(html) {
$("#new").html(html);
// only if the length is 0 do we re-queue the function
// otherwise (becase it's setTimeout) it will just die
// off and stop.
if(html.lenght == 0) {
setTimeout(getDataFromServer, interval);
}
}
});
}
// make an initial call to the function to get the ball rolling
setTimeout(getDataFromServer, interval);
// if you want it to execute immediately instead of wait out the interval,
// replace the above line to simply:
//getDataFromServer();
});

Categories

Resources