Reputation: 946
I'm trying to get AJAX file (picture) upload working, but I'm having some problems sending variables through the formData API:
This is the formData code:
var data = new FormData();
data.append('SelectedFile', _file.files[0]);
data.append('name', event_title);
As you can see on line 3 I am trying to send a variable to the server at the same time. event_title is defined as
var event_title = document.getElementById("new_event_title").value;
And that is called before the formData code.
I can send normal text through to the server just fine, for example
date.append("name", "enter-name");
However when I change this to a variable it stops working.
I've checked MDN and HTML5rocks to no avail, so if anyone could help I'd appreciate it.
Upvotes: 0
Views: 849
Reputation: 11972
This code demonstrates how it's possible to send a file and a variable string parameter at the same time:
document.getElementById("submitBtn").onclick = function(){
var event_title = document.getElementById("new_event_title").value;
var file = document.getElementById("file").files[0];
var data = new FormData();
data.append('SelectedFile', file);
data.append('name', event_title);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://example.com/', true);
xhr.send(data);
};
<input type="text" id="new_event_title" value="My Event Title">
<input type="file" id="file">
<br>
<input type="submit" id="submitBtn" value="Send">
Click above to run the code and look in the network tab of the browser console, you'll see the data is sent. I suspect your problem is related to other code on your page.
Upvotes: 1