Upload not working with Jquery xhr & Ajax - javascript

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

Related

how to retrieve file request type in jsp sending from ajax?

I want to upload an image using JSP and ajax in which all uploaded file validation. I'm checking via jQuery and you can see in code before success function code. and this file information I want to retrieve in the JSP page. this ajax code sending file details which I want to upload to the target JSP page. if ajax is sending normal input text field data, we can retrieve it via request.getParameter() in JSP page but how to retrieve file input response.
var file;
$("#updatepictureform").submit(function(event) {
$("#updatepicturemessage").hide();
//show spinner
$("#spinner").css("display", "block");
event.preventDefault();
if (!file) {
$("#spinner").css("display", "none");
$("#updatepicturemessage").html('<div class="alert alert-danger">Please upload a picture!</div>');
$("#updatepicturemessage").slideDown();
return false;
}
var imagefile = file.type;
var match = ["image/jpeg", "image/png", "image/jpg"];
if ($.inArray(imagefile, match) == -1) {
$("#updatepicturemessage").html('<div class="alert alert-danger">Wrong File Format</div>');
$("#updatepicturemessage").slideDown();
$("#spinner").css("display", "none");
return false;
} else {
$.ajax({
url: "updatepicture.jsp",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data) {
if (data) {
$("#updatepicturemessage").html(data);
console.log(data);
//hide spinner
$("#spinner").css("display", "none");
//show message
$("#updatepicturemessage").slideDown();
//update picture in the settings
} else {
location.reload();
}
},
error: function() {
$("#updatepicturemessage").html("<div class='alert alert-danger'>There was an error with the Ajax Call. Please try again later.</div>");
//hide spinner
$("#spinner").css("display", "none");
//show message
$("#signupmessage").slideDown();
}
});
}
});
This is the output I am getting when printing file information at ajax page.
Array{[picture]=>Array{[name]=>myprofile.jpg [type]=>image/jpeg [error]=>0 [size]=>276599 }}

Why doesn't my form work on mobile devices?

I have a form downloaded from http://reusableforms.com/ that works great on desktop. But the submit button changes to "sending ..." and gets stuck on mobile devices. An error message doesn't display and the page just stops working. What would cause this problem? I am putting my javascript code below. Here is the site for reference: http://jasminew.xyz/flash
$(function()
{
$.ajaxSetup({ cache: false }); // or iPhones don't get fresh data
function after_form_submitted(data)
{
if(data.result == 'success')
{
$('#carouselExampleIndicators').hide();
$('form#reused_form').hide();
$('#success_message').show();
$('#error_message').hide();
}
else
{
$('#error_message').append('<ul></ul>');
jQuery.each(data.errors,function(key,val)
{
$('#error_message
ul').append('<li>'+key+':'+val+'</li>');
});
$('#success_message').hide();
$('#error_message').show();
//reverse the response on the button
$('button[type="button"]', $form).each(function()
{
$btn = $(this);
label = $btn.prop('orig_label');
if(label)
{
$btn.prop('type','submit' );
$btn.text(label);
$btn.prop('orig_label','');
}
});
}//else
}
$('#reused_form').submit(function(e)
{
e.preventDefault();
$form = $(this);
//show some response on the button
$('button[type="submit"]', $form).each(function()
{
$btn = $(this);
$btn.prop('type','button' );
$btn.prop('orig_label',$btn.text());
$btn.text('Sending ...');
});
var formdata = new FormData(this);
$.ajax({
type: "POST",
url: 'handler.php',
data: formdata,
success: after_form_submitted,
dataType: 'json' ,
processData: false,
contentType: false,
cache: false,
});
});
});
EDIT
I have opened remote Safari dev tools and the XHR Post is timing out. I'm not sure what that means.
EDIT
Okay, the problem is that the form stops working if the two upload fields in the form aren't used on iOS. Does anyone know a workaround?
I reviewed your code and would suggest some minor updates:
$(function() {
$.ajaxSetup({
cache: false
}); // or iPhones don't get fresh data
function after_form_submitted(data) {
if (data.result == 'success') {
$('#carouselExampleIndicators').hide();
$('form#reused_form').hide();
$('#success_message').show();
$('#error_message').hide();
} else {
$('#error_message').append('<ul></ul>');
$.each(data.errors, function(key, val) {
$("<li>").html(key + ": " + val).appendTo($('#error_message ul'));
});
$('#success_message').hide();
$('#error_message').show();
//reverse the response on the button
$('button[type="button"]', $form).each(function() {
var $btn = $(this);
var label = $btn.data('orig-label');
if (label) {
$btn.prop('type', 'submit');
$btn.text(label);
$btn.data('orig-label', null);
}
});
}
}
$('#reused_form').submit(function(e) {
e.preventDefault();
var $form = $(this);
//show some response on the button
$('button[type="submit"]', $form).each(function() {
var $btn = $(this);
$btn.prop('type', 'button');
$btn.data('orig-label', $btn.text());
$btn.text('Sending ...');
});
var formdata = new FormData($form[0]);
$.ajax({
type: "POST",
url: 'handler.php',
data: formdata,
success: after_form_submitted,
dataType: 'json',
processData: false,
contentType: false,
cache: false,
});
});
});
I see nothing that is "wrong", just some syntax cleanup. Also this was sort of ambiguous in the creation of FormData, so I switched to a more specific element: $form[0].
I adjusted a few other things to be more jQuery like. All functions the same.
Also, make sure that Ajax URL path is correct. You have:
url: 'handler.php'
Make sure that your can browse to this directly. If the path is not correct, the form will not post properly. It may be better to use a Direct URL Path instead of a relative path.
If you have access to your Web Server or PHP Logs, you can also check there to see if POSTs to your handler.php script are failing in some way. In Safari, you may want to check Network results and see if it provide more response details.
Test it, let me know if it works any better.

Get status of form submission from backend

Is it possible to get status of each steps from backend? Like when I submit multipart form through ajax, it should show file upload progress, once it's finished it should show file format conversion progress then aws upload progress. Tried following ajax trick but it only show for upload progress.
$.ajax({
url: url,
type:"POST",
data: data,
processData: false,
contentType: false,
xhr: function(){
var xhr = $.ajaxSettings.xhr() ;
// set the onprogress event handler
xhr.upload.onprogress = function(evt){ console.log('progress', evt.loaded/evt.total*100) } ;
// set the onload event handler
xhr.upload.onload = function(){ console.log('DONE!') } ;
// return the customized object
return xhr ;
}
})
it's expressjs in backend. Please let me know if I'm doing it wrong or any suggestions.

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 upload file through Jquery/AJAX [duplicate]

This question already has answers here:
Uploading both data and files in one form using Ajax?
(13 answers)
Closed 9 years ago.
I am currently POSTING my form through AJAX with the following code:
$(document).ready(function(){
$("form#createForm").submit(function() { // loginForm is submitted
$("form#createForm input#createForm_submit").attr('disabled','disabled');
tinyMCE.triggerSave();
$.ajax({
type: "POST",
dataType: "json",
url: "perform", // URL of the Perl script
data: $("#createForm").serialize(),
// script call was successful
// data contains the JSON values returned by the Perl script
success: function(data){
$('div.form-group').each(function(){
$(this).removeClass('has-error');
});
if (data.error) { // script returned error
var myList = $('ul.msg-list').empty();
$.each(data.msg, function(key,item) {
$("div."+key).addClass('has-error');
$('<li>').text(item.errtxt).appendTo(myList);
});
$('div#create_createresult').html('some error').html(myList);
$('div#create_createresult').addClass("text-danger");
$("form#createForm input#createForm_submit").removeAttr('disabled');
} // if
else
{ // login was successful
//$('form#login_loginform').hide();
$('div#create_createresult').text(data.msg);
$('div#create_createresult').addClass("success");
} //else
} // success
}); // ajax
$('div#login_loginresult').fadeIn();
return false;
});
});
Now I want to add the posibility of uploading a picture in the same form and just implement it in this JQUERY and in the same server-side script. My only problem is, I don't know how to do it.. I have tested the above, and I find, that it doesn't pass the $_FILES-variable to my server side script.
Can anyone lead me in any direction of, what I need to do, to add the possibility of image upload with this script?
try to use this.
// grab your file object from a file input
$('#fileInput').change(function () {
sendFile(this.files[0]);
});
// can also be from a drag-from-desktop drop
$('dropZone')[0].ondrop = function (e) {
e.preventDefault();
sendFile(e.dataTransfer.files[0]);
};
function sendFile(file) {
$.ajax({
type: 'post',
url: '/targeturl?name=' + file.name,
data: file,
success: function () {
// do something
},
xhrFields: {
// add listener to XMLHTTPRequest object directly for progress (jquery doesn't have this yet)
onprogress: function (progress) {
// calculate upload progress
var percentage = Math.floor((progress.total / progress.totalSize) * 100);
// log upload progress to console
console.log('progress', percentage);
if (percentage === 100) {
console.log('DONE!');
}
}
},
processData: false,
contentType: file.type
});
}

Categories