Multiple calls to Ajax instead of once - javascript

I have the following code which works fine for most cases, but the problem I am having is on mouse over . After you hover for 10 sec the content expands and then calls ajax. The Ajax is making calls 5 times instead of just once.
I am not sure why its keep calling 5 times. Can someone help me fix this so ajax call runs only once?
Here is my code snippet below and the full working fiddle demo is here
$(".previewCard-content").hide();
var timeo = null;
$("body").on("mouseenter", ".previewCard-showhide", function() { // Use rather mouseenter!
var $that = $(this); // Store the `this` reference
clearTimeout(timeo); // Clear existent timeout on m.Enter
timeo = setTimeout(function() { // Before setting a new one
$that.hide().closest('p').next(".previewCard-content").slideDown("slow");
/**************** AJAX CALL********************/
var LinkTextVal = $that.closest('.previewCard-b').find('.previewCardPageLink').text();
console.log(" LinkTextVal " + LinkTextVal);
var descPageName = LinkTextVal + ' | About';
if ($('#userID').val() !== '' && $('#userID').val() !== undefined && $('#userID').val() !== null) {
$.ajax({
url: '/localhost/biz/actions/searchBookmark' + '?cachestop=' + nocache,
type: "get",
data: {
bookmarkName: descPageName
},
success: function(response) {
if (response === true) {
$that.parents('.previewCard-b').find('.save a').addClass('saved');
$that.parents('.previewCard-b').find('.save a').addClass('active');
$that.parents('.previewCard-b').find('.save a').find(".action-text").text("Saved");
}
},
error: function(e) {
console.log('Unable to check if a bookmark exists for the user.');
}
});
}
/***************** END AJaX/SAVE BUTTON ************/
}, 1000);
}).on("mouseleave", ".previewCard-showhide", function() { // mouse leaves? Clear the timeout again!
clearTimeout(timeo);
});
$(".close-btn").on("click", function() {
var $itemB = $(that).closest(".previewCard-b");
$itemB.find(".previewCard-content").slideUp();
$itemB.find(".previewCard-showhide").show();
});

Mouse hover events happen every time the mouse moves over the element. You need is to have a boolean which checks if you have sent the AJAX Request or not, and if it hasn't send the AJAX request, else ignore the event.
$(".previewCard-content").hide();
var timeo = null;
var ajaxSent = false
$("body").on("mouseenter", ".previewCard-showhide", function() { // Use rather mouseenter!
var $that = $(this); // Store the `this` reference
clearTimeout(timeo); // Clear existent timeout on m.Enter
timeo = setTimeout(function() { // Before setting a new one
$that.hide().closest('p').next(".previewCard-content").slideDown("slow");
/**************** AJAX CALL********************/
var LinkTextVal = $that.closest('.previewCard-b').find('.previewCardPageLink').text();
console.log(" LinkTextVal " + LinkTextVal);
var descPageName = LinkTextVal + ' | About';
if ($('#userID').val() !== '' && $('#userID').val() !== undefined && $('#userID').val() !== null && !ajaxSent) {
ajaxSent = true;
$.ajax({
url: '/localhost/biz/actions/searchBookmark' + '?cachestop=' + nocache,
type: "get",
data: {
bookmarkName: descPageName
},
success: function(response) {
if (response === true) {
$that.parents('.previewCard-b').find('.save a').addClass('saved');
$that.parents('.previewCard-b').find('.save a').addClass('active');
$that.parents('.previewCard-b').find('.save a').find(".action-text").text("Saved");
}
},
error: function(e) {
console.log('Unable to check if a bookmark exists for the user.');
}
});
}
/***************** END AJaX/SAVE BUTTON ************/
}, 1000);
}).on("mouseleave", ".previewCard-showhide", function() { // mouse leaves? Clear the timeout again!
clearTimeout(timeo);
});
$(".close-btn").on("click", function() {
var $itemB = $(that).closest(".previewCard-b");
$itemB.find(".previewCard-content").slideUp();
$itemB.find(".previewCard-showhide").show();
});

Related

Why does my setTimeout not stop when I clear?

I am trying to stop my Timeout when I received data back from my ajax post. However, I get the data back, it updates my html, but the timer is still going. What's going wrong?
function getResponse() {
var i = 0;
var reply = null;
var myTimer;
while (i < 24 && reply == null) {
(function(i) {
myTimer = setTimeout(function() {
$.ajax({
url: '/getResponse',
data: "123456",
type: 'POST',
success: function (data) {
console.log("HERE data2 " + data);
if(data != "" || data != null){
reply = data;
document.getElementById("responseText").innerHTML = reply;
clearTimeout(myTimer);
}
},
error: function (error) {
document.getElementById("responseText").innerHTML = error;
console.log(error);
}
});
}, 5000 * i)
})(i++)
}
Here you are overwriting your global myTimer variable in each iteration of the while loop. So every time you are doing clearTimeout(myTimer) you are just clearing the timeout of the last setTimeout that is run when i becomes 23 and not for setTimeout created in the previous 22 iterations of the while loop. You actually have to declare the myTimer variable inside the IIFE in the while loop like the following to clearTimeout for all the 23 setTimeouts created during the while loop:
function getResponse() {
var i = 0;
var reply = null;
// var myTimer;
while (i < 24 && reply == null) {
(function(i) {
var myTimer = setTimeout(function() { // Declare myTimer here
$.ajax({
url: '/getResponse',
data: "123456",
type: 'POST',
success: function (data) {
console.log("HERE data2 " + data);
if(data != "" || data != null){
reply = data;
document.getElementById("responseText").innerHTML = reply;
clearTimeout(myTimer);
}
},
error: function (error) {
document.getElementById("responseText").innerHTML = error;
console.log(error);
}
});
}, 5000 * i)
})(i++)
}
It is cleared. But you are calling your function over and over (23 times) and every time you are setting new timeout and clearing him again.

Get the name of the uploaded file

I am new to AngularJS1 and Js. Here i am uploading a file which will be saved on my drive as well as in mongodb. What I am trying to do is to get the uploaded file name which can easily be seen here in attached picture. Kindly help me out with this.
$scope.uploadedFileList.push(p);
$('#addproFile').ajaxfileupload({
action: 'http://' + window.location.hostname + ':' + window.location.port + '/api/upload',
valid_extensions : ['md','csv','css', 'txt'],
params: {
dummy_name: p
},
onComplete: function(response) {
console.log('custom handler for file:');
alert(JSON.stringify(response));
/* $scope.nameString = uploadedFileList.join(',');
$scope.$apply();*/
},
onCancel: function() {
console.log('no file selected');
}
});
This is my controller
(function($) {
$.fn.ajaxfileupload = function(options) {
var settings = {
params: {},
action: '',
onStart: function() { },
onComplete: function(response) { },
onCancel: function() { },
validate_extensions : true,
valid_extensions : ['gif','png','jpg','jpeg'],
submit_button : null
};
var uploading_file = false;
if ( options ) {
$.extend( settings, options );
}
// 'this' is a jQuery collection of one or more (hopefully)
// file elements, but doesn't check for this yet
return this.each(function() {
var $element = $(this);
// Skip elements that are already setup. May replace this
// with uninit() later, to allow updating that settings
if($element.data('ajaxUploader-setup') === true) return;
$element.change(function()
{
// since a new image was selected, reset the marker
uploading_file = false;
// only update the file from here if we haven't assigned a submit button
if (settings.submit_button == null)
{
upload_file();
}
});
if (settings.submit_button == null)
{
// do nothing
} else
{
settings.submit_button.click(function(e)
{
// Prevent non-AJAXy submit
e.preventDefault();
// only attempt to upload file if we're not uploading
if (!uploading_file)
{
upload_file();
}
});
}
var upload_file = function()
{
if($element.val() == '') return settings.onCancel.apply($element, [settings.params]);
// make sure extension is valid
var ext = $element.val().split('.').pop().toLowerCase();
if(true == settings.validate_extensions && $.inArray(ext, settings.valid_extensions) == -1)
{
// Pass back to the user
settings.onComplete.apply($element, [{status: false, message: 'The select file type is invalid. File must be ' + settings.valid_extensions.join(', ') + '.'}, settings.params]);
} else
{
uploading_file = true;
// Creates the form, extra inputs and iframe used to
// submit / upload the file
wrapElement($element);
// Call user-supplied (or default) onStart(), setting
// it's this context to the file DOM element
var ret = settings.onStart.apply($element, [settings.params]);
// let onStart have the option to cancel the upload
if(ret !== false)
{
$element.parent('form').submit(function(e) { e.stopPropagation(); }).submit();
} else {
uploading_file = false;
}
}
};
// Mark this element as setup
$element.data('ajaxUploader-setup', true);
/*
// Internal handler that tries to parse the response
// and clean up after ourselves.
*/
var handleResponse = function(loadedFrame, element) {
var response, responseStr = $(loadedFrame).contents().text();
try {
//response = $.parseJSON($.trim(responseStr));
response = JSON.parse(responseStr);
} catch(e) {
response = responseStr;
}
// Tear-down the wrapper form
element.siblings().remove();
element.unwrap();
uploading_file = false;
// Pass back to the user
settings.onComplete.apply(element, [response, settings.params]);
};
/*
// Wraps element in a <form> tag, and inserts hidden inputs for each
// key:value pair in settings.params so they can be sent along with
// the upload. Then, creates an iframe that the whole thing is
// uploaded through.
*/
var wrapElement = function(element) {
// Create an iframe to submit through, using a semi-unique ID
var frame_id = 'ajaxUploader-iframe-' + Math.round(new Date().getTime() / 1000)
$('body').after('<iframe width="0" height="0" style="display:none;" name="'+frame_id+'" id="'+frame_id+'"/>');
$('#'+frame_id).get(0).onload = function() {
handleResponse(this, element);
};
// Wrap it in a form
element.wrap(function() {
return '<form action="' + settings.action + '" method="POST" enctype="multipart/form-data" target="'+frame_id+'" />'
})
// Insert <input type='hidden'>'s for each param
.before(function() {
var key, html = '';
for(key in settings.params) {
var paramVal = settings.params[key];
if (typeof paramVal === 'function') {
paramVal = paramVal();
}
html += '<input type="hidden" name="' + key + '" value="' + paramVal + '" />';
}
return html;
});
}
});
}
})( jQuery )
this is my ajax file upload function

Clear setTimeouts applied by class.each operation that creates timeout

I'm sorry the title might not make much sense. I'm not sure how to word what i'm doing.
I have a class that I add to elements that uses HTML5 data attributes to setup a refresh timer. Here is the current code.
$(document).ready(function () {
$('.refresh').each(function() {
var element = $(this);
var url = element.data('url');
var interval = element.data('interval');
var preloader = element.data('show-loading');
var globalPreloader = true;
if (typeof preloader === 'undefined' || preloader === null) {
}
else if (preloader != 'global' && preloader != 'true') {
globalPreloader = false;
}
(function(element, url, interval) {
window.setInterval(function () {
if (!globalPreloader)
{
$('#' + preloader).show();
}
$.ajax({
url: url,
type: "GET",
global: globalPreloader,
success: function (data) {
element.html(data);
if (!globalPreloader) {
$('#' + preloaderID).hide();
}
}
});
}, interval);
})(element, url, interval);
});
$.ajaxSetup({ cache: false });
});
Now I have elements that a user can click on the 'window' which removes it.
These elements can be tired to a timer that was set by the above code.
Code used to remove the element
$(".btn-close").on('click', function () {
var id = $(this).closest("div.window").attr("id");
if (typeof id === 'undefined' || id === null) {
} else {
$('#' + id).remove();
}
});
I need to now kill the timers created for the elements removed.
What is the best way to do this?
Not clear on how you clear them so I do them all here at the end.
$(document).ready(function () {
$('.refresh').each(function () {
var element = $(this);
var url = element.data('url');
var interval = element.data('interval');
var showLoading = element.data('show-loading');
var preloaderID = element.data('preloader-id');
if (typeof showLoading === 'undefined' || showLoading === null) {
showLoading = true;
}
(function (element, url, interval) {
var timerid = window.setInterval(function () {
if (showLoading) {
$('#' + preloaderID).show();
}
$.ajax({
url: url,
type: "GET",
global: showLoading,
success: function (data) {
element.html(data);
if (showLoading) {
$('#' + preloaderID).hide();
}
}
});
}, interval);
element.data("timerid",timerid );//add the timerid
})(element, url, interval);
});
$.ajaxSetup({
cache: false
});
$('.refresh').each(function () {
var timerId = $(this).data("timerid");
window.clearInterval(timerId);
});
});
Example: remove timer on a click
$('.refresh').on('click', function () {
var timerId = $(this).data("timerid");
window.clearInterval(timerId);
});
window.setIntervalreturns a handle for the timeout. You can use that to stop the timeout:
var handle = window.setInterval(function() {
window.clearInterval(handle);
}, 1000);
Hope that helps.
Here's a little demo of intervals and "interval assassins". It's a minimal example showing how you can clear intervals in a JavaScript-y way.
$('.start').click(function() {
var $parentRow = $(this).closest('tr')
var $stop = $parentRow.find('.stop')
var $val = $parentRow.children('.val')
// interval
var iid = setInterval(function() {
$val.text(+$val.text() + 1)
}, 10)
console.log(`New Target: ${iid}`)
// interval assassin
$stop.click(function() {
clearInterval(iid)
console.log(`Interval[${iid}] has been assassinated.`)
$(this).off('click')
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><button class="start">Start</button></td>
<td><button class="stop">Stop</button></td>
<td class="val">0</td>
</tr>
<tr>
<td><button class="start">Start</button></td>
<td><button class="stop">Stop</button></td>
<td class="val">0</td>
</table>
Just run the snippet to see a demo. Feel free to comment if you have any questions. You can set up multiple intervals by pressing start repeatedly and have them all be cleared at once with a single click of stop.

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 ".)

JS Wait till page Loads, Unless 5 seconds have passed then start timer (alter current .js)

The below code is a timer for my site's ads. The way its setup now it waits for the page to load fully before starting the timer. What I would like to do is to Alter this slightly to only wait 5 seconds, if the page has not finished loading by then just go ahead and start the timer. I have no idea how to do this at all.
$(document).ready(function () {
ptcevolution_surfer();
});
function showadbar(error) {
$("#pgl").removeAttr("onload");
if (error == '') {
$(".adwait").fadeOut(1000, function () {
$("#surfbar").html('<div class="progressbar" id="progress"><div id="progressbar"></div></div>');
$("#progressbar").link2progress(secs, function () {
endprogress('');
});
});
} else {
$(".adwait").fadeOut(1000, function () {
$("#surfbar").html("<div class='errorbox'>" + error + "</div>");
$(".errorbox").fadeIn(1000);
});
}
}
/* End Surf Bar */
function endprogress(masterkey) {
if (masterkey == '') {
$("#surfbar").fadeOut('slow', function () {
$("#vnumbers").fadeIn('slow');
});
return false;
} else {
$("#vnumbers").fadeOut('slow', function () {
$(this).remove();
$("#surfbar").fadeIn('slow');
});
}
$("#surfbar").html("Please wait...");
var dataString = 'action=validate&t=' + adtk + '&masterkey=' + masterkey;
$.ajax({
type: "POST",
url: "index.php?view=surfer&",
data: dataString,
success: function (msg) {
if (msg == 'ok') {
$("#surfbar").html("<div class='successbox'>" + adcredited + "</div>");
$(".successbox").fadeIn('slow');
if (adtk == 'YWRtaW5hZHZlcnRpc2VtZW50') {
window.opener.hideAdminAdvertisement();
} else {
window.opener.hideAdvertisement(adtk);
}
return false;
} else {
$("#surfbar").html("<div class='errorbox'>" + msg + "</div>");
$(".errorbox").fadeIn('slow');
}
}
});
}
function ptcevolution_surfer() {
if (top != self) {
try {
top.location = self.location;
} catch (err) {
self.location = '/FrameDenied.aspx';
}
}
$("#surfbar").html("<div class='adwait'>" + adwait + "</div>");
}
By your use of $, I'm going to assume jQuery
var __init = (function () {
var initialised = 0; // set a flag, I've hidden this inside scope
return function () { // initialisation function
if (initialised) return; // do nothing if initialised
initialised = 1; // set initialised flag
ptcevolution_surfer(); // do whatever
};
}()); // self-invocation generates the function with scoped var
window.setTimeout(__init, 5e3); // 5 seconds
$(__init); // on page ready
Now what happens? The first time the function is fired, it prevents itself from being fired a second time, then starts off whatever you want done.

Categories