Ajax callback called multiple times - javascript

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
}
};

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);
}
});
});

Cannot add class to clicked element

I have code for adding products into favorites using JQuery and AJAX, my JavaScript code looks like:
$('.product-item-btn-fav').on('click', function(e){
b = $(this).data("product_number");
$.ajax({
type: "POST",
url: domain + "/ajax/favorite/" + b,
success: function (a) {
var d = parseInt($(a).find("#result").html());
if (d == 1) {
$(this).addClass("active");
} else {
if (d == -1) {
$(this).removeClass("active");
}
}
}
})
});
And HTML:
<a class="product-item-btn-fav" data-product_number="[%item.product_number%]">
<svg class="svg-icon-heart-filled">
<use xlink:href="[%domain.url_media%]/images/svg-sprite.svg#svg-icon-heart-filled"></use>
</svg>
</a>
This code works, it adds product into favorite list at backend side (so AJAX works and it returns valid result 1 or -1), but this call $(this).addClass("active"); doesn't add css class to <a> tag.
You have to store $(this) in variable for a
$('.product-item-btn-fav').on('click', function(e){
b = $(this).data("product_number");
var _t = $(this);
$.ajax({
type: "POST",
url: domain + "/ajax/favorite/" + b,
success: function (a) {
var d = parseInt($(a).find("#result").html());
if (d == 1) {
_t.addClass("active");
} else {
if (d == -1) {
_t.removeClass("active");
}
}
}
})
});
this does not point the element you are thinking, store this in a variable and use that inside the ajax callback function:
$('.product-item-btn-fav').on('click', function(e){
var b = $(this).data("product_number");
var prod = $(this);
$.ajax({
type: "POST",
url: domain + "/ajax/favorite/" + b,
success: function (a) {
var d = parseInt($(a).find("#result").html());
if (d == 1) {
prod.addClass("active");
} else {
if (d == -1) {
prod .removeClass("active");
}
}
}
});
});
That is because context to anchor element is lost in ajax callback function. You can set the context using context option in ajax. See Ajax Docs:
$.ajax({
type: "POST",
context : this,
url: domain + "/ajax/favorite/" + b,
success: function (a) {
var d = parseInt($(a).find("#result").html());
if (d == 1) {
$(this).addClass("active");
} else {
if (d == -1) {
$(this).removeClass("active");
}
}
}
})
$.ajax({
type: "POST",
context : this,
url: domain + "/ajax/favorite/" + b,
success: function (a) {
var d = parseInt($(a).find("#result").html());
if (d == 1) {
$(this).addClass("active");
} else {
$(this).removeClass("active");
}
}
})

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 call at last

in my jquery function i have two ajax call with serverside method and its working fine,
problem is ajax call at last amd after ajax line of code run but this lines of code depand on
function Rbook(b) {
var one = $(b).attr("data-oneislcc");
var two = $(b).attr("data-twoislcc");
var trip1 = $(b).attr("data-oneinfo");
var trip2 = $(b).attr("data-twoinfo");
var owflt = "l";
var inflt = 'r';
var owjdata = $(b).attr("data-ow");
var iwjdata = $(b).attr("data-iw");
var llccreturn, rlccreturn;
var lres, rres;
$("#fadeing").css("display", "block");
$("#fade").css("display", "block").css("height", $(document).height / 2);
if (one == 'true') {
$.ajax({
type: "POST",
url: "Search-RoundResult.aspx/FareQuoteMethod",
data: "{'ALcode':'" + trip1 + "','flt':'" + owflt + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function OnSuccess(response) {
if (response.d != null) {
lres = response.d;
if (response.d == "sessionExpire") {
}
else {
var data = new Array()
data = response.d.split("oldfare=");
llccreturn = owlcc(data[0], data[1])
}
}
else {
alert("Please Try agian.");
}
},
Error: function errer(msg) {
$("#fade").css("display", "none");
$("#light").css("display", "none");
alert(msg.d)
}
});
}
else {
llccreturn = ownonlcc(owjdata);
}
if (two == 'true') {
$.ajax({
type: "POST",
url: "Search-RoundResult.aspx/FareQuoteMethod",
data: "{'ALcode':'" + trip2 + "','flt':'" + inflt + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function OnSuccess(response) {
if (response.d != null) {
if (rres == "sessionExpire") {
}
else {
var data = new Array()
data = response.d.split("oldfare=");
rlccreturn = iwlcc(data[0], data[1])
}
}
else {
alert("Please Try agian.");
}
},
Error: function errer(msg) {
$("#fade").css("display", "none");
$("#light").css("display", "none");
alert(msg.d)
}
});
}
else {
rlccreturn = iwnonlcc(iwjdata);
}
if (llccreturn == 'farechange' || rlccreturn == 'farechange') {
$("#farechange").css("display", "block");
$("#fade").css("display", "block");
}
if (llccreturn == 'nofarechange' || rlccreturn == 'nofarechange') {
window.location = "reviewbooking.aspx?trip1=" + $(b).attr("data-oneinfo") + "&iwlcc=" + $(b).attr("data-oneislcc") + "&trip2=" + $(b).attr("data-twoinfo") + "&owlcc=" + $(b).attr("data-twoislcc");
}}
var owlcc = function (jdata, oldfare) {
//Some Calulation
retrun 'farechange';
}
var ownonlcc = function (jdata) { //Some Calulation
retrun 'nofarechange'}
var iwlcc = function (jdata, oldfare) { //Some Calulation
return 'farechange'}
var iwnonlcc = function (jdata) { retrun 'nofarechange'}
if run this code its run this line of code then rest so condition not validate
i dont know where i m doing wrong
if (llccreturn == 'farechange' || rlccreturn == 'farechange') {
$("#farechange").css("display", "block");
$("#fade").css("display", "block");
}
if (llccreturn == 'nofarechange' || rlccreturn == 'nofarechange') {
window.location = "reviewbooking.aspx?trip1=" + $(b).attr("data-oneinfo") + "&iwlcc=" + $(b).attr("data-oneislcc") + "&trip2=" + $(b).attr("data-twoinfo") + "&owlcc=" + $(b).attr("data-twoislcc");
}
It looks like you don't understand asynchronous javascript. When you do an ajax call, it sends the request, then continues running the code and only later runs the success handler. Otherwise, it wouldn't be able to do anything at all until the response came back, since javascript is single-threaded.
The Rbook function does the following: First, get lots of information from the DOM; then, send some ajax requests (and set handlers to run when the response comes back); then possibly make some changes to the DOM, depending on the values of llccreturn and rlccreturn (but they're still undefined). It's only when the ajax response comes back and the success handler is run that these variables are set, but by then it's too late.
If you want to run some code after hearing the ajax response, put it in the success handler (or call it from the success handler). In this case, it's further complicated by the fact that you don't want to run the code until both ajax responses have arrived, and also by the fact that you might just run iwnonlcc or ownonlcc synchronously instead of doing an ajax call. I'd say the easiest way to fix this would be to wrap the code you want to run at the end inside a function and an if block like this:
function dataWasReceived() {
if (llccreturn !== undefined && rlccreturn !== undefined) {
if (llccreturn == 'farechange' || rlccreturn == 'farechange') {
$("#farechange").css("display", "block");
$("#fade").css("display", "block");
}
if (llccreturn == 'nofarechange' || rlccreturn == 'nofarechange') {
window.location = "reviewbooking.aspx?trip1=" + $(b).attr("data-oneinfo") + "&iwlcc=" + $(b).attr("data-oneislcc") + "&trip2=" + $(b).attr("data-twoinfo") + "&owlcc=" + $(b).attr("data-twoislcc");
}
}
}
Then, every time you set the value of llccreturn or rlccreturn, call this function:
rlccreturn = iwlcc(data[0], data[1])
dataWasReceived();
and:
rlccreturn = iwnonlcc(iwjdata);
dataWasReceived();
etc.
I'm also concerned about this line (appears twice):
data: "{'ALcode':'" + trip2 + "','flt':'" + inflt + "'}",
You probably wanted to apply the argument as an object, not a JSON string representing that object:
data: {ALcode: trip2, flt: inflt},
(Incidentally, the string you gave wasn't valid JSON anyway, since it used ' instead of ".)

how should i delay the ajax request?

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);
}) ;

Categories