Reputation: 13771
Can someone help me submit a form using AJAX? The purpose of the form is to upload a file. The specific problem I'm having is how to capture the action
and enctype
parameters. My form:
<form role="form" method="post" action="http://localhost:3000/api/some_url" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<input id="submit" type="submit" class="btn btn-primary" value="Submit">
</form>
I need something like:
$.ajax({
type: "POST",
url: 'http://localhost:3000/api/some_url',
action: 'http://localhost:3000/api/some_url',
enctype: 'multipart/form-data',
headers: {
'x-access-token': this.token,
},
success: function () {
console.log('success!')
},
error: function (a, b, c) {
console.log(a)
console.log(b)
console.log(c)
}
})
Can someone help?
Thanks in advance!
Upvotes: 1
Views: 1663
Reputation: 176
Give id to your form
<form id="frm_upload_image" role="form" method="post" action="http://localhost:3000/api/some_url" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<input id="submit" type="submit" class="btn btn-primary" value="Submit">
</form>
after that make following changes in your ajax call
var form = new FormData($("#frm_upload_image"));
$.ajax({
url: $("#frm_upload_image").attr('action'),
type: "POST",
data: form,
contentType: false,
cache: false,
processData:false,
success:function() {
console.log('success!')
},
error: function (a, b, c) {
console.log(a)
console.log(b)
console.log(c)
}
});
});
it works for me
Upvotes: 2