Trigger a java script in before submit form - javascript

Hello while creating my php script I came across a difficulty to execute script 1[ajax uploader] ( on from submit ). The code that triggers the upload is uploadObj.startUpload(); i tried to add it on script 2 in before submit action, but somehow it doesn't lunch. Can you help me?
Script 1.
var uploadObj = $("#mulitplefileuploader").uploadFile({
url: "uploader/upload.php",
multiple: false,
fileName: "myfile",
maxFileSize: 655360 * 100, //5mb
allowedTypes: "jpg,png,gif,zip,txt,doc,docx,csv,xml,pdf,JPG,JPEG,jpeg",
maxFileCount: 1,
autoSubmit: false,
dragDropStr: "<span><b>Przeciągnij i upuść plik</b></span>",
abortStr: "Anuluj",
cancelStr: "Przerwij",
doneStr: "Dodano",
dynamicFormData: function () {
var data = {
uid: "<?PHP echo $_SESSION['userid']; ?>"
}
return data;
},
onSubmit: function (files) {
$("#eventsmessage").html($("#eventsmessage").html() + "<br/>Submitting:" + JSON.stringify(files));
},
onSuccess: function (files, data, xhr) {
$("#eventsmessage").html($("#eventsmessage").html() + "<br/>Success for: " + JSON.stringify(data));
},
afterUploadAll: function () {
$("#eventsmessage").html($("#eventsmessage").html() + "<br/>All files are uploaded");
},
onError: function (files, status, errMsg) {
$("#eventsmessage").html($("#eventsmessage").html() + "<br/>Error for: " + JSON.stringify(files));
}
});
Script 2.
$(document).ready(function () {
var options = {
target: "#msgholder",
beforeSubmit: function () {
showLoader;
},
success: showResponse,
url: "ajax/controller.php",
resetForm: 0,
clearForm: 0,
data: {
processTicket: 1
}
};
$("#admin_form").ajaxForm(options);
});
function showResponse(msg) {
hideLoader();
$(this).html(msg);
$("html, body").animate({
scrollTop: 0
}, 600);
}

Related

How can I implement a wait mechanism until receiving confirm dialog response?

Here is my code:
$(function () {
$(document).on('click', '.fa-times', function(e){
e.stopPropagation();
var result = ConfirmDialog('Are you sure?');
if (result) {return false}
var row = $(this).closest('tr');
row.css('opacity','0.3');
var word = $(this).closest('td').siblings('.word').text();
$.ajax({
url : '../../te_addStopWord',
type : 'GET',
data: {word : word},
dataType : 'JSON',
success : function () {
row.remove();
}, // success
error : function ($a,$b,$c) {
alert($b);
row.css('opacity','1');
}
}); // ajax
})
function ConfirmDialog(message) {
$('<div></div>').appendTo('body')
.html('<div><h6>'+message+'?</h6></div>')
.dialog({
modal: true, title: 'Delete message', zIndex: 10000, autoOpen: true,
width: 'auto', resizable: false,
buttons: {
Yes: function () {
$(this).remove();
return true;
},
No: function () {
$(this).remove();
return false;
}
},
close: function (event, ui) {
$(this).remove();
}
});
};
})
But my code run that ajax request without waiting for the response of ConfirmDialog(message) function. How can I force it to wait?
You have 2 functions which get triggered depending on which confirm button is selected. Handle your ajax code from there.
I liked how Abhijit's answer abstracted out the code, but I think he missed something.
$(function() {
$(document).on('click', '.fa-times', function(e) {
e.stopPropagation();
function getConfirmHandler(element){
return function handleConfirm(result) {
if (result) {
return false
}
var row = element.closest('tr');
row.css('opacity', '0.3');
var word = element.closest('td').siblings('.word').text();
$.ajax({
url: '../../te_addStopWord',
type: 'GET',
data: {
word: word
},
dataType: 'JSON',
success: function() {
row.remove();
}, // success
error: function($a, $b, $c) {
alert($b);
row.css('opacity', '1');
}
}); // ajax
}
}
ConfirmDialog('Are you sure?', getConfirmHandler($(this)))
});
function ConfirmDialog(message, callback) {
$('<div></div>').appendTo('body')
.html('<div><h6>' + message + '?</h6></div>')
.dialog({
modal: true,
title: 'Delete message',
zIndex: 10000,
autoOpen: true,
width: 'auto',
resizable: false,
buttons: {
Yes: function() {
$(this).remove();
callback(true);
},
No: function() {
$(this).remove();
callback(false);
}
},
close: function(event, ui) {
$(this).remove();
}
});
};
})
Try move ajax into your ConfirmDialog:yesfunction. Or Try to use promise.
buttons: {
Yes: function () {
var row = $(this).closest('tr');
row.css('opacity','0.3');
var word = $(this).closest('td').siblings('.word').text();
$.ajax({
url : '../../te_addStopWord',
type : 'GET',
data: {word : word},
dataType : 'JSON',
success : function () {
row.remove();
}, // success
error : function ($a,$b,$c) {
alert($b);
row.css('opacity','1');
}
}); // ajax
$(this).remove();
return true;
},
No: function () {
$(this).remove();
return false;
}
},

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

JQuery UI Dialog and duplicated form elements

I am using a JQuery UI Dialog and the ajax submit plugin from malsup.com.
The issue is that the UI Dialog (I believe that is the culprit) is duplicating the fields of the form. It would not be such an issue except that this form is for uploading multiple files. The form uses a DataTable.
Apart from the duplicating fields the process is fine.
I am not re-using the dialog, which would duplicate the fields (see this )
The page gets the form and submits it through ajax: here is the code:
function smxTableDialogForm ( aURL, tableId, row ) {
var lData = "";
var lURL = aURL.split("?");
var lDialog;
if (lURL.length == 2){
lData = lURL[1];
lURL = lURL[0]
};
$.ajax({
type: "POST",
url: lURL,
data: lData,
dataType: "json"
}).
done( function(response){
if ( response.success ){
lDialog = $("<div></div>").dialog( {
height: "auto",
maxHeight: 800,
width: 750,
autoOpen: false,
buttons: [
{ text: "Save",
icons: {primary: "ui-icon-check" },
click: function () {
smxAjaxSubmit(response.formid);
$(this).dialog("close");
}
},
{ text: "Cancel",
icons: {primary: "ui-icon-close"},
click: function() {
$(this).dialog("close");
}
}],
close: function (event, ui) {
$(this).remove();
},
resizable: false,
modal: true
});
lDialog.html(response.content);
lDialog.dialog("open");
}
else {
$.alert(response.message, response.title);
};
}).
fail( function(jqXHR, textStatus, errorThrown) {
$.alert("Sorry, no info to display.", "oops");
});
};
function smxAjaxSubmit (aFormId) {
$("#" + aFormId).ajaxSubmit({
dataType: "json",
beforeSend: function(){
$.blockUI({ message: '<h3><img src="/sysimages/ajaxloader.gif" /> Just a moment...</hr>' });
},
complete: function(){
$.unblockUI();
},
success: function(response) {
alert(response);
},
error: function(jqXHR, textStatus, errorThrown) {
$.alert("Problem. status: " + textStatus + "; error: " + errorThrown, "oops");
}
});
};
Any ideas gratefully received. Thanks.

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

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

Categories

Resources