Asynchronous complete condition with dropzone.js - javascript

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

Related

When I edited directly in the grid instead of the modal at the right the filter never drops but when I edit in modal and save the filter dropped

class ProductInfoDetailsViewModel {
constructor(parent, productInfoWindowId, inventoryId, productId, supplierId, store) {
this._parent = parent;
this._created = false;
this._productInfoWindowId = productInfoWindowId;
this._inventoryId = inventoryId;
this._productId = productId;
this._supplierId = supplierId;
this._store = store;
}
_getMvvmData(inventoryId, productId, supplierId) {
return new Promise(function (resolve, reject) {
$.ajax({
url: '/ProductRowInfoSite/GetInventoryControl',
data: {
'inventoryId': inventoryId,
'productId': productId,
'supplierId': supplierId,
},
dataType: 'json', // "jsonp" is required for cross-domain requests; use "json" for same-domain requests
success: function (result) {
resolve(result);
},
error: function (jqXHR, textStatus, errorThrown) {
reject([jqXHR, textStatus, errorThrown]);
},
type: 'POST',
});
});
}
async create() {
let self = this;
let userStore = new UserStore();
//productInfoTextGrid
this._productInfoDetailsViewModel = kendo.observable({
value: {},
close: function () {
//$("#generalProductInfoWindow").data("kendoWindow").close();
//closeWindow();
},
not: function (value) {
return !this.get(value);
},
save: function (e) {
let productInfoTextGrid = $(self._productInfoWindowId + ' ' + '#productInfoTextGrid').data('kendoGrid');
/* productInfoTextGrid.saveChanges();*/
let orderUnitsGrid = $(self._productInfoWindowId + ' ' + '#orderUnitsGrid').data('kendoGrid');
let selectedRefHistProd = null;
try {
selectedRefHistProd = this.get('value.SelectedRefHistProd').ProductId;
} catch (error) {
// may be set to null and that's fine/TK.
}
var data = {
ProductId: self._productId,
InventoryId: self._inventoryId,
SupplierId: self._supplierId,
Fmean: this.get('value.Fmean'),
FMAD: this.get('value.FMAD'),
FTrend: this.get('value.FTrend'),
SelectedSeason: this.get('value.SelectedSeason').SeasonId,
MinQuantity: this.get('value.MinQuantity'),
SelectedOrderUnitNo: this.get('value.SelectedOrderUnit').UnitNo,
LeadTime: this.get('value.LeadTime'),
LeadTimeDeviation: this.get('value.LeadTimeDeviation'),
StockKeepInterest: this.get('value.StockKeepInterest'),
MaxLevel: this.get('value.MaxLevel'),
MinLevel: this.get('value.MinLevel'),
OrderQuantity: this.get('value.OrderQuantity'),
ReorderLevel: this.get('value.ReorderLevel'),
EnableManualSetRAndQ: this.get('value.EnableManualSetRAndQ'),
ForecastError: this.get('value.ForecastError'),
SelectedHistoryProductId: selectedRefHistProd,
};
var dataString = JSON.stringify(data);
$.ajax({
url: '/ProductRowInfoSite/SaveParameters',
data: {
data: dataString,
},
dataType: 'json',
// "jsonp" is required for cross-domain requests; use "json" for same-domain requests
success: function (result) {
// notify the data source that the request succeeded
//options.success(result);
self._store.dispatch({ type: ActionProductInfoWindow.Saving });
self._parent.refreshParentGrids();
},
error: function (result) {
displayAjaxError(result);
},
type: 'POST',
});
let userStore = new UserStore();
let finishSaved = userStore.translatedString('SOLOSupplier.ProductInfoWindows.FinishSaved');
displaySuccess(finishSaved);
productInfoTextGrid.saveChanges();
orderUnitsGrid.saveChanges();
},
recalc: function () {
var validator = $(self._productInfoWindowId).kendoValidator().data('kendoValidator');
var a = validator.validate();
},
products: new kendo.data.DataSource({
type: 'json',
serverFiltering: true,
pageSize: 100,
transport: {
read: function (options) {
$.ajax({
url: '/ProductRowInfoSite/GetProductInventoryList',
data:
{
'inventoryId': self._inventoryId,
'productId': self._productId,
'data': options.data,
},
//"filter": filter
dataType: 'json', // "jsonp" is required for cross-domain requests; use "json" for same-domain requests
success: function (result) {
// notify the data source that the request succeeded
options.success(result.HistProducts);
},
error: function (result) {
// notify the data source that the request failed
options.error(result);
},
type: 'POST',
});
},
parameterMap: function (data, type) {
return kendo.stringify($.extend({ 'text': $(data.filter.filters).get(0).value }, data));
},
},
}),
isEnabled: true,
onValidate: function (e) {
console.log('onValidate');
let maxLevel = this.get('value.MaxLevel');
let minLevel = this.get('value.MinLevel');
let userStore = new UserStore();
let validationErrorMessage = userStore.translatedString('uctrlSupplierWeb.MaxLevelMinLevelWarning');
let validator = $(self._productInfoWindowId).kendoValidator({
messages: {
custom: validationErrorMessage,
},
rules: {
custom: function (input) {
if (input.is('[name=minLevelParameter]') && input.val() === '') {
return true;
} else if (input.is('[name=minLevelParameter]') && input.val() !== '' && maxLevel !== null) {
return maxLevel > minLevel;
}
if (input.is('[name=maxLevelParameter]') && input.val() === '') {
return true;
} else if (input.is('[name=maxLevelParameter]') && input.val() !== '' && minLevel !== null) {
return maxLevel > minLevel;
} else {
return true;
}
},
},
},
).data('kendoValidator');
if (validator.validate() === true) {
self._store.dispatch({ type: ActionProductInfoWindow.Changing });
} else {
self._store.dispatch({ type: ActionProductInfoWindow.Cancelling });
}
},
});
kendo.bind($(self._productInfoWindowId + ' ' + '#tabInventoryControl'), self._productInfoDetailsViewModel);
try {
let result = await self._getMvvmData(self._inventoryId, self._productId, self._supplierId);
self._productInfoDetailsViewModel.products.read();
self._productInfoDetailsViewModel.set('value', result);
if (result.UnitsOnOrderAfterLeadtime === true) {
if ($(self._productInfoWindowId + ' ' + '#valueUnitsOnOrder').data('kendoNumericTextBox')) {
let widget = $(self._productInfoWindowId + ' ' + '#valueUnitsOnOrder').data('kendoNumericTextBox');
widget.wrapper.find('input').addClass('lightRed');
}
}
if ($(self._productInfoWindowId + ' ' + '#minLevelParameterId').data('kendoNumericTextBox')) {
$(self._productInfoWindowId + ' ' + '#minLevelParameterId')
.data('kendoNumericTextBox')
.min(result.MinLevelDefault);
}
if ($(self._productInfoWindowId + ' ' + '#maxLevelParameterId').data('kendoNumericTextBox')) {
$(self._productInfoWindowId + ' ' + '#maxLevelParameterId')
.data('kendoNumericTextBox')
.min(result.MinLevelDefault);
}
var validator = $(self._productInfoWindowId).kendoValidator().data('kendoValidator');
validator.validate();
let element = $(self._productInfoWindowId);
window.kendo.ui.progress(element, false);
} catch ([jqXHR, textStatus, errorThrown]) {
displayAjaxError(jqXHR, textStatus, errorThrown);
productInfoDetailsViewModel.set('value', []);
window.kendo.ui.progress(element, false);
}
}
}
Saving edits in product info modal deletes used filters on products grid
if (productNo === null) {
let newFilter = await self._getFilterOnlyFromLocalStorage();
let totalFilter = $(self._gridId).data("kendoGrid").dataSource.filter();
totalFilter.filters.push.apply(totalFilter.filters, newFilter.filters);
$(self._gridId).data("kendoGrid").dataSource.filter(newFilter);
self._setPredefinedFilterButton(self);
}
}

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

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.

How can I stop queue animation jquery?

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

django request.user.is_authenticated() isn't returning true after page refresh (sometimes)

I have a registration form. After it is submitted, the page refreshes and I get some information back based on request.user. Sometimes request.user.is_authenticated() is returning True and everything works fine.... and sometimes False seemingly randomly.
I appreciate any insight into why this might be happening.
Registration form code
$('#reg_form').submit(function(e) {
e.preventDefault();
e.stopPropagation();
var serializedData = $(this).serializeArray();
var names = serializedData.map(function(r) {
return r.name;
});
var index_user = names.indexOf("regusername");
var index_pass = names.indexOf("regpassword1");
var index_email = names.indexOf("regemail");
var data2 = {};
data2["username"] = serializedData[index_user].value;
data2["password1"] = serializedData[index_pass].value;
data2["password"] = serializedData[index_pass].value;
data2["password2"] = serializedData[index_pass].value;
data2["email"] = serializedData[index_email].value;
console.log(data2);
var serializedFormData = $(this).serialize();
$.ajax({
url: window.url_root + '/accountsjson/register/',
type: 'POST',
dataType: 'json',
data: data2,
success: function(data) {
console.log(data); //remove
if (data.hasOwnProperty('success')) {
console.log("successful registration detected!!");
utils.loginAfterRegister(data2);
$('.register').slideUp();
$('.frame').hide();
} else {
utils.showRegister();
}
},
error: function() {
console.log("ERROR posting registration request. Abort!");
},
});
Function called from loginAfterRegister which has the refresh
function sendRating(rating, reload_on_return) {
$.ajax({
type: "POST",
dataType: 'json',
url: window.url_root + "/savecommentrating/1/" + rating.cid + "/",
data: {
"rating": rating.r2 / 100.0
},
success: function(data) {
if (data.hasOwnProperty('success')) {
console.log("data was sent!");
if (reload_on_return) {
location.reload();
}
}
},
error: function() {
console.log("rating didn't get sent!!");
}
})
}
mobile function within views.py
def mobile(request):
create_visitor(request)
os = get_os(1)
disc_stmt = get_disc_stmt(os, 1)
return render_to_response('mobile.html', context_instance = RequestContext(request, {'url_root' : settings.URL_ROOT,
'loggedIn' : str(request.user.is_authenticated()).lower(),
'client_data': mobile_client_data(request),
'client_settings': get_client_settings(True),
}))
create_visitor()
def create_visitor(request):
# See if we need to create a visitor here
if not request.user.is_authenticated() and not request.session.get('visitor_id', False):
visitor = Visitor()
visitor.save()
request.session['visitor_id'] = visitor.id

Categories

Resources