How can I stop queue animation jquery? - javascript

I am using this function to add or remove products from favorites.
When I add or remove a product from favorites a div pops out with a message.
I have a problem with the queue animation.
Does anyone knows a way to fix this?
function addFavorite(code, action) {
var website = 'http://localhost';
var cod = code;
var action = action;
var $this = $j(this);
if (action == 'removeFav') {
$j.ajax({
type: 'post',
url: '/ajax/handler.favorite.php?action=removeFav',
data: {
'cod': cod
},
beforeSend: function() {
$j('.topMessage').show();
$j('.topMessage span').html('<img src="' + website + '/assets/loader.gif" alt="loading..">');
$j('.topMessage span').animate({
top: "+=80px",
}, 500);
},
success: function(data) {
$j('.topMessage span').html(data);
$j('.topMessage span').delay(3000).animate({
top: "-=80px",
}, 500);
}
});
}
if (action == 'addFav') {
$j.ajax({
type: 'post',
url: '/ajax/handler.favorite.php?action=addFav',
data: {
'cod': cod
},
beforeSend: function() {
$j('.topMessage').show();
$j('.topMessage span').html('<img src="' + website + '/assets/loader.gif" alt="loading..">');
$j('.topMessage span').animate({
top: "+=80px",
}, 500);
},
success: function(data) {
$j('.topMessage span').html(data);
$j('.topMessage span').delay(3000).animate({
top: "-=80px",
}, 500);
}
});
}
}

You can do something like this:
Create a function to display your messages and animate your div.
function displayAddedMessage(message) {
var span = $j('.topMessage span');
var addedMessage = span.parent();
var wrapper = addedMessage.parent();
addedMessage.css('top', -85).hide();
if (message) {
span.html(message);
}
var clonedAddedMessage = addedMessage.clone(false);
addedMessage.remove();
wrapper.prepend(clonedAddedMessage);
clonedAddedMessage.show().delay(100).animate({
top: 10
}, 500).delay(3500).animate({
top: -100
}, 500);
}
You can use this function in:
function addFavorite(code, action) {
var website = 'http://localhost';
var cod = code;
var action = action;
var $this = $j(this);
if (action == 'removeFav') {
$j.ajax({
type: 'post',
url: '/ajax/handler.favorite.php?action=removeFav',
data: {
'cod': cod
},
beforeSend: function() {
$j('.topMessage').show();
displayAddedMessage('<img src="' + website + '/assets/loader.gif" alt="loading..">');
},
success: function(data) {
$j('.topMessage span').html(data);
displayAddedMessage(data);
}
});
}
if (action == 'addFav') {
$j.ajax({
type: 'post',
url: '/ajax/handler.favorite.php?action=addFav',
data: {
'cod': cod
},
beforeSend: function() {
$j('.topMessage').show();
displayAddedMessage('<img src="' + website + '/assets/loader.gif" alt="loading..">');
},
success: function(data) {
$j('.topMessage span').html(data);
displayAddedMessage(data);
}
});
}
}

You can achieve like this :
$j('.topMessage span').stop().animate({
top: "-=80px",
}, 500);
Refer documentation.

hope this will solve your problem
first create a global variable
var isAnimating = false; // a global variable
then change your ajax request code with this one
$j.ajax({
type: 'post',
url: '/ajax/handler.favorite.php?action=removeFav',
data: {
'cod': cod
},
beforeSend: function() {
$j('.topMessage').show();
$j('.topMessage span').html('<img src="' + website + '/assets/loader.gif" alt="loading..">');
iF(!isAnimating) { // check animation is not running
isAnimating = true;
$j('.topMessage span').animate({
top: "+=80px",
}, 500);
}
},
success: function(data) {
$j('.topMessage span').html(data);
$j('.topMessage span').delay(3000).animate({
top: "-=80px",
}, 500, function() {
isAnimating = false; // this callback will called after animation complete
});
}
});

Related

Get embeded page with javascript for myBB

I have this code and I am woundering how to change it so that it will get the information without you having to use the click function.
Image from Visual Studio
if (PREVIEW == 1) {
$(this).before('<span class="prev-img" alt="Preview" title="Preview">🔍</span>');
var linkurl = $(this).attr('href');
$(this).prev('.prev-img').on('click', function() {
$('.am_preview').each(function () {
$(this).removeClass('am_preview');
});
$(this).next('a').addClass('am_preview');
$.ajax({
type: "get",
url: "xmlhttp.php?action=load_preview&linkurl="+encodeURI(linkurl),
async: true,
success: function(response) {
$('.am_preview').outerHTML(response.html);
$(".am_embed").css("max-width", MAXWIDTH+"px");
},
error: function (response) {
$('.am_errorMessage').each(function () {
$(this).hide();
});
$('.am_preview').after('<div class="am_errorMessage">' + NOPREVIEW + '</div>');
}
});
setTimeout(function() {
$('.am_errorMessage').each(function () {
$(this).fadeOut('fast');
});
}, 6000);
$(this).hide();
});
}
// Embed from sites with oembed api
if (file.indexOf('soundcloud.com/') !== -1) {
$(this).scembed();
$(this).prev('.prev-img').hide();
}

Ajax callback is firing after function call

Hi Have a ajax call in a function thats called on date input change event to check if a date is already in use for User. the success in the Ajax call fires after the click function is finished.
How do I get the success results and continue on with the #datepicker change funtion as I need the json results for rest of function.
controller
public ActionResult IsDateAvailable(DateTime date, int Id) {
var dateAvailable = !(_context.Trading.Any(t => t.uId == Id && t.TradingDate == date));
if (!(dateAvailable)) {
return Json(new {
status = false, msg = "This date already exists."
});
}
return Json(new {
status = true
});
}
JavaScript
$(document).ready(function() {
var message;
var isDateValid;
function CheckDate(para) {
var dateValid;
var mesg;
return $.ajax({
url: '#Url.Action("IsDateAvailable", "Trading")',
type: "GET",
data: para,
dataType: "json",
success: function(data) {
if (!(data.status)) {
message = data.msg;
} else {
isDateValid = true;
}
},
error: function(xhr, httpStatusMessage) {
alert(xhr + httpStatusMessage);
}
});
}
$("#datePicker").change(function() {
$("#alert").css({
'display': 'none'
});
if (Id == 0) {
$("#alert").attr('class', 'alert alert-danger');
$("#alert").text('Please select a User.');
$("#alert").show();
return false;
}
var date = $(this).val();
var para = {
date: date,
Id: Id
};
CheckDate(para);
if (isDateValid) {
$("#btnAdd").show();
} else {
$("#btnAdd").css({
'display': 'none'
});
$("#alert").attr('class', 'alert alert-danger');
$("#alert").text(message);
$("#alert").show();
}
});
});
You should turn to being asynchronous. change your code to match with these:
.
.
.
function CheckDate(para) {
return new Promise((resolve, reject) => {
return $.ajax({
url: '#Url.Action("IsDateAvailable", "Trading")',
type: "GET",
data: para,
dataType: "json",
success: function(data) {
if (!(data.status)) {
message = data.msg;
} else {
isDateValid = true;
}
resolve();
},
error: function(xhr, httpStatusMessage) {
alert(xhr + httpStatusMessage);
reject();
}
});
}
.
.
.
checkDate(para).then(res => {
if (isDateValid) {
$("#btnAdd").show();
} else {
$("#btnAdd").css({
'display': 'none'
});
$("#alert").attr('class', 'alert alert-danger');
$("#alert").text(message);
$("#alert").show();
}
}).catch(err => { /* do something */ });
You just need to set async: false inside your ajax request. You can also remove the word return from the CheckDate, because of it's redundant:
function CheckDate(para) {
var dateValid;
var mesg;
$.ajax({
url: '#Url.Action("IsDateAvailable", "Trading")',
async: false,
type: "GET",
data: para,
dataType: "json",
success: function(data) {
if (!(data.status)) {
message = data.msg;
} else {
isDateValid = true;
}
},
error: function(xhr, httpStatusMessage) {
alert(xhr + httpStatusMessage);
}
});
}

Resumable file upload customize name and add additional parametrs

I'm using http://resumablejs.com/ and can't understand how I can change filename after upload.
Describe a little more my situation:
I have file UploadFile.php with default code:
include 'vendor/autoload.php';
use Dilab\Network\SimpleRequest;
use Dilab\Network\SimpleResponse;
use Dilab\Resumable;
$request = new SimpleRequest();
$response = new SimpleResponse();
$resumable = new Resumable($request, $response);
$resumable->tempFolder = 'tmps';
$resumable->uploadFolder = 'upload/video';
$resumable->process();
I know that if I will use following:
$originalName = $resumable->getOriginalFilename(Resumable::WITHOUT_EXTENSION);
$slugifiedname = 'custom_prefix_'.$originalName;
$resumable->setFilename($slugifiedname);
It's will add 'custom_prefix_' to my filename.
But! I need use for prefix some additional information from form (Firstname and Lastname), how I can add this information to my request?
In frontend my file looks like:
<script type="text/javascript">
window.onload = (function () {
var r = new Resumable({
target: '/UploadFile.php',
maxChunkRetries: 2,
maxFiles: 1,
prioritizeFirstAndLastChunk: true,
simultaneousUploads: 4,
chunkSize: 5 * 1024 * 1024,
uploadMethod: 'POST',
maxFileSize: 550 * 1024 * 1024
});
...
uploadFile.on('click', function () {
$('.valid').html('');
if (results.children().length > 0) {
$.ajax({
url: '/Validate.php',
type: "POST",
data: $('#upload_form').serialize()+'&fileType='+fType+'&fileName='+fName,
dataType: "json",
success: function (data) {
if (results.children().length > 0) {
if(data[0]==true && data[1]==true){
$.ajax({
url: '/FormUpload.php',
type: "POST",
data: $('#upload_form').serialize()+'&fileType='+fType+'&fileName='+fName,
success: function (data) {
if (results.children().length > 0) {
r.upload();
} else {
nothingToUpload.fadeIn();
setTimeout(function () {
nothingToUpload.fadeOut();
}, 3000);
}
}
});
}else{
if(data[0]==false){
valid.text('Please complete all required fields!');
}
if(data[1]==false){
valid.text('Please complete all exeption fields!');
}
}
} else {
nothingToUpload.fadeIn();
setTimeout(function () {
nothingToUpload.fadeOut();
}, 3000);
}
}
});
} else {
nothingToUpload.css('opacity', 1);
setTimeout(function () {
nothingToUpload.css('opacity', 0);
}, 3000);
}
});
Try this code:
$resumable->process();
// you can get file information after the upload is complete
if (true === $resumable->isUploadComplete()) { // true when the final file has been uploaded and chunks reunited.
$extension = $resumable->getExtension();
$filename = $resumable->getFilename();
}
I found solution in my file FormUpload.php I return necessary information and send it like this:
uploadFile.on('click', function () {
$('.valid').html('');
if (results.children().length > 0) {
$.ajax({
url: '/Validate.php',
type: "POST",
data: $('#upload_form').serialize()+'&fileType='+fType+'&fileName='+fName,
dataType: "json",
success: function (data) {
if (results.children().length > 0) {
if(data[0]==true && data[1]==true){
$.ajax({
url: '/FormUpload.php',
type: "POST",
data: $('#upload_form').serialize()+'&fileType='+fType+'&fileName='+fName,
success: function (data) {
var data = jQuery.parseJSON(data);
if (results.children().length > 0) {
r.files[0].fileName = data.new_file_name;
r.upload();
} else {
nothingToUpload.fadeIn();
setTimeout(function () {
nothingToUpload.fadeOut();
}, 3000);
}
}
});
}else{
if(data[0]==false){
valid.text('Please complete all required fields!');
}
if(data[1]==false){
valid.text('Please complete all exeption fields!');
}
}
} else {
nothingToUpload.fadeIn();
setTimeout(function () {
nothingToUpload.fadeOut();
}, 3000);
}
}
});
} else {
nothingToUpload.css('opacity', 1);
setTimeout(function () {
nothingToUpload.css('opacity', 0);
}, 3000);
}
});

javascript works on localhost but fails on hosting server

When i click on add-to-basket button i see an error which appears in my browser console saying :
Here is my basket.js file :
$(document).ready(function() {
initBinds();
function initBinds() {
if ($('.remove_basket').length > 0) {
$('.remove_basket').bind('click', removeFromBasket);
}
if ($('.update_basket').length > 0) {
$('.update_basket').bind('click', updateBasket);
}
if ($('.fld_qty').length > 0) {
$('.fld_qty').bind('keypress', function(e) {
var code = e.keyCode ? e.keyCode : e.which;
if (code == 13) {
updateBasket();
}
});
}
}
function removeFromBasket() {
var item = $(this).attr('rel');
$.ajax({
type: 'POST',
url: '/home/u919084925/public_html/mod/basket_remove.php',
dataType: 'html',
data: ({ id: item }),
success: function() {
refreshBigBasket();
refreshSmallBasket();
},
error: function() {
alert('An error has occurred');
}
});
}
function refreshSmallBasket() {
$.ajax({
url: '/home/u919084925/public_html/mod/basket_small_refresh.php',
dataType: 'json',
success: function(data) {
$.each(data, function(k, v) {
$("#basket_left ." + k + " span").text(v);
});
},
error: function(data) {
alert("An error has occurred");
}
});
}
function refreshBigBasket() {
$.ajax({
url: '/home/u919084925/public_html/mod/basket_view.php',
dataType: 'html',
success: function(data) {
$('#big_basket').html(data);
initBinds();
},
error: function(data) {
alert('An error has occurred');
}
});
}
if ($(".add_to_basket").length > 0) {
$(".add_to_basket").click(function() {
var trigger = $(this);
var param = trigger.attr("rel");
var item = param.split("_");
$.ajax({
type: 'POST',
url: '/home/u919084925/public_html/mod/basket.php',
dataType: 'json',
data: ({ id : item[0], job : item[1] }),
success: function(data) {
var new_id = item[0] + '_' + data.job;
if (data.job != item[1]) {
if (data.job == 0) {
trigger.attr("rel", new_id);
trigger.text("Remove from basket");
trigger.addClass("red");
} else {
trigger.attr("rel", new_id);
trigger.text("Add to basket");
trigger.removeClass("red");
}
refreshSmallBasket();
}
},
error: function(data) {
alert("An error has occurred");
}
});
return false;
});
}
function updateBasket() {
$('#frm_basket :input').each(function() {
var sid = $(this).attr('id').split('-');
var val = $(this).val();
$.ajax({
type: 'POST',
url: '/home/u919084925/public_html/mod/basket_qty.php',
data: ({ id: sid[1], qty: val }),
success: function() {
refreshSmallBasket();
refreshBigBasket();
},
error: function() {
alert('An error has occurred');
}
});
});
}
// proceed to paypal
if ($('.paypal').length > 0) {
$('.paypal').click(function() {
var token = $(this).attr('id');
var image = "<div style=\"text-align:center\">";
image = image + "<img src=\"/images/loadinfo.net.gif\"";
image = image + " alt=\"Proceeding to PayPal\" />";
image = image + "<br />Please wait while we are redirecting you to PayPal...";
image = image + "</div><div id=\"frm_pp\"></div>";
$('#big_basket').fadeOut(200, function() {
$(this).html(image).fadeIn(200, function() {
send2PP(token);
});
});
});
}
function send2PP(token) {
$.ajax({
type: 'POST',
url: '/mod/paypal.php',
data: ({ token : token }),
dataType: 'html',
success: function(data) {
$('#frm_pp').html(data);
// submit form automatically
$('#frm_paypal').submit();
},
error: function() {
alert('An error has occurred');
}
});
});
I tried to resolve it but couldn't find a proper solution.
Help me with this, I cannot understand the cause of this error.
This is mainly due to Rules of Origins (CORS), for some reason the javascript(browser) sees the request as not residing in the same server. And the reason for that, I believe, is because /home/u919084925/public_html/mod/basket.php is not seen as a valid url on the server, it should start with http://{hostname}/{path}.
It looks like your ajax url is totally wrong and the browser interpret that is cross origin ajax request. Please simply check in browser's address bar if your ajax provided urls are valid.

Asynchronous complete condition with dropzone.js

I have a page with three dropzones which each call a function to update an image on the site once they're complete. The problem is that if three files are being uploaded at the same time, the function does not fire until the last of the three has finished uploading. Is there a way to fire off an iteration of the function every single time a file is uploaded?
Javascript:
var updatePreview = function(page) {
$.ajax({
url: 'submit.php',
type:'GET',
success: function(data){
var pageSize = '',
source_preview = '',
source_preview_background = '';
if ($(data).find('#file_0' + page + ' .ledger_preview').length) {
//If paper is ledger-size
source_preview = $(data).find('#file_0' + page + ' .ledger_preview'),
source_preview_background = source_preview.css('background-image');
$('#file_0' + page + ' .ledger_preview').css('background-image', source_preview_background);
}
else {
//If paper is letter-size
source_preview = $(data).find('#file_0' + page + ' .letter_preview'),
source_preview_background = source_preview.css('background-image');
$('#file_0' + page + ' .letter_preview').css('background-image', source_preview_background);
}
}
});
};
Dropzone.autoDiscover = false;
var dzOne = new Dropzone('#file-one', {
url: 'submit.php',
paramName: 'file_01',
method: 'POST',
init: function() {
this.on('complete', function() {
updatePreview('1');
});
},
accept: function(file, done) {
done();
}
});
var dzTwo = new Dropzone('#file-two', {
url: 'submit.php',
paramName: 'file_02',
method: 'POST',
init: function() {
this.on('complete', function() {
updatePreview('2');
});
},
accept: function(file, done) {
done();
}
});
var dzThree = new Dropzone('#file-three', {
url: 'submit.php',
paramName: 'file_03',
method: 'POST',
init: function() {
this.on('complete', function() {
updatePreview('3');
});
},
accept: function(file, done) {
done();
}
});

Categories

Resources