image not uploaded after calling upload function in ajax - javascript

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.

Related

download PDF file with ajax and function call in jQuery

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

Uncaught TypeError: Cannot read property 'length' of undefined file upload Dropzone JS

I'm trying to upload a file, when an button is clicked. The issue is in the 2nd block of code
Dropzone.options.myDropzone = {
autoProcessQueue: false,
init: function () {
var submitButton = document.querySelector("#submit-all")
myDropzone = this;
submitButton.addEventListener("click", function () {
myDropzone.processQueue();
});
this.on("addedfile", function () {
});
}
};
Above is my create a new dropzone section, and down below is my logic.I get an error on my for loop. saying length is undefined.
$("#submit-all").click(function (e) {
$('#myPleaseWait').modal('show')
var fileUpload = $("#files").get(0);
var files = this.file;
var data = new FormData();
var _url = $(this).data('appcontroller');
for (var i = 0; i < files.length ; i++) { //Error is stopping here when upload button is pressed
data.append(files[i].name, files[i]);
}
$.ajax({
type: "POST",
url: _url,
contentType: false,
processData: false,
data: data,
success: function (message) {
$('#myPleaseWait').modal('hide');
alert(message);
},
error: function () {
$('#myPleaseWait').modal('hide');
alert("There was error uploading files!");
}
});
});
i've added a js fiddle with my html code https://jsfiddle.net/q47axhdf/2/
Any help would greatly appreciated
Like always found the answer after posting this. i removed .length from my file.length in the for loop and the upload works perfect.

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
// ...
}
}
})

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

Upload not working with Jquery xhr & Ajax

I have image upload function in my "form" which gets uploaded via ajax. So, until image is uploading, User continues to fill rest of form. and than click on submit button which is another ajax function to submit whole form.
Problem is I have below function for image upload :-
jQuery(window).load(function(){
jQuery(':button').click(function(){
var formData = new FormData(jQuery('form')[0]);
jQuery.ajax({
url: 'upload.php', //Server script to process data
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = jQuery.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//Ajax events
beforeSend: function(e) { $('#progress').css('display', 'block'); },
success: function(e) {
if (e != "no" && e != 'dir') {
$('#img').attr("src", e);
$('#imglinktosent').val(e);
} else if (e == 'dir') {
alert('Oops! We could not find \image\ directory or may be permission is not correct');
} else {
alert('File was not Uploaded, Kindly Upload Image with Size less than 512KB');
}
} ,
error: function(e) { alert('error' + e.message); } ,
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
});
function progressHandlingFunction(e){
if(e.lengthComputable){
$('progress').attr({value:e.loaded,max:e.total});
}
}
});//]]>
It was hindering my complete form submission, therefore i changed it into Below function.
function uploadimage(){
jQuery(':button').click(function(){
var formData = jQuery('#myfile').val();
jQuery.ajax({
url: 'upload.php', //Server script to process data
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = jQuery.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//Ajax events
beforeSend: function(e) { $('#progress').css('display', 'block'); },
success: function(e) {
if (e != "no" && e != 'dir') {
$('#img').attr("src", e);
$('#imglinktosent').val(e);
} else if (e == 'dir') {
alert('Oops! We could not find \image\ directory or may be permission is not correct');
} else {
alert('File was not Uploaded, Kindly Upload Image with Size less than 512KB');
}
} ,
error: function(e) { alert('error' + e.message); } ,
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
});
function progressHandlingFunction(e){
if(e.lengthComputable){
$('progress').attr({value:e.loaded,max:e.total});
}
}
}
So, that whenever user clicks on "upload image" button. Image will get uploaded by "uploadimage()" function set on "button" with event "onclick".
But PHP was giving error with "undefined index myfile" in upload.php
After searching for a while, i found, There was "request payload" and no formdata option in header.
After searching more in stackoverflow, i found i have to specify this too :
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
as if you would have noticed at line 30, I am sending direct formData
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
**
But I am unsure where should i specify
**
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
in my uploadimage() function to work.
Ajax doesn't support binary file transfers by default. I think it is more easy to base-64 encode your image and just post the data string to the server. You can use a html5 canvas element to get a base-64 encoded string from your image canvas.toDataURL(); . Server side you'll need to decode this string with base64_decode($yourimagedatastring);

Categories