I am trying to upload files using jQuery and AJAX. I have used FormData object which is supported in HTML5. I am using IE11. Below is my code:
<form id="tradeForm" method="post" action="/trade.action?method=addTrade" enctype="multipart/form-data">
Trade Type : <input type="text" id="tradeType" name="tradeType">
Trade Document : <input type="file" id="attachedFile" name="attachment" size="40">
</form>
I've tried using $.post:
$("#tradeForm").submit(function(event){
event.preventDefault();
var form = $(this);
var formData = new FormData(form);
url = form.attr("action");
$.post(url, formData, function(data) {
console.log(data);
});
});
And also using $.ajax
$("#tradeForm").submit(function(event){
event.preventDefault();
var form = $(this);
var formData = new FormData(form);
url = form.attr("action");
$.ajax({
url: url,
type: "POST",
data: formData,
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
}).done(function(data) {
console.log(data);
});
});
I get the following errors:
Argument not optional
When $.post method is used
SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3
When $.ajax method is used. How can I solve these errors?
The FormData constructor expects a DOMElement, not a jQuery object, so you need to amend your FormData() definition. Try this:
$("#tradeForm").submit(function(event){
event.preventDefault();
var $form = $(this);
var formData = new FormData($form[0]); // note [0] here
url = $form.prop("action");
$.ajax({
url: url,
type: "POST",
data: formData,
processData: false,
contentType: false
}).done(function(data) {
console.log(data);
});
});
change this:
var formData = new FormData(form);
to
var formData = new FormData(form[0]);
As FormData needs a form the DOM element this not the jQuery object $(this)
Change the form variable to this:
var form = document.getElementById('tradeForm');
url = $(form).attr("action");
set the contentType: 'Content-Type: multipart/form-data';
I found the fix for the issue. Below are changes done :
Pass DOM element to FormData constructor instead of Jquery Object.
var formData = new FormData(document.getElementById("tradeForm"));
Remove attribute - enctype="multipart/form-data" from the form in the html.Otherwise it will not be possible to read form data at the server end.
Use correct server URL(In my case the URL was wrong). The error message - SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3 was because of wrong URL. It was misleading.
Related
I have a button by where onclick i am trying to send the form data to the server page to process. but somehow the formdata is going empty
can anyone guide what i am doing wrong here, here is my code
function ajax(obj) {
alert('hello');
console.log(obj);
var form = document.querySelector('form');
var data = new FormData(form);
var post_url = $('#formid').attr("action"); //get form action url
var form_data = $('#formid').serialize() & '&yes=1'; //Encode form elements for submission
console.log(form_data);
console.log(data);
$.post(post_url, form_data, function( response ) {
$("#results").html(response);
});
return false;
}
the function ajax is called on the button click inside a form
You are using post menthod wich gets params in body serilliazing the args like that is good for GET request you should send in body just use a object holding all the info
$.ajax({
type: "POST",
url: url,
data: data ,// object
success: success,
dataType: dataType
});
In the below code, I'm able to transfer data but when I use the function append to transfer file and data it's not working. Can someone tell me how to transfer file from upload? Looking forward to some help
$(document).ready(function() {
var loader = '<img src="../assets/media/loader.gif" />';
$('#submit').click(function() {
confirm("Do you really want to send messages?");
$('.loading').html(loader).fadeIn();
var msg_area_cst = $('textarea[name=msg_area_cst]').val();
var num_cst = $('textarea[name=num_cst]').val();
var form_data = new FormData();
form_data = 'msg_area_cst=' + msg_area_cst + '&num_cst=' + num_cst;
form_data.append('upload', $('input[name=upload]'));
$.ajax({
url: "../server/CustomMsg.php",
type: "POST",
data: form_data,
success: function(html) {
if (html == 1) {
$('#register_form').fadeOut('slow');
$('.loading').fadeOut();
$('.message').html('Successfully Sent ! ').fadeIn('slow');
} else
alert('Sorry, unexpected error. Please try again later.');
}
});
});
});
The problem is because you correctly declare a FormData object, but then in the next line overwrite it immediately with a string.
You need to append() all data to the FormData object. In addition you need to provide the file data to the append() method, not the jQuery object referencing the input type="file" control.
var form_data = new FormData();
form_data.append('msg_area_cst', msg_area_cst);
form_data.append('num_cst', num_cst);
form_data.append('upload', $('input[name=upload]')[0].files[0]);
That being said, you can make this much more simple if the controls you're reading the values from are contained in a form element. Then you can use the submit event of that form and pass a reference to it to the FormData constructor.
Also you don't do anything with the result of the confirm() I assume you want to stop the form submission if Cancel is clicked, which the above example now does using preventDefault().
Finally, using html == 1 is very unreliable. Firstly html will be a string so relying on implicit type coercion to an integer is not ideal. Also, returning a plain text response can cause issues if there's any whitespace included. I'd strongly suggest you change your server side logic to return a serialised format, such as JSON, and use a boolean value for a 'success' flag.
With all that said, try this:
$('#yourForm').on('submit', function(e) {
if (!confirm("Do you really want to send messages?")) {
e.preventDefault();
}
$('.loading').html(loader).fadeIn();
$.ajax({
url: "../server/CustomMsg.php",
type: "POST",
data: new FormData(this),
success: function(html) {
if (html.trim() === "1") {
$('#register_form').fadeOut('slow');
$('.loading').fadeOut();
$('.message').html('Successfully Sent ! ').fadeIn('slow');
} else
alert('Sorry, unexpected error. Please try again later.');
}
}
});
});
Try this ajax code
$.ajax({
url: "../server/CustomMsg.php",
type: "POST",
data: form_data,
contentType: false,
cache: false,
processData:false,
async: true,
success: function(html) {
if (html == 1) {
$('#register_form').fadeOut('slow');
$('.loading').fadeOut();
$('.message').html('Successfully Sent ! ').fadeIn('slow');
} else
alert('Sorry, unexpected error. Please try again later.');
}
});
HTML here.
<form id="myForm">
<input type="text" name="name">
<input type="file" name="userImage">
<button onclick="post('./example.php')" type="button">Save</button>
</form>
Now i want to post it by using post() function
Java-script:
Function post(url){
$.ajax({
url:url,
type: 'POST',
data: $("#myform").serialize(),
success: function (data) {
alert("successfully posted.");
}
});
}
But not serialized file
My advice is: try to have apart html and js defining the event callback on "attacheventlistener" function or "on" jquery's function (this way is easier).
Your problem is that you are passing the string "url" when you need pass a valid url, so write the url directly on ajax url field or define a data attribute on your form tag, e.g. data-url="http://whatever", and catch this value from the event.
If you use jquery's "on" function is extremly easy, you could to get it data's value via jquery's "data" function over "this" var.
Something like ...
$("#myForm").on("click",
function() {
post(this.data("url"));
});
But probably you do not need url being a var.
If I understand correctly, the problem is that nothing is being posted.
The thing is is that you are trying to do a file upload via ajax, this is not wrong but it needs to be done differently shown here:
jQuery Ajax File Upload
You can add extra data with form data
use serializeArray and add the additional data:
var data = $('#myForm').serializeArray();
data.push({name: 'tienn2t', value: 'love'});
$.ajax({
type: "POST",
url: "your url.php",
data: data,
dataType: "json",
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
});
First of all i need to say that, if you want to upload file, i mean if your form have file input then add the form attribute enctype="multipart/form-data" according to RFC-7578. you can also see the uses http://www.w3schools.com/tags/att_form_enctype.asp.
Then move to the html part again. Suppose you have a form input like
<form action="some_domain/example.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="fileId"/>
<input type="text" name="firstName" id="name">
<button onclick="post('some_domain/example.php')" type="button">Save</button>
</form>
Now post the file data using ajax:
function post(url){
$.ajax({
url:url,
type: 'POST',
processData:false,
contentType:false,
data: $('#fileId')[0].files[0],
success: function (data) {
alert("successfully posted.");
}
});
}
I think this should be worked fine.
UPDATE:
if you want to post text data as well then you should use FormData object.
function post(url){
var formData = new FormData();
var files = document.getElementById("fileId").files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
formData.append('files[]', file, file.name);
}
formData.append('firstName',$('#name').val());
$.ajax({
url:url,
type: 'POST',
processData:false,
contentType:false,
data: formData,
success: function (data) {
alert("successfully posted.");
}
});
}
This question already has answers here:
jQuery Ajax File Upload
(27 answers)
Closed 6 years ago.
I want to upload image without page loading, here sendImageFile is the value of file field. Now when I trying to upload any file from file_upload_to_user.php but every time $_FILES["sendImageFile"]["name"] returns null value.
<form enctype="multipart/form-data" method="post" name="img_upload_form" id="img_upload_form" action="file_upload_to_user.php">
<input name="sendImageFile" id="sendImageFile" type="file" accept=".png, .jpg, .jpeg"/>
<input type="submit" name="photoUploadToSend" id="photoUploadToSend" style="display:none" />
</form>
JS
var frm = $('#img_upload_form');
frm.submit(function (ev) {
var sendImageFile = document.getElementById("sendImageFile").value;
var to_hash = "000000000";
var dataString = 'sendImageFile='+sendImageFile+"&to_hash="+to_hash;
$.ajax({
type:"POST",
url:"file_upload_to_user.php",
data:dataString,
cache:false,
success: function(info) { alert(info);}
});
}
document.getElementById("sendImageFile").onchange = function change(){
// Upload image
document.getElementById("photoUploadToSend").click();
}
If you want to upload a file with ajax then you have to do it with FormData. And to send a formData with jQuery you need to send two other properties to to disable sending wrong stuff. so it's just easier to use fetch...
var form = document.getElementById("img_upload_form")
var fd = new FormData(form)
fetch("file_upload_to_user.php", {method: 'POST', body: fd})
To send a formdata with jQuery ajax you have to set this two:
processData: false,
contentType: false,
You need to use formData
var formData = new FormData();
formData.append('file', $('#sendImageFile')[0].files[0]);
formData.append('to_hash',"000000000");
$.ajax({
url : 'file_upload_to_user.php',
type : 'POST',
data : formData,
processData: false,//prevent automatic processing
contentType: false,//do not set any content type header
success: function(info) { alert(info);}
});
i already had a form which uses ajax to save the the data to the database. so i have this sample
Html code
<input id="product_name" type="text" >
<input id="product_description"/>
<input id="product_img" type="file" accept="image/*"/>
<button id="btnSave">Save</button>
Javascrip Code
$("#btnSave").click(function(){
p_name = $("#product_name").val();
p_des = $("#product_description").val();
p_image = $("#product_img").prop('files')[0];
data = {
'product_name':p_name,
'product_description':p_des
}
$.post('url_here',data,function(response){
console.log(response);
});
});
i do have this info Jquery input.files equivalent but i cant make it passed as a $_FILE for php.Please give me some example codes combining the input type text and file without using the form tag and using jquery ajax.
You can use FormData:
document.getElementById('btnSave').addEventListener('click', function() {
var fd = new FormData();
fd.append('product_name', document.getElementById('product_name').value);
fd.append('product_description', document.getElementById('product_description').value);
fd.append('product_name', document.getElementById('product_img').files[0]);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'url_here');
xhr.addEventListener('load', function(e) {
console.log(xhr.responseText);
});
xhr.send(fd);
});
UPDATE
Since you want to use jQuery AJAX (I have no idea why, since it was not prepared to use XHR2), you can workaround by telling it to not process the data parameter, e.g:
$('#btnSave').click(function() {
p_name = $('#product_name').val();
p_des = $('#product_description').val();
p_image = $('#product_img').prop('files')[0];
var data = new FormData();
data.append('product_name', p_name);
data.append('product_description', p_des);
data.appned('product_img', p_image);
$.ajax({
url: 'url_here',
data: data,
processData: false,
contentType: false,
type: 'POST',
success: function(response){
console.log(response);
}
});
});