how should i delay the ajax request? - javascript

like this jquery code, how should i delay the ajax request? input is a text field...over my head ....thx for help...
var proname = "" ;
$("input[name='proname']").keyup(function(e){
//how should i delay this function on here ?
if (e.which == 13) return ;
if ($(this).val() != proname)
{
proname = $(this).val() ;
}
else
{
return ;
}
$.ajax({
type: "post",
data: "proname="+proname+"&page=1",
url: "/project/searchrate",
success: function(view){
alert(view) ;
}
}) ;
}) ;

You want to use setTimeout.
From your usage, it seems to be a good idea to have a timeout that is being cleared every time another keyup event occurs, to avoid a queue.
var requestDelay;
var proname;
$('input[name=proname]').keyup(function() {
if(e.which == 13 || $(this).val() == proname)
return;
proname = $(this).val();
// postpone the submit another 300 ms upon every new character
window.clearTimeout(requestDelay);
requestDelay = window.setTimeout(function() {
$.ajax(...);
}, 300);
});

I see you are doing some kind of autosearch/autocomplete feature.
Have you considered just using the jQuery UI Autocomplete? http://jqueryui.com/demos/autocomplete/#remote-jsonp
As for the question itself you have already been answered.

Use setTimeout.
var proname = "" ;
$("input[name='proname']").keyup(function(e){
if (e.which == 13) return;
setTimeout(function() {
if ($(this).val() != proname) {
proname = $(this).val();
} else {
return;
}
$.ajax({
type: "post",
data: "proname="+proname+"&page=1",
url: "/project/searchrate",
success: function(view){
alert(view) ;
}
});
}, DELAY_IN_MSECS);
});

$("input[name='proname']").keyup(function(e){
//how should i delay this function on here ?
if (e.which == 13) return ;
setTimeout(function() {
if ($(this).val() != proname)
{
proname = $(this).val() ;
}
else
{
return ;
}
$.ajax({
type: "post",
data: "proname="+proname+"&page=1",
url: "/project/searchrate",
success: function(view){
alert(view) ;
}
}) ;
}, 1000);
}) ;

Related

How add debounce ( delay ) time on search filter ? Javascript

All code example is here:
I need to add debounce time for this search ( on every keyup delay ) ?
Like keyup. For every maybe 0.5 second delay.
var searchRequest = null;
$(function () {
var minlength = 3;
$("#sample_search").keyup(function () {
var that = this,
value = $(this).val();
console.log('value', value)
if (value.length >= minlength ) {
if (searchRequest != null)
searchRequest.abort();
searchRequest = $.ajax({
type: "GET",
url: "https://jsonplaceholder.typicode.com/comments",
data: {
'search_keyword' : value
},
dataType: "text",
success: function(msg){
//we need to check if the value is the same
if (value==$(that).val()) {
console.log('value real' , msg)
//Receiving the result of search here
}
}
});
}
});
});
Look at the code below.
$("#sample_search").keyup(function() {
// If the user kept typing. Delete the previous timeout.
clearTimeout(delayTime);
// call 'ajaxCall' function after 500ms
var delayTime = setTimeout(ajaxCall, 500);
});
you can use setTimeout() function:
$(function () {
var minlength = 3;
$("#sample_search").keyup(function () {
var that = this,
value = $(this).val();
console.log('value', value);
if (value.length >= minlength ) {
if (searchRequest != null)
searchRequest.abort();
setTimeout(function(){
searchRequest = $.ajax({
type: "GET",
url: "https://jsonplaceholder.typicode.com/comments",
data: {
'search_keyword' : value
},
dataType: "text",
success: function(msg){
//we need to check if the value is the same
if (value==$(that).val()) {
console.log('value real' , msg)
//Receiving the result of search here
}
}
});
}, 500);
}
});
});

Return value false to stop ajax call?

var filterval = filterlist();
if (filterval) {
$.ajax({
type: "POST",
url: "filt.php",
data: main_string,
cache: false,
dataType:'json',
success: function(data) {}
});
}
filterlist() {
var fprice = $('input[name="fprice"]').val();
var lprice = $('input[name="lprice"]').val();
if (fprice >= lprice) {
alert("Value Wrong");
return false;
}
else if (fprice == "" || lprice == "") {
alert("price empty");
return false;
}
return fprice + " " + lprice;
}
I expectation is
Filterlist() function value false to AJAX process stop.
Value not false to work on ajax process .
var fprice = parseInt($('input[name="fprice"]').val());
var lprice = parseInt($('input[name="lprice"]').val());
Use parseInt to convert fprice and price into numbers(from strings) and then compairing is possible :)

Ajax callback called multiple times

I have a ajax-call to a script for searching numbers. The response is a json array with name and surname(Strings). The client-script is this and I think really don't see why the script is looping and sending the response multiple times. The toogle-solution was the last thing I tried.
$(document).ready(function () {
$("#phone").keyup(function () {
var number = $(this).val();
var toogle = 0;
if (number.length == 10 && toogle == 0) {
alert('inside with 10 numbers');
toogle = 1;
$.ajax({
type: "POST",
url: "info-phone.php",
dataType: "jsonp",
data: {
number: number
}
}).done(function (msg) {
toogle = 0;
if (msg.Name != "" && msg.Surname != "") {
$("#phone").add("Are you " + msg.Name + " " + msg.Surname);
};
}); //done-function
}
}); //phone-keyup
}); //document-ready
Basically I have a input, and when the user reaches 10 numbers this script will call the server and get the name to that number.
Any ideas? Just a typo?
try this:
$(document).ready(function () {
window.toogle = 0;
$("#phone").click(function () {
var number = $(this).val();
if (number.length == 10 && window.toogle == 0) {
alert('inside with 10 numbers');
window.toogle = 1;
$.ajax({
type: "POST",
url: "info-phone.php",
dataType: "jsonp",
data: {
number: number
}
}).done(function (msg) {
window.toogle = 0;
if (msg.Name != "" && msg.Surname != "") {
$("#phone").add("Are you " + msg.Name + " " + msg.Surname);
}
}); //done-function
}
}); //phone-keyup
}); //document-ready
I think your issue is that you're using .length which measures the length of strings, on the return of the jQuery .val() method, which returns strings or "numbers". As your input is a phone number, I think the .val() method is returning an integer, and you'd need to convert it to a string for .length to work correctly.
Try
number.toString().length;
First of all, you should not write anonymous functions with several identations.
Just name your functions to see clearer in that mess!
Your variables number and toogle are local to the anonymous function you call doing keyup.
I think there might be a problem here no?
Like this:
$(document).ready(function () {
window.toogle = 0;
$("#phone").click(phoneKeyUp); //phone-keyup -> this one you declare it to make document.ready() clearer
}); //document-ready
var phoneKeyUp = function() {
var number = $(this).val();
if (number.length == 10 && window.toogle == 0) {
alert('inside with 10 numbers');
window.toogle = 1;
$.ajax({
type: "POST",
url: "info-phone.php",
dataType: "jsonp",
data: {
number: number
}
}).done(function (msg) {
window.toogle = 0;
if (msg.Name != "" && msg.Surname != "") {
$("#phone").add("Are you " + msg.Name + " " + msg.Surname);
}
}); //done-function -> this one may stay here
}
};

Javascript does user exists, returning value from ajax to late?

I have a script that tells a visitor if the username is already exist or not before he can proceed,
Below you see a part of my code;
EDIT: Ok I have read what you guys said, and modified it, but I still dont get it to work :S, my teacher doesn't know it either...
<script type="text/javascript">
jQuery(document).ready(function(){
// Smart Wizard
jQuery('#wizard').smartWizard({onFinish: onFinishCallback, onLeaveStep: onNextStep});
function onNextStep(){
validateSteps(function (next) { return next; });
}
function onFinishCallback(){
alert('Finish Clicked');
}
function UsernameExist(fullname, callback)
{
    var data = 'user='+ fullname;
    if(fullname) {
        $.ajax({
            type: "POST",
            url: "user_check.php",
            data: data,
async: false,
            beforeSend: function(html) {
                $("#msg_lastname").html('');
            },
            success: function(html){
                $("#msg_lastname").show();
                 $("#msg_lastname").append(html);
if(html.search("red") != -1)
{
callback(false);
}
else
{
callback(true);
}
            }
        });
}
}
function validateSteps(callback){
var isStepValid = true;
// validate step 1
var firstname = $('#firstname').val();
if(!firstname || (firstname.length < 3 || firstname.length > 10))
{
$('#msg_firstname').html('<br/><font color="red">Enter a first name, between 3 and 10 letters.</font>').show();
isStepValid = false;
}
else
{
$('#msg_firstname').html('').hide();
}
var lastname = $('#lastname').val();
if(!lastname || (lastname.length < 3 || lastname.length > 14))
{
$('#msg_lastname').html('<br/><font color="red">Enter a last name, between 3 and 14 letters.</font>').show();
isStepValid = false;
}
else
{
$('#msg_lastname').html('').hide();
}
var gender = $('#gender').val();
if(!gender || Number(gender) == -1)
{
$('#msg_gender').html('<br/><font color="red">Choose your gender!</font>').show();
isStepValid = false;
}
else
{
$('#msg_gender').html('').hide();
}
var age = $('#age').val();
if(!age || Number(age) > 90 || Number(age) < 21)
{
$('#msg_age').html('<br/><font color="red">Enter a age between 21 and 90.</font>').show();
isStepValid = false;
}
else
{
$('#msg_age').html('').hide();
}
var pin = $('#pin').val();
if(!pin || pin.length > 10 || pin.length < 4)
{
$('#msg_pin').html('<br/><font color="red">Enter a PIN between 4 and 10 numbers.</font>').show();
isStepValid = false;
}
else
{
$('#msg_pin').html('').hide();
}
if (isStepValid) {
UsernameExist(firstname + ' ' + lastname, function (exists) {
callback( exists );
});
} else {
callback( false );
}
}
jQuery('select, input:checkbox').uniform();
});
</script>
Now the problem is that when I run this script, it returns undefined, I guess because the UsernameExist is not done fast enough, and it seems the return UsernameExist is not waiting for it for some reason...
You are returning UsernameExists before it has been run.
Instead, call UsernameExists like this:
if (isStepValid) {
UsernameExist(firstname + ' ' + lastname, function (exists) {
return exists;
});
} else {
return false;
}
This works because UsernameExists expects a callback function and on success passes either true or false to callback().
you need just to set async option as false
function UsernameExist(fullname, callback) {
var data = 'user=' + fullname;
if (fullname) {
$.ajax({
type: "POST",
url: "user_check.php",
data: data,
async: false,
beforeSend: function (html) {
$("#msg_lastname").html('');
},
success: function (html) {
//your code after success
}
});
}
}
from jQuery documentation jQuery.ajax
If you need synchronous requests, set this option to false
so you need to execute your ajax call and wait until it's completely finish to execute what you want based on the result
Maybe you should call UsernameExist(fullname, callback) after jQuery load complete.
try this :
getScript('http://code.jquery.com/jquery-1.9.1.min.js', function () {UsernameExist(fullname, callback)});
function getScript(url, callback) {
var script;
script = document.createElement("script");
script.setAttribute('language', 'javascript');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', url);
var done = false;
vObj = script.onload;
script.onload = script.onreadystatechange = function () {
if (!done && (!this.readyState ||
this.readyState == "loaded" || this.readyState == "complete")) {
done = true;
if (typeof callback === 'function')
callback(this.ownerDocument.attributes);
}
};
var head = document.getElementsByTagName('head')[0];
head.appendChild(script);}
Try something like this :
// Smart Wizard
$('#wizard').smartWizard({onFinish: onFinishCallback, onLeaveStep: onNextStep});
function onNextStep() {
var isValid = validateSteps();
alert(isValid);
}
function onFinishCallback(){
alert('Finish Clicked');
}
function UsernameExist(fullname)
{
var data = 'user='+ fullname;
var userAlreadyExists = null;
if(fullname) {
$.ajax({
type: "POST",
url: "user_check.php",
data: data,
async: false,
beforeSend: function(html) {
$("#msg_lastname").html('');
},
success: function(html){
$("#msg_lastname").show();
$("#msg_lastname").append(html);
if(html.search("red") != -1)
{
userAlreadyExists = false;
}
else
{
userAlreadyExists = true;
}
}
});
}
return userAlreadyExists;
}
function validateSteps(){
...
if (isStepValid) {
return UsernameExist(firstname + ' ' + lastname);
} else {
return false;
}
}

Ajax continuous pull from database

I have literally just started programing with Ajax and cant get this to work.
Here is what I have so far:
var oldAction = '';
function updateCheck() {
$.ajax({
url: 'check_status.php',
success: function (data) {
if (data.length != oldAction) {
if (data.length == '4') {
playSong();
} else {
pauseSong();
}
}
oldAction = data.length;
}
});
}
setInterval('updateCheck();', 1000);
Does anyone know why this would not be working?
Thanks
Sure. length() is looking for an integer, but you are comparing it to a string.
If oldAction really needs to be a string, then you need to do something like this:
if (data.length != Number(oldAction)) {
if (data.length == 4) {
playSong();
} else {
pauseSong();
}
};
try this:
function updateCheck() {
var
oldAction = 0,
callAjax = function () {
$.ajax({
url: 'check_status.php',
success: function (data) {
if (data.length != oldAction) {
(data.length == 4) ? playSong() : pauseSong();
}
oldAction = data.length;
}
});
};
setInterval(callAjax, 1000);
}
updateCheck();
​

Categories