Uploading is stuck - javascript

$("#sendingForm").submit(
function ()
{
if (checkForm())
sendForm();
return false;
}
);
function sendForm ()
{
var formData = new FormData($("#sendingForm"));
$.ajax({
url: '/process.php',
method: 'post',
contentType: 'multipart/form-data',
data: formData,
success: function(response){
if (response!="0")
errorsDecode(response);
else
alrightMes();
alert(response);
}
});
}
I used to serialize form data, but then I had to add file uploading, so i use FormData class. but it doesn't work. I can't find out the reason. Help me please.

FormData won't unwrap a jQuery object representing the form element.
Try changing:
var formData = new FormData($("#sendingForm"));
To
var formData = new FormData($("#sendingForm")[0]);
You also need to prevent processing of the FormData object internally by $.ajax and browser will set the multi-part content type when a FormData object is used
$.ajax({
url: '/process.php',
method: 'post',
contentType: false,// browser will set multi-part when FormData used
processing: false,
data: formData,
success: function(response) {
if (response != "0")
errorsDecode(response);
else
alrightMes();
alert(response);
}
});

Related

How to send Form Data and other Data using AJAX

I'm trying to send HTML form data using AJAX however I'm also trying to send other data along with the same AJAX POST call.
Is this possible?
$('#HTMLConForm').on('submit', function (e)
{
e.preventDefault();
$.ajax({
url: "***NewUserURL.com***",
type: "POST",
data:{
'otherinfo': otherinfo,
'form_data': new FormData(this),
},
processData: false,
contentType: false,
success: function (data)
{
alert('You Have Registered')
/*window.location = "index.html"; */
},
error: function (xhr, desc, err)
{
}
});
});
Any help with be appreciated!
Pass the FormData object itself to data, don't wrap it in a simple object.
Use the FormData object's append method to add additional data.
e.preventDefault();
const formdata = new FormData(this);
formdata.append("otherinfo", otherinfo);
$.ajax({
url: "***NewUserURL.com***",
type: "POST",
data: formdata,

How to add PHP Session variable into FormData using AJAX?

I'd like to pass a PHP session variable (called 'profileid') using FormData and AJAX. I thought this below would work, it did not. Why?
var imageData = new FormData();
imageData.append('image', $('#uploadImage')[0].files[0]);
imageData.append('profileid', <?php echo $_SESSION['profileid'];?>);
//Make ajax call here:
$.ajax({
url: '/upload-image-results-ajax.php',
type: 'POST',
processData: false, // important
contentType: false, // important
data: imageData,
//leaving out the rest as it doesn't pertain
You could add the profileid in the $.ajax URL parameter instead of adding it in FormData:
$(document).ready(function (e) {
$('#uploadImageForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: "/upload-image-results-ajax.php?profileid=<?= $_SESSION['profileid']; ?>",
type: "POST",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(response){
console.log("success");
console.log(response);
},
error: function(response){
console.log("error");
console.log(response);
}
});
}));
$('#uploadImage').on("change", function() {
$("#uploadImageForm").submit();
});
});
Don't forget to place session_start(); at the beginning of your code.

How to find if an ajax call is completed?

Peace And blessing be upon you :)
Basically I have two function, each performs an ajax call. Something like:
1:
function step1(){
var formdata = new FormData();
formdata = {
'URI': sendtosev
};
$.ajax({
type: 'POST',
url: 'http://localhost:20012/serv1',
data: formdata,
contentType: "text/html",
success: function(result){
$('.UID).text(result);
}
});
}
2:
function step2(){
var stkname=$('.UID').text();
var formdata = new FormData();
formdata = {
'URI': stkname
};
$.ajax({
type: 'POST',
url: 'http://localhost:20012/serv1',
data: formdata,
contentType: "text/html",
success: function(result){
alert(result);
}
});
}
FYI: step1 ajax is performed to get some data from serv1 servlet. and step2 ajax uses step1 ajax output and through it get some new Data from serv2.
Now Currently What I'm doing is:
$(function({
step1();
step2();
});
Through this step2 FormData is null because step1 has not yet finished it's call and haven't received its output.
Question: How to find if step1() ajax is completed and have received the output So I could call step2();
function step1(){
var formdata = new FormData();
formdata = {
'URI': sendtosev
};
$.ajax({
type: 'POST',
url: 'http://localhost:20012/serv1',
data: formdata,
contentType: "text/html",
success: function(result){
$('.UID').text(result);
step2();
}
});
}
//step2 implementation
//start with
step1();
Simply call step2 if step1 succeeded...
You can use jquery callback functions. Please see below code for reference
function step1(callback){
var formdata = new FormData();
formdata = {
'URI': sendtosev
};
$.ajax({
type: 'POST',
url: 'http://localhost:20012/serv1',
data: formdata,
contentType: "text/html",
success: function(result){
$('.UID).text(result);
callback(result);
}
});
}
function step2(result){
var stkname=$('.UID').text();
var formdata = new FormData();
formdata = {
'URI': stkname
};
$.ajax({
type: 'POST',
url: 'http://localhost:20012/serv1',
data: formdata,
contentType: "text/html",
success: function(result){
alert(result);
}
});
}
$(function({
step1(function(result){
step2();
});
});
This is a good candidate for callbacks. For example, step1 could be rewritten as follows:
function step1(callback){
var formdata = new FormData();
formdata = {
'URI': sendtosev
};
$.ajax({
type: 'POST',
url: 'http://localhost:20012/serv1',
data: formdata,
contentType: "text/html",
success: function(result){
$('.UID').text(result);
callback();
}
});
}
And then you can code the following when you call it:
step1(step2);
2 ways to accomplish it
pass 'async:false' to $.ajax parameter. then $.ajax will not return until the response come
call step2() in ajax callback function

Ajax send array and Image in same request

I want to make an ajax call that sends both JSON and file data to my PHP backend. This is my ajax call currently:
$.ajax({
type: 'POST',
dataType: 'json',
data: jsonData,
url: 'xxx.php',
cache: false,
success: function(data) {
//removed for example
}
});
The data(jsonData) is a JSON array that also holds the input from a file select as well(I am assuming this is wrong due to the type mismatch). I tried using contentType: false, and processData: false, but when I try to access $_POST data in PHP there is nothing there. The data I am passing does not come from a form and there is quite a bit of it so I do not want to use FormData and append it to that object. I am hoping i will not have to make two ajax calls to accomplish this.
If you want to send data along with any file than you can use FormData object.
Send your jsonData as like that:
var jsonData = new FormData(document.getElementById("yourFormID"));
Than in PHP, you can check your data and file as:
<?php
print_r($_POST); // will return all data
print_r($_FILES); // will return your file
?>
Try Using formdata instead of normal serialized json
Here's an example:
var formData = new FormData();
formData.append("KEY", "VALUE");
formData.append("file", document.getElementById("fileinputID").files[0]);
then in your ajax
$.ajax({
type: 'POST',
url: "YOUR URL",
data: formData,
contentType: false,
processData: false,
dataType: 'json',
success: function (response) {
CallBack(response, ExtraData);
},
error: function () {
alert("Error Posting Data");
}
});
You can try like this also
You can visit this answer also
https://stackoverflow.com/a/35086265/2798643
HTML
<input id="fuDocument" type="file" accept="image/*" multiple="multiple" />
JS
var fd = new FormData();
var files = $("#fuDocument").get(0).files; // this is my file input in which We can select multiple files.
fd.append("kay", "value"); //As the same way you can append more fields
for (var i = 0; i < files.length; i++) {
fd.append("UploadedImage" + i, files[i]);
}
$.ajax({
type: "POST",
url: 'Url',
contentType: false,
processData: false,
data: fd,
success: function (e) {
alert("success");
}
})

Send file by Ajax and FormData fail

I'm trying to send a file using Ajax in Jquery creating a FormData previously. This is my code:
var inputFileImage = document.getElementById('uploadImage');
var file = inputFileImage.files[0];
var data = new FormData();
data.append('archivo',file);
jQuery.ajax({
url: '/services/rpc.php',
type: 'post',
data: {functionName: 'saveProfileImage', data : data},
contentType:false,
processData:false,
})
.done(function(response) {
alert(response);
}.bind(this))
.fail(function(response) {
alert('Sorry, there was an unexpected error, please try again later.\n\nInformation about the error:\n'+response);
});
This ajax always goes to the fail function, and if I change the processData to true returns my another error saying Error: TypeError: 'append' called on an object that does not implement interface FormData.
Thanks for your help!
processData has to be off to send binary data. The FormData element is completely used as binary data, while data:{} needs to be processed. Additional parameters have to be appended to the formData in this case!
var data = new FormData();
data.append('archivo',file);
data.append('functionName','saveProfileImage');
jQuery.ajax({
url: '/services/rpc.php',
type: 'post',
data: data,
contentType:false,
processData:false,
});

Categories

Resources