AJAX drag and drop - javascript

I have created an AJAX drag and drop file upload form. But when the upload is complete it shows file upload done. But I want it to be redirected to another page. How can I do this?
This is my code
function sendFileToServer(formData,status)
{
var uploadURL ="upload.php"; //Upload URL
var extraData ={}; //Extra Data.
var jqXHR=$.ajax({
xhr: function()
{
var xhrobj = $.ajaxSettings.xhr();
if (xhrobj.upload)
{
xhrobj.upload.addEventListener('progress', function(event)
{
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable)
{
percent = Math.ceil(position / total * 100);
}
status.setProgress(percent);
}, false);
}
return xhrobj;
},
url: uploadURL,
type: "POST",
contentType:false,
processData: false,
cache: false,
data: formData,
success: function(data){
status.setProgress(100);
$("#status1").append("File upload Done<br>");
}
});
status.setAbort(jqXHR);
}

To redirect to another page, use window.location.
window.location = "http://www.yoururl.com";

Related

AJAX PHP JavaScript code not running on Iphone or Ipad

I have javascript file which uses some AJAX post requests, basically the file is linked to a submit button on a form on my site, when the form is submitted it then takes the form data and uses the inputs to edit a svg file using xml then saves it to the server as a png and then sends it with an email to the user.
My problem is that it works perfect on windows desktop and on andriod (kindle) but when i try to use it on iphone or ipad it executes the ajax php post requests for making the image (piechart.php) and mailing it (mail.php) but doesnt execute the code to save the file to the server (upload.php), which means all the emails are being sent without the image.
I ran MIH Tool on my Iphone and it came back with no errors but this is where i found that the upload.php wasnt being executed
Here is the js file:
$(document).ready(function(){
$(document).on('click', '.resetForm', function(event) {
event.preventDefault();
/* Act on the event */
location.reload();
});
function base64ToBlob(base64, mime)
{
mime = mime || '';
var sliceSize = 1024;
var byteChars = window.atob(base64);
var byteArrays = [];
for (var offset = 0, len = byteChars.length; offset < len; offset += sliceSize) {
var slice = byteChars.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
return new Blob(byteArrays, {type: mime});
}
// FUNCTION MAKING CANVAS WITH SVG
function drawInlineSVG(ctx, rawSVG, callback)
{
var svg = new Blob([rawSVG], {type:"image/svg+xml;charset=utf-8"}),
domURL = self.URL || self.webkitURL || self,
url = domURL.createObjectURL(svg),
img = new Image;
img.onload = function () {
ctx.drawImage(this, 0, 0);
domURL.revokeObjectURL(url);
callback(this);
};
img.src = url;
}
//****************************************
function jim(){
var svgText = document.getElementById("myViewer").outerHTML;
var myCanvas = document.getElementById("canvas");
var ctxt = myCanvas.getContext("2d");
// FUNCTION TO SET ENCODED SVG TEXT IN INPUT
drawInlineSVG(ctxt, svgText, function() {
//lamba url
shorternUrl = canvas.toDataURL("image/png");
shorternUrl = shorternUrl.replace(/^data:image\/(png|jpg);base64,/, "");
var blob = base64ToBlob(shorternUrl, 'image/png');
var formData = new FormData();
formData.append('encodeURL', blob);
$.ajax({
url:"upload.php",
type: "POST",
cache: false,
contentType: false,
processData: false,
data: formData})
.done(function(e){
$(".successMessageWrap").html('<div class="successMessageWrapTable"><div class="successMessage"><a class="resetForm" href="index.php"><i class="fa fa-close"></i></a><img src="images/logo.png"><h2>Thanks for using <span>Wheel of Life</span></h2><p>A copy of your wheel of life has been sent into your Email Id</p>Make New</div></div>');
});
/*success: function(data)
{
$(".successMessageWrap").html('<div class="successMessageWrapTable"><div class="successMessage"><a class="resetForm" href="index.php"><i class="fa fa-close"></i></a><img src="images/logo.png"><h2>Thanks for using <span>Wheel of Life</span></h2><p>A copy of your wheel of life has been sent into your Email Id</p>Make New</div></div>');
}*/
});
}
//***************************
$('form').submit(function(e){
e.preventDefault();
//
if(check_radio('PhysicalRank','Physical Environment')==false){return false; }
if(check_input('EnyInput','Physical Environment')==false){return false;}
if(check_radio('BussinessRank','Business/Career')==false){return false; }
if(check_input('BussinessInput','Business/Career')==false){return false;}
if(check_radio('financeRank','Finances')==false){return false; }
if(check_input('FinanceInput','Finances')==false){return false;}
if(check_radio('HealthRank','Health')==false){return false; }
if(check_input('HealthInput','Health')==false){return false;}
if(check_radio('FFRank','Family & Friends')==false){return false; }
if(check_input('FFInput','Family & Friends')==false){return false;}
if(check_radio('RelationRank','Romance/ Relationships')==false){return false; }
if(check_input('RelationInput','Romance/ Relationships')==false){return false;}
if(check_radio('GrowthRank','Personal Growth')==false){return false; }
if(check_input('GrothInput','Personal Growth')==false){return false;}
if(check_radio('FunRank','Fun & Recreation')==false){return false; }
if(check_input('FunInput','Fun & Recreation')==false){return false;}
if(check_input('name','Name')==false){return false;}
if(check_input('email','Email')==false){return false;}
//diable submit
$("input#WheelSubmit").attr('type', '');
$("input#WheelSubmit").attr('disabled', 'disabled');
$(".successMessageWrap").fadeIn();
//AJAX
$.ajax({
url:"piechart.php",
type:"POST",
data:new FormData(this),
contentType: false,
processData:false,
cache:false,
success: function(data)
{
$(".piechartSvg").html(data);
jim();
}
});
//*************************
//AJAX
$.ajax({
url:"mail.php",
type:"POST",
data:new FormData(this),
contentType: false,
processData:false,
cache:false,
success: function(data)
{
$("#test").html(data);
}
});
});
});//main
I have been working it this for days and cant understand why it is only that part that isn't executing on iOs devices even using chrome on iphone doesn't work either
If anyone could help that would be great thanks

Progress Bar in ajax while uploading 2 files or more

Hi Im trying to upload a 2 file or more, my problem is my progress bar will say 100% because of the small file being uploaded first, then its going back to the percent of the large file.. My question is how can I have a same progress if i have many files being uploaded?
$('body').on('change', 'input:file.gallery_images', function(event)
{
event.preventDefault();
var data = new FormData();
data.append('id', $("#id").val());
var count = $(this)[0].files.length;
$.each($(this)[0].files, function(i, file)
{
data.append('userfile', file);
$.ajax(
{
type: "POST",
url: href+path+"/imagens/store",
data: data,
mimeType: 'multipart/form-data',
contentType: false,
cache: false,
processData: false,
dataType: "json",
xhr: function()
{
var _xhr = $.ajaxSettings.xhr();
_xhr.addEventListener('progress', function (event) { }, false);
if (_xhr.upload)
{
_xhr.upload.onprogress = function(event)
{
var percent = 0;
if (event.lengthComputable)
{
var position = event.position || event.loaded;
var total = event.totalSize || event.total;
percent = Math.ceil(position / total * 100);
}
$("#progress-bar").width(percent + '%');
};
}
return _xhr;
},
beforeSend: function()
{
$("#progress").fadeIn('slow');
$("#progress-bar").width('0%');
},
success: function(data)
{
if(data.gallery)
{
if($(".alert").length > 0)
{
$(".alert").hide('slow').remove();
$("#droppable").show('slow');
}
$('.gallery').fadeTo('300', '0.5', function () {
$(this).html($(this).html() + data.gallery).fadeTo('300', '1');
});
}
$("#progress").fadeOut('slow');
}
});
});
});
Ok, first thing I noticed is that you're adding the file to the 'data' variable inside your $.each... but that means the first POST contains the first image, the second POST contains the first and the second, and so on. I think you should this part inside your $.each:
var data = new FormData();
data.append('id', $("#id").val());
Ok, so, to solve your problem: Before sending anything, go through them and sum their size. You'll also need to store the progress for each file individually, so start it as zero:
var sumTotal = 0;
var loaded = [];
for (var i = 0, list = $(this)[0].files; i < list.length; i++) {
sumTotal += list[i].size;
loaded[i] = 0;
}
Inside your onprogress, instead of comparing the event.position with the event.totalSize, you'll store this position on your 'loaded' array, sum all your array, and then compare it to your sumTotal.
loaded[i] = event.position || event.loaded;
var sumLoaded = 0;
for (var j = 0; j < loaded.length; j++) sumLoaded += loaded[j];
percent = Math.ceil(sumLoaded * 100/sumTotal);
;)

Upload progress bar inside modal not working when ajax call

I have page where drag and drop upload works , When drag and dropped it opens a modal which has progress bar. The drag and drop functionality works well. When the file is dropped the modal is opened but the progress bar doesn't seem to increase at all. Even after the success response of the ajax call the the progress bar is still the same.
<div class="modal-body">
<div class="progress">
<div class="bar"></div >
<div class="percent">0%</div >
</div>
<div id="status"></div>
</div>
Here is my Jquery
$("html").on("drop", function(e) {
e.preventDefault();
e.stopPropagation();
$('#myModal').modal('show');
var dt = e.dataTransfer || (e.originalEvent && e.originalEvent.dataTransfer);
var files = e.target.files || (dt && dt.files);
if (files) {
for(var i = 0; i<e.originalEvent.dataTransfer.files.length;i++){
var file_ext = e.originalEvent.dataTransfer.files[i].name.split('.').pop();
console.log(file_ext);
if ((file_ext == 'pdf') || (file_ext == 'docx') || (file_ext == 'txt')) {
console.log('right file');
var resume = e.originalEvent.dataTransfer.files[i];
var resume_name = resume.name;
console.log(resume_name);
var form_data = new FormData();
form_data.append("resume",resume);
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$.ajax({
url : '/resume_upload',
type : 'POST',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
mimeType: "multipart/form-data",
data : form_data,
beforeSend: function() {
$('#myModal').modal('show');
status.empty();
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal);
percent.html(percentVal);
},
success : function(data) {
$('#myModal').modal('hide');
console.log(data.msg);
//alert(data.msg);
},
processData : false,
contentType : false,
error : function(xhr ,status ,error){
console.log(xhr);
alert(xhr);
}
});
}
And how do i create multiple progress divs when more than one file is dropped.

how to run the following function jquery with a button?

The truth is that very little jquery, and I have the following jquery code with django and what it does is this.
to select the file:
<input id="chunked_upload" type="file" name="the_file">
the following jquery code is automatically executed
<script type="text/javascript">
var md5 = "",
csrf = $("input[name='csrfmiddlewaretoken']")[0].value,
form_data = [{"name": "csrfmiddlewaretoken", "value": csrf}];
function calculate_md5(file, chunk_size) {
var slice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
chunks = chunks = Math.ceil(file.size / chunk_size),
current_chunk = 0,
spark = new SparkMD5.ArrayBuffer();
function onload(e) {
spark.append(e.target.result); // append chunk
current_chunk++;
if (current_chunk < chunks) {
read_next_chunk();
} else {
md5 = spark.end();
}
};
function read_next_chunk() {
var reader = new FileReader();
reader.onload = onload;
var start = current_chunk * chunk_size,
end = Math.min(start + chunk_size, file.size);
reader.readAsArrayBuffer(slice.call(file, start, end));
};
read_next_chunk();
}
$("#chunked_upload").fileupload({
url: "{% url 'api_chunked_upload' %}",
dataType: "json",
maxChunkSize: 100000, // Chunks of 100 kB
formData: form_data,
add: function(e, data) { // Called before starting upload
$("#messages").empty();
// If this is the second file you're uploading we need to remove the
// old upload_id and just keep the csrftoken (which is always first).
form_data.splice(1);
calculate_md5(data.files[0], 100000); // Again, chunks of 100 kB
data.submit();
},
chunkdone: function (e, data) { // Called after uploading each chunk
if (form_data.length < 2) {
form_data.push(
{"name": "upload_id", "value": data.result.upload_id}
);
}
$("#messages").append($('<p>').text(JSON.stringify(data.result)));
var progress = parseInt(data.loaded / data.total * 100.0, 10);
/*$("#progress").text(Array(progress).join("=") + "> " + progress + "%");*/
$('#progress .progress-bar').css('width',progress + '%');
$('#progress .progress-bar').css('aria-valuenow',progress + '%');
},
done: function (e, data) { // Called when the file has completely uploaded
$.ajax({
type: "POST",
url: "{% url 'api_chunked_upload_complete' %}",
data: {
csrfmiddlewaretoken: csrf,
upload_id: data.result.upload_id,
md5: md5
},
dataType: "json",
success: function(data) {
$("#messages").append($('<p>').text(JSON.stringify(data)));
}
});
},
});
</script>
this code upload the file into several pieces with a progress bar. The problem is that I want the code to run only if I click a button to load and not how.
I tried as follows:
<input id="chunked_upload" type="file" name="the_file">
<button id="enviar">Enviar</button>
<script type="text/javascript">
var md5 = "",
csrf = $("input[name='csrfmiddlewaretoken']")[0].value,
form_data = [{"name": "csrfmiddlewaretoken", "value": csrf}];
function calculate_md5(file, chunk_size) {
var slice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
chunks = chunks = Math.ceil(file.size / chunk_size),
current_chunk = 0,
spark = new SparkMD5.ArrayBuffer();
function onload(e) {
spark.append(e.target.result); // append chunk
current_chunk++;
if (current_chunk < chunks) {
read_next_chunk();
} else {
md5 = spark.end();
}
};
function read_next_chunk() {
var reader = new FileReader();
reader.onload = onload;
var start = current_chunk * chunk_size,
end = Math.min(start + chunk_size, file.size);
reader.readAsArrayBuffer(slice.call(file, start, end));
};
read_next_chunk();
}
$('button#enviar').click(function(){
$("#chunked_upload").fileupload({
url: "{% url 'api_chunked_upload' %}",
dataType: "json",
maxChunkSize: 100000, // Chunks of 100 kB
formData: form_data,
add: function(e, data) { // Called before starting upload
$("#messages").empty();
// If this is the second file you're uploading we need to remove the
// old upload_id and just keep the csrftoken (which is always first).
form_data.splice(1);
calculate_md5(data.files[0], 100000); // Again, chunks of 100 kB
data.submit();
},
chunkdone: function (e, data) { // Called after uploading each chunk
if (form_data.length < 2) {
form_data.push(
{"name": "upload_id", "value": data.result.upload_id}
);
}
$("#messages").append($('<p>').text(JSON.stringify(data.result)));
var progress = parseInt(data.loaded / data.total * 100.0, 10);
/*$("#progress").text(Array(progress).join("=") + "> " + progress + "%");*/
$('#progress .progress-bar').css('width',progress + '%');
$('#progress .progress-bar').css('aria-valuenow',progress + '%');
},
done: function (e, data) { // Called when the file has completely uploaded
$.ajax({
type: "POST",
url: "{% url 'api_chunked_upload_complete' %}",
data: {
csrfmiddlewaretoken: csrf,
upload_id: data.result.upload_id,
md5: md5
},
dataType: "json",
success: function(data) {
$("#messages").append($('<p>').text(JSON.stringify(data)));
}
});
},
});
})
The problem I have to do with this method is that:
I must first click and then I select the file.
and should be reversed where must first select the file and then click to work.
need councils how to do it please
Create a Button into your template and replace:
data.submit();
by:
$("#SubmitButtonid").off('click').on('click', function () {
data.submit();
});

How to get whole data out of callback function in javascript

I have written following function which takes a json data from a url.
function getWeatherDataForCities(cityArray){
var arrAllrecords = [];
var toDaysTimestamp = Math.round((new Date()).getTime() / 1000) - (24*60*60);
for(var i in cityArray){
for(var j=1; j<=2; j++){
var jsonurl = "http://api.openweathermap.org/data/2.5/history/city?q="+cityArray[i]+"&dt="+toDaysTimestamp;
$.ajax({
url: jsonurl,
dataType: "jsonp",
mimeType: "textPlain",
crossDomain: true,
contentType: "application/json; charset=utf-8",
success: function(data){
arrAllrecords[j]["cityName"] = data.list[0].city.name;
arrAllrecords[j]["weather"] = data.list[0].weather[0].description;
} });
toDaysTimestamp = toDaysTimestamp - (24*60*60);
}
}
return arrAllrecords; //returning arrAllrecords
}
$(document ).ready(function() {
var cityArray = new Array();
cityArray[0] = "pune";
var arrAllRecords = getWeatherDataForCities(cityArray);
//Print All records returned by getWeatherDataForCities(cityArray);
});
I have written some comments in above code.I have called getWeatherDataForCities function which returns all records from url.I have declared getWeatherDataForCities array in function.I want to add all returned records in that array.I have tried as above but nothing is getting into array.
In console showing j and arrAllrecords are undefined.
How to get all records in array from callback function?
you response will be highly appreciated
Your getWeatherDataForCities function won't return anything because ajax operations are asynchronous. You need to use a callback for that.
Modify your function to accept a callback function:
function getWeatherDataForCities(cityArray, callback){
var arrAllrecords = [];
var toDaysTimestamp = Math.round((new Date()).getTime() / 1000) - (24*60*60);
for(var i in cityArray){
for(var j=1; j<=2; j++){
var jsonurl = "http://api.openweathermap.org/data/2.5/history/city?q="+cityArray[i]+"&dt="+toDaysTimestamp;
$.ajax({
url: jsonurl,
dataType: "jsonp",
mimeType: "textPlain",
crossDomain: true,
contentType: "application/json; charset=utf-8",
success: function(data){
arrAllrecords[j]["cityName"] = data.list[0].city.name;
arrAllrecords[j]["weather"] = data.list[0].weather[0].description;
// call the callback here
callback(arrAllrecords);
}
});
toDaysTimestamp = toDaysTimestamp - (24*60*60);
}
}
}
And use it like this:
$(document ).ready(function() {
var cityArray = new Array();
cityArray[0] = "pune";
getWeatherDataForCities(cityArray, function(arrAllrecords) {
// Do something with your data
});
});
You are trying to use the empty array. When fetching the values it will always return you undefined.
var arrAllrecords = [];
arrAllrecords[2]; //undefined
arrAllrecords[2]["cityname"]; //undefined
Better you should use array of objects.
I don't know why you have used variable j. The below code works for me.
var arrAllrecords = [];
function getWeatherDataForCities(cityArray){
var toDaysTimestamp = Math.round((new Date()).getTime() / 1000) - (24*60*60);
for(var i in cityArray){
var jsonurl = "http://api.openweathermap.org/data/2.5/history/city?q="+cityArray[i]+"&dt="+toDaysTimestamp;
$.ajax({
url: jsonurl,
dataType: "jsonp",
mimeType: "textPlain",
crossDomain: true,
contentType: "application/json; charset=utf-8",
success: function(data){
arrAllrecords.push({
"cityName" : data.list[0].city.name,
"weather" : data.list[0].weather[0].description
});
if(arrAllrecords.length === cityArray.length) {
callback(arrAllrecords);
}
} });
}
}
function callback(arrAllrecords) {
console.log(arrAllrecords);
}
$(document).ready(function() {
var cityArray = new Array();
cityArray[0] = "pune";
cityArray[1] = "mumbai";
cityArray[2] = "delhi";
getWeatherDataForCities(cityArray);
});

Categories