Ajax form with both file and text inputs [duplicate] - ajax

This question already has answers here:
Uploading both data and files in one form using Ajax?
(13 answers)
Closed 10 years ago.
I'm trying to create an ajax upload form that sends both a file and a text input.
I've managed to send the file with the following code:
var $form = $('#form');
var formData = new FormData();
formData.append('file', $('#file')[0].files[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
dataType: 'html',
data: formData,
processData: false,
contentType: false
});
However, I also need to send the text input, so I've tried passing the whole form to the FormData object:
var $form = $('#form');
var formData = new FormData($form);
$.ajax({
url: 'upload.php',
type: 'POST',
dataType: 'html',
data: formData,
processData: false,
contentType: false
});
But then I get nothing in 'upload.php'
How can I send the text and the file inputs together?
Thanks!

Found this answer (Previous Answer) after much searching and works great in my application:
$("form#data").submit(function(){
var fd = new fd($(this)[0]);
var request = jQuery.ajax({
url: gurl,
type: 'POST',
cache: false,
contentType: false,
processData: false,
data: fd
});
I would also check your AJAX call, the dataType: 'html' might cause errors.

Related

JS/JSON file upload immutable dictionary is empty

I know, similar questions had been asked before.
All questions I found concerns upload within a form and need a submit button. This I don't want. I want upload to start after file selection is made (I'm aware of security risks).
Why is the contend of the file dictionary not send?
The button itself is created by JS:
downLoadBtn = document.createElement('INPUT');
downLoadBtn.id = 'downloadBtn';
downLoadBtn.type = 'file';
downLoadBtn.onchange = function(){upload()}
function upload(){
file = document.getElementById('downloadBtn')
console.log(file['files']['0'])
$.ajax({
type: "POST",
url: '/upload',
dataType : 'json',
data: JSON.file,
success: function (response){
console.log(response);
}
});
}
python:
#app.route('/upload', methods = ['POST'])
def upload():
if request.method == 'POST':
data = request.files
print(data)
return jsonify(data)
What I'm doing wrong?
You pass JSON.file as the data parameter which is not defined in the code you posted, it should be the file tat was selected.
Since your server side code expects multipart from data, you'll have to use a FormData object.
function upload(){
file = document.getElementById('downloadBtn')
console.log(file['files']['0'])
var fd = new FormData();
fd.append('file', file['files']['0']);
$.ajax({
type: "POST",
url: '/upload',
dataType : 'json',
data: fd,
contentType: false,
processData: false,
success: function (response){
console.log(response);
}
});
}

Ajax request - xml/json

Studying for an exam and came across the following practice question.
You develop a web application by using jQuery. You develop the following jQuery code:
$(document).ready(function () {
$('#submit').click(function () {
$.ajax({
//INSERT CODE
data: $('#myForm').serialize(),
success: function (result) {
$('#result').text(result.message);
}
});
})
})
The web application exposes a RESTful web api that has an endpoint of product/create. You need to create a new product by using AJAX.
Which code segment should you insert at line 04?
//Option A:
type: "POST",
dataType: "xml",
contentType: "application/x-www-urlencoded; charset=UTF-8",
url: ".product/create",
//OPTION B:
type: "POST",
dataType: "json",
url: ".product/create",
Could someone explain why option B is correct?
I understand that it should be a post request since a new product is being created. Datatype could be either json or xml. Content-type is optional. Is it because result.message can only work when a json is passed in?
For the datatype:"xml", The contenttype is not valid in Option A. The valid options for XMLs are: text/xml, application/xml.
But, Option B has valid entries.
The corrected option A is below,
//Option A:
type: "POST",
dataType: "xml",
contentType: "application/xml; charset=UTF-8",
url: ".product/create",

Can't pass data from attributes using ajax laravel 5.1

var formData = new FormData();
formData.append('name', name.val());
formData.append('email', email.val());
formData.append('contact_number', contact_number.val());
formData.append('barangay', barangay.val());
formData.append('landmark', landmark.val());
formData.append('password', password.val());
formData.append('confirm_password', confirm_password.val());
//Problem start here it came from attributes but I can alert the data and it was fine.
formData.append('image_pin', img_top);
formData.append('img_left', img_left);
formData.append('img_z_index', img_z_index);
formData.append('input_value', input_value);
formData.append('input_top', input_top);
formData.append('input_left', input_left);
$.ajax({
url: 'register',
headers: {'X-CSRF-TOKEN': token.val() },
method: 'post',
processData: false,
contentType: false,
cache: false,
dataType: 'json',
data: formData,
success: function(data){
console.log(data);
},
error: function(){
}
});
//The input works fine but the attributes data is undefined
$request->input('img_top');
$request->input('img_left');

AJAX not saving variables to javascript (asynchronous issues)

Why is alert saying that the text[0] is undefined?
This is my code:
var text = new Array;
$.ajax({
url: 'engine1/api.php',
data: "",
dataType: 'json',
success: function(rows){
text = rows;
}
});
alert(text[0]);
var text = new Array;
$.ajax({
url: 'engine1/api.php',
data: "",
dataType: 'json',
success: function(rows){
text = rows;
alert(text[0]); // will work, this gets executed after you set text
}
});
//alert(text[0]); << don't put this here, it will get executed right after you send the request
Finally answered my own question, for anyone that comes across this question, here is what I did:
Because ajax is asynchronous, alert(text[0]) is getting executed before text=rows.
You can set ajax to run procedurally like this:
$.ajax({
url: 'engine1/api.php',
data: "",
dataType: 'json',
async: false;
success: function(rows){...
Apperently this is one of the few cases that you can/should set ajax to async:false (because you're serving javascript/jquery to the client).

Send FormData and String Data Together Through JQuery AJAX

I have the below that uploads an image using JQuery's AJAX function
var id = <?php echo $id; ?>;
var img_data = new FormData($("form")[0]);
$.ajax({
url: 'add.php',
data: img_data,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
I'd like to include a string with the FormData sent. I tried the following, but no luck
data: img_data {id: id},
What's the correct syntax here?
Use append
var img_data = new FormData($("form")[0]);
img_data.append('id', id);
You could create a JSON data object and pass that as application/json and process the data within add.php:
var data = {
id : <?php echo !empty($id) ? $id : "''",
img_data : new FormData($("form")[0])
};
$.ajax({
url: 'add.php',
data: data,
contentType: "application/json",
type: 'POST',
success: function(data){
alert(data);
}
});
Although unconventional, you could also append the data as a query string to the URL with the POST. You'd also need to edit add.php to get this parameter.
$.ajax({
url: 'add.php?id=' + id,
data: img_data,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});

Resources