AJAX PHP JavaScript code not running on Iphone or Ipad - javascript

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

Related

Is it possible to store base64 of a file in javascript object and send it to backend using ajax?

I am just trying to upload image file in base64 format by storing it in a js object. But the problem here is the object property 'baseData' doesn't fill with the DataURL of the image. If the way I mentioned below is possible, please suggest the solution to fill the 'baseData' property.
What I am doing is storing the 'type' (image or video, not extensions) and DataURL of the file in the object(fileDataObject) and pushing the object to an array(blobData), and returning the same at the end of the function.
Thanks in advance
var filesAccept = filesValidator($("#file-upload")[0].files);
if(filesAccept !== false){
var fd = new FormData();
fd.append("files", filesAccept)
$.ajax({
type: "POST",
url: "receiver.php",
data: fd,
processData: false,
contentType: false,
dataType: "text",
success: function (result) {
console.log(result);
},
});
}
function filesValidator(f) {
if (f.length === 0) {
$("#error-info").text("Please select some images or videos.");
return false;
} else if(f.length !== 0) {
var blobData = [];
var fileType;
$("#error-info").text("");
var n = 10;
if (f.length < 10) {// checking if files count less than 10
n = f.length;
}
for (let i = 0; i < n; i++) {
var reader = new FileReader();
fileType = f[i].type.split("/");
if(fileType[1] === "gif"){
return false;
} else if (fileType[0] === "image") {// if file is images
reader.onload = function(e) {
var src = e.target.result.split(",")[1];
console.log(src);
var fileDataObject = {
baseData : src,
type : "image"
};
blobData.push(JSON.stringify(fileDataObject));
}
reader.readAsDataURL(f[i]);
} else if(fileType[0] === "video") { //if file is video
reader.onload = function(e) {
var src = e.target.result.split(",")[1];
var fileDataObject = {
baseData : src,
type : "video"
};
blobData.push(JSON.stringify(fileDataObject));
}
reader.readAsDataURL(f[i]);
}
console.log(blobData);
}
return blobData;
}
}

Spring/Javascript: Send canvas image as a MultipartFile using AJAX

I'm trying to send my canvas image to controller. I tried using ajax but it doesn't seem to work. Hope you can help me. This is my code.
function takeSnapshot() {
var video = document.querySelector('video')
, canvas;
var img = document.querySelector('img') || document.createElement('img');
var context;
var width = video.offsetWidth
, height = video.offsetHeight;
canvas = canvas || document.createElement('canvas');
canvas.width = width;
canvas.height = height;
context = canvas.getContext('2d');
context.drawImage(video, 0, 0, width, height);
img.src = canvas.toDataURL('image/png');
document.body.appendChild(img);
var dataURL = canvas.toDataURL('image/png');
var blob = dataURItoBlob(dataURL);
var fd = new FormData(document.forms[0]);
fd.append("uploadfile", blob, "test");
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "/api/file/upload",
data: fd,
processData: false, //prevent jQuery from automatically transforming the data into a query string
contentType: false,
cache: false,
success: (data) => {
alert("shit");
},
error: (e) => {
alert("error");
}
});
}
function dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type:mimeString});
}
And this is my controller that receives the submitted image.
#PostMapping("/api/file/upload")
public String uploadMultipartFile(#RequestParam("uploadfile") MultipartFile file) {
try {
fileStorage.store(file);
return "File uploaded successfully! -> filename = " + file.getOriginalFilename();
} catch (Exception e) {
return "Error -> message = " + e.getMessage();
}
}
I tried setting the value of input file type mannually but others said that it may lead to security problems. And I also I can't make it work. I want to do direct image capturing and save the image to server. I'm using spring and hibernate. Hoping you could help me. Thank you !!

AJAX drag and drop

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";

Safari browsers sends blob/datauri as string in Node.js

I am trying to receive the file sent through AJAX. What's happening is that when the file sent using Chrome/Firefox the file goes to req.files but when it was sent using Safari, the file goes to req.params. The application treat the file as a string "[Object blob]". Thanks.
Sending userdata through ajax.
updatePartnerProfile: function(obj){
var parentObj = this;
var target = $(obj.target);
var parent = target.closest('#editPartnerDetailsForm');
var logoImg = parent.find('.cropped');
var companyLogoBase64 = logoImg.find('.croppedImage').attr('src');
var companyLogo = util.dataURItoBlob(companyLogoBase64);
var userData = new FormData();
userData.append('token', parentObj.token);
userData.append('companyLogo', companyLogo);
$.ajax({
type: 'POST',
url: parentObj.serverUrl + 'api/admin/update/organization/' + parentObj.partnerId,
processData: false,
contentType: false,
cache: false,
data: userData,
success: function(data){
//todo
}
},
error: function(err){
console.log(err);
}
});
},
dataURItoBlob : function(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
if (!_.isUndefined(dataURI)){
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type:mimeString});
} else {
return null;
}
}
Am I missing something in the code?
Well, as per this question, you need to be using the buffer property of ia, not just [ia]. Instead of
return new Blob([ia], {type:mimeString});
try
return new Blob([ia.buffer], {type:mimeString});

Why does Chrome and Firefox crash while uploading a file larger than 30 MB?

I am trying to upload a file on the server in my angularjs app. The file is upload in base64 string format. The things work fine when the file size is less than 30 MB but the browsers (both chrome and firefox) crash when he file size is more than 30 MB. The browsers crash before the post request is made.
Here is the code of my controller for uploading the file:
$scope.addMyFile = function(t,pid,id,week,day) {
$("#upload"+t+pid+id).each(function() {
var $input = $(this);
var inputFiles = this.files;
if(inputFiles == undefined || inputFiles.length == 0) return;
var inputFile = inputFiles[0];
var inputFileSize = inputFile.size;
var reader = new FileReader();
reader.onload = function(event) {
var dataString = event.target.result;
var firstPart = dataString.split(',')[0];
var secondPart = dataString.split(',')[1];
dataString = secondPart;
var fileName = inputFile.name;
var fileExtension = firstPart.split('/')[1].split(';')[0];
reader.readAsDataURL(inputFile);
});
};
UploadMyFile Function:
$scope.uploadFile = function(type,week,day,fileName,fileExtension,dataString) {
$scope.loading = true;
$scope.uploadBar = true;
var fileUploadUrl = serverURL;
var request = $http({
method: "POST",
url: fileUploadUrl,
headers: { 'Accept' :'application/json','Content-Type' :'application/json', authToken:userauthToken, 'Accept-Language': 'en'},
data: { name : fileName, documentString:dataString, extension: fileExtension}
});
request.success(
function(data) {
$scope.uploadStatus = data.status;
$scope.getWeekList(type);
$scope.uploadBar = false;
alert('The file has been successfully uploaded.');
});
$scope.loading = false;
request.error(
function(data, status) {
console.log(status);
$scope.uploadStatus = data.status || "Request failed";
alert('The file could not be uploaded. Please try again.');
});
};

Categories