download PDF file with ajax and function call in jQuery - javascript

I am trying to download the file using this function but I am not able to execute the function after first ajax success. I read other resources but it was not helpful, I am trying to achieve this from 2 days and regularly searching nothing happend.
Please helpme to create this function after first success response it will call the function as DownloadFile();
I am returning these array in the first success response -
current no any error showing only the first success response show and downlaodfile() function not run.
filename: "PO_21-22_0166.pdf"
path: "./folder/myfilename.pdf"
responseCode: "200"
status: "success"
Please help me, how I make it correct so I can download the file with the help of my created own code.
Where I am doing mistake and how it will after fix.
$.ajax({
cache: false,
type: "POST",
url: "example.com",
cache: false,
success: function(response) {
if (response.responseCode == '200') {
var fileName = response.filename;
var myurl = response.path;
function DownloadFile(fileName) {
//var myurl = response.path;
$.ajax({
url: myurl,
cache: false,
xhr: function() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 2) {
if (xhr.status == 200) {
xhr.responseType = "blob";
} else {
xhr.responseType = "text";
}
}
};
return xhr;
},
success: function(data) {
//Convert the Byte Data to BLOB object.
var blob = new Blob([data], {
type: "application/octetstream"
});
//Check the Browser type and download the File.
var isIE = false || !!document.documentMode;
if (isIE) {
window.navigator.msSaveBlob(blob, fileName);
} else {
var url = window.URL || window.webkitURL;
link = url.createObjectURL(blob);
var a = $("<a />");
a.attr("download", fileName);
a.attr("href", link);
$("body").append(a);
a[0].click();
$("body").remove(a);
}
},
});
}
} else {
alert(response.message);
return false;
}
},
});

Related

AJAX PHP 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
Apple browsers has some nasty bug due to which the browser doesn't refresh javascript again the solution is that you move your code to
$(document).ready(function(){
}
Try it and let me know if that solves your problem
can you also try this
$.ajax({
url:"piechart.php",
type:"POST",
data:new FormData(this),
contentType: false,
processData:false,
cache:false,
success: function(data)
{
$(".piechartSvg").html(data);
beforeSend: function (event, files, index, xhr, handler, callBack) {
jim();
},
}
});
Here I have added a "before send" block in the final Ajax request try it and let me know

JS The downloaded archive throws "the archive is either unknown format or damaged"

I keep getting the problem with downloaded zip file. All the time when I click on the archive it throws "Archive is either unknown format or damaged". I think the problem is with the coding (format of the content of the archive). Please help!
$.ajax({
url: '/Unloading/' + $("#radioVal:checked").val(),
type: "POST",
data: { 'dateTimeTo': $("#dateTimeTo").val(), 'dateTimeFrom': $("#dateTimeFrom").val() },
beforeSend: function() {$("#divLoading").show();},
success: function (result) {
$("#divLoading").hide();
if (result.length === 0) {
var message ="Error";
$("#dialog-message").text(message);
$("#dialog-message").dialog({
modal: true,
buttons: {
close: function() {
$(this).dialog("close");
}
}
});
} else {
var xmlstr, filename, bb;
filename = "UnloadedLeases.zip";
bb = new Blob([result], { type: "application/zip" }); // I think somewhere here is a problem with the coding
var pom = document.createElement('a');
pom.setAttribute("target", "_blank");
pom.setAttribute('href', window.URL.createObjectURL(bb));
pom.setAttribute("download", filename);
document.body.appendChild(pom);
pom.click();
document.body.removeChild(pom); //removing the element a from the page
}
},
As far as I know, $.ajax doesn't let you download binary content out of the box (it will try to decode your binary from UTF-8 and corrupt it). Either use a jQuery plugin (like jquery.binarytransport.js) or use a xhr directly (with responseType).
$.ajax({
url: '/Unloading/' + $("#radioVal:checked").val(),
type: "POST",
dataType: 'binary', // using jquery.binarytransport.js
// ...
success: function (result) {
// Default response type is blob
if (result.size === 0) { // instead of length for blobs
// ...
} else {
var bb = result; // already a blob
// ...
}
}
})

Send Webm buffer to php server

I'm recording video and audio from the browser using MediaRecorder. After I finish recording I try to upload it to the server with something like this:
function upload() {
var fileName = 'video.webm';
var formData = new FormData();
formData.append('filename', fileName);
formData.append('blob', blobs);
$.ajax({
type: 'POST',
url: '/upload.php',
data: formData,
processData: false,
contentType: false
}).done(function(data) {
console.log(data);
});
xhr('upload.php', formData, function (fName) {
window.open(location.href + fName);
});
function xhr(url, data, callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
alert('Done');
}
};
request.open('POST', url);
request.send(data);
}
}
Apparently the $_FILES variable doesn't get set in php, but the $_POST does. The file name has been passed correctly, but if I output the blobs to a file, I'm not able to reproduce the file in an html5 video object, so I guess something is wrong with that.
Could anyone explain what's the best way to accomplish this upload?
Thanks

image not uploaded after calling upload function in ajax

I'm working on an image upload form which will validate if the uploaded picture contain nudity with the help of nudejs script.
If the image doesn't contain nudity it will be uploaded.
The upload and check nudity function are working great, but the problem is that i didn't find a way to link these 2 methods since the return of the check nudity function "onImageClick()" come 'undefined' so i can't check if its true or false in order to call the upload function via $.ajax.
This is the code:
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
//return onImageClick('previewing'); //previewing is the id of the image in my html file
//if(onImageClick('previewing')) return;
var rn = onImageClick('previewing');
console.log("rn: "+rn); //always get undefined
$("#message").empty();
$('#loading').show();
$.ajax({
url: "ajax_php_file.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data) {
$('#loading').hide();
$("#message").html(data);
}
});
}));
// Function to preview image after validation
$(function() {
$("#file").change(function() {
$("#message").empty(); // To remove the previous error message
var file = this.files[0];
var imagefile = file.type;
var match = ["image/jpeg","image/png","image/jpg"];
if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2]))) {
$('#previewing').attr('src','no-preview.png');
$("#message").html("<p id='error'>Please Select A valid Image File</p>"+"<h4>Note</h4>"+"<span id='error_message'>Only jpeg, jpg and png Images type allowed</span>");
return false;
}
else
{
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
});
});
function imageIsLoaded(e) {
$("#file").css("color","green");
$('#image_preview').css("display", "block");
$('#previewing').attr('src', e.target.result);
$('#previewing').attr('width', '250px');
$('#previewing').attr('height', '230px');
};
//check nudity function
function onImageClick(node) {
nude.load(node);
// Scan it
nude.scan(function(result){
console.log(result ? "Nudity found in " + node + "!" : "Not nude");
console.log("returned value is:",result);
return result;
});
}
});
EDIT: I edit the code based on #Amir answer where he mention an important point i didn't notice before.
Now i can fire the upload function when there is no nudity, but the image didn't uploaded even the success function in ajax call is fired:
success: function(data)
{
$('#loading').hide();
$("#message").html(data);
}
This is the new code:
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
//call check nudity function
onImageClick('previewing');
//check nudity function
function onImageClick(node) {
nude.load(node);
// Scan it
nude.scan(function(result){
console.log(result ? "Nudity found in " + node + "!" : "Not nude");
console.log("returned value is:",result);
if(result){
alert("conatain nudity!!");
}
else{
$("#message").empty();
$('#loading').show();
$.ajax({
url: "ajax_php_file.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$('#loading').hide();
$("#message").html(data);
}
});
}
});
};
}));
// Function to preview image after validation
$(function() {
$("#file").change(function() {
$("#message").empty(); // To remove the previous error message
var file = this.files[0];
var imagefile = file.type;
var match= ["image/jpeg","image/png","image/jpg"];
if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2])))
{
$('#previewing').attr('src','no-preview.png');
$("#message").html("<p id='error'>Please Select A valid Image File</p>"+"<h4>Note</h4>"+"<span id='error_message'>Only jpeg, jpg and png Images type allowed</span>");
return false;
}
else
{
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
});
});
function imageIsLoaded(e) {
$("#file").css("color","green");
$('#image_preview').css("display", "block");
$('#previewing').attr('src', e.target.result);
$('#previewing').attr('width', '250px');
$('#previewing').attr('height', '230px');
};
});
nude.scan is async so you should pass a callback.
something like:
nude.scan(function (result) { /* your logic according to the result */ })
I found a solution for this, the problem was with FormData, it was returning:
TypeError: Argument 1 of FormData.constructor does not implement interface HTMLFormElement. That is for some reason didn't appear in chrome console but it does in Firefox.
So i added this line of code in the else statement(in case nudity not found):
var form = $('form').get(0);
this code returns a jQuery object($('form')) and pass a HTML element to FormData (get(0)).
Then in ajax request: data: new FormData(form),
Hope that this solution help other people.

How to send a string along with file via ajax request to a php file?

I got a php file that saves file to server to a folder called upload it receives file via an ajax request every thing works fine so far the next requirement is to send a string along with the file to specify an upload folder & sub folder like "Course/Math" how to achieve that?
JS
$( document ).ready(function() {
$('#Upload').click(function(){
var formData = new FormData($('form')[0]);
$.ajax({
url: 'uploadFile.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progressHandling, false);
}
return myXhr;
},
success: completeHandler,
data: formData,
cache: false,
contentType: false,
processData: false
});
});
var progressHandling = function(e){
if(e.lengthComputable){
var percent = Math.round((e.loaded / e.total) * 100);
$('#uploadprogress').css('width', percent+'%');
}
}
var completeHandler = function(data){
$('#message').text(data);
$('#uploadprogress').css('width', '0%');
$('#file').val('');
};
});
PHP
<?php
if ($_FILES["file"]["error"] > 0) {
} else {
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo true;
}
?>
Sample Example of Sending form data in ajax call with .serialize()
var formData = $('#myform').serialize;
$.ajax({
url: 'uploadFile.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progressHandling, false);
}
return myXhr;
},
success: completeHandler,
data: formData,
cache: false,
contentType: false,
processData: false
});
If you want to add a string simply use like following:
var value = 'test';
var formData = $('#myform').serialize+"&newstring="+value;
Update
File upload is not possible through ajax.
You can upload file, without refreshing page by using IFrame or AjaxFileUpload Plugin.
Further Details here is Answer.
Also file some detail explanation here also:
jQuery Ajax File Upload
jQuery Upload Progress and AJAX file upload
You could use the HTML5 Upload element.
$("#FileUpload").change(function (e) {
var uploadFile = e.target.files;
if (uploadFile.length > 0) {
if (window.FormData !== undefined) {
var data = new FormData();
for (var x = 0; x < uploadFile.length; x++) {
data.append("file" + x, uploadFile[x]);
}
data.append("ELEMENTCLASSNAME", $("#ELEMENTID").val());
$.ajax({
type: "POST",
url: 'URL',
contentType: false,
processData: false,
data: data,
success: function (result) {
alert(result);
},
failure: function (result) {
alert(result);
},
error: function (xhr, status, p3, p4) {
var err = "Error " + " " + status + " " + p3 + " " + p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
console.log(err);
}
});
} else {
alert("This browser doesn't support HTML5 file uploads!");
}
}});
On the server side use the Request Object get the value:
var versionName = Request["ELEMENTCLASSNAME"];

Categories