Sending file data with ajax form submit - javascript

I have got issue sending file to a server with ajax for submitting. I tried lots of methods with var xhr = new XMLHttpRequest(); and $.ajax({}); but always its gives error Uncaught TypeError: Illegal invocation. I also use processData: false, but in this condition I got all form fields apart file field.
My Code for ajax is:
var fd = new FormData();
fd.append( 'file', $('#file')[0].files[0] );
fd.append( 'name', 'test');
$.ajax({
url: "uploadFile.php",
data: fd,
cache: false,
contentType: false,
// processData: false,
type: 'POST',
success: function(data, textStatus, jqXHR){
console.log('success');
},
error: function(jqXHR, textStatus, errorThrown){
console.log('error');
}
});
In this I got only name field with value test in output, but not file.
Somebody please let me know where I am wrong.

Set contentType to specific format instead of false.
For eg. in case of image set it to :- "image/jpeg" etc.

Related

Post data in Ajax call arrays converted to strings?

I'm trying to send arrays as post variables in an Ajax call using formData. For some reason they are getting converted to strings when I look in the console. I can't update the functions accepting the data to accept strings, they must accept arrays. I was reading about using the serialize function but then I'm also left with strings...so I'm not sure how to do this. Here is the code I have so far:
function submitSearch(method) {
if (method==='ajax_getPrograms') {
fields = ['pkProgramID','fldName','fldOrganization','fldProgramStartDate','fldProgramEndDate'];
}
if (method==='ajax_getPlots') {
fields = ['id','lat','long','plotSampleYear'];
}
if (method==='ajax_getTrees') {
fields = ['id','species','DBH','treeStatus','treeSampleYear'];
}
var posturl = baseURL + "data/"+method;
var formData = new FormData();
formData.append('fields',fields);
$.ajax({
url: posturl,
cache: false,
data: formData,
method: 'POST',
mimeType: "multipart/form-data",
contentType: false,
processData: false,
type: 'POST',
error: function (xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
},
success: function (data) {
console.log(data);
}
});
}
When I submit that I get an error that my function is receiving a string and not an array, and this is what I see in the network tab of the console:
Any help is appreciated, thank you!

File not sending with FormData in Ajax request

I have an ajax request that is sending a file along with some other info. Everything except the file is the correct value, and the file is always null. I can't figure out why.
Here is the input I have included in the form:
<input type="file" id="file" runat="server"/>
On button click, it calls this function:
function ButtonClick() {
var file = document.getElementById('file').files[0]; // correctly gets the file
var formData = new FormData();
formData.append('key1', 'val1');
formData.append('key2', 'val2');
formData.append('file', file, file.name);
$.ajax({
cache: false,
data: formData,
dataType: 'json',
processData: false,
contentType: false,
success: function (data, textStatus, jqXHR) { closeWindow(); },
timeout: 30000,
type: 'POST',
url: '<%= ResolveClientUrl("~/api/Example/ExampleUrl") %>'
});
}
When I receive the request server-side, I get the following values:
var key1= HttpContext.Current.Request.Form["key1"]); // returns "val1"
var key2= HttpContext.Current.Request.Form["key2"]); // returns "val2"
var file= HttpContext.Current.Request.Form["file"]); // returns "null"
And when I take a look at HttpContext.Current.Request.Form, "file" is not in the request at all.
The file should be accessible via
HttpContext.Current.Request.Files["file"]

Ajax POST error (400 BAD REQUEST)

and thank you in advance for helping me.
I'm trying to make a POST where I pass the TOKEN in the URL and I want to pass another param too so I can save the info in the DB. I have this:
$("#btnAddCompany").click(function(e) {
var token = "123";
var companyValue = document.getElementById("companyValue").value;
var obj ={CompanyId: 4 ,Name: companyValue }
var postData = JSON.stringify(obj);
console.log(postData);
$.ajax({
type: "POST", //REQUEST TYPE
dataType: "json", //RESPONSE TYPE
contentType: "application/json",
data: postData,
url: "http://banametric.ddns.net/BanaMetricWebServices/BanaSov_WS.svc/CompanySave/"+token,
success: function(data) {
toastr.success("Lidl Adicionado!");
},
error: function(err) {
console.log("AJAX error in request: " + JSON.stringify(err, null, 2));
}
}).always(function(jqXHR, textStatus) {
if (textStatus != "success") {
alert("Error: " + jqXHR.statusText);
}
})
});
But I'm getting an 400 error (Bad Request) so I assume that I'm making something wrong, but I don't find out what. The error trace is this:
AJAX error in request: { "readyState": 4, "responseText": "\r\n
The server encountered an error processing the request. The
exception message is 'The incoming message has an unexpected message
format 'Raw'. The expected message formats for the operation are
'Xml', 'Json'. This can be because a WebContentTypeMapper has not been
configured on the binding. See server logs for more
details. The exception stack trace is: \r\n at
System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message
message, Object[] parameters)\r\n at
It's error because of
The expected message formats for the operation are 'Xml', 'Json'.
So you can pass contentType in your ajax call
$.ajax({
....,
contentType: "application/json"
})
I am not sure, but it depends on what server wants to read from you.
Server does not want to read raw bytes, it wants xml or json
Try to add headers like
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
in $.ajax() function
You need to set the content type header in your request to inform the server you're sending the data as JSON.
The error message is telling you that the server does not understand the content you're sending it - you have to give it a hint that the data is in a particular format, especially because, again as mentioned in the error message, it allows you to submit in more than one different format (JSON or XML in this case).
Adding
contentType: "application/json"
to the options in your $.ajax call should resolve the issue.
P.S. We can't see the signature of your controller method but it's possible you may also need to give your parameter a name within the JSON, e.g. something like data: JSON.stringify({ "companyValue": postData }); , but there's not enough info in your question to say for certain what the correct structure should be.
$("body").on("submit", ".example_form", function() {
$.ajax({
url: 'http://example.com/{ROUTE_URL}',
data: new FormData(this),
processData: false,
contentType: false,
/* OR contentType: "application/json; charset=utf-8"*/
type: 'POST',
dataType: "json",
success: function(data) {
console.log(data);
}
});
});
Instead of this
var postData = JSON.stringify(companyValue);
why don't you try this:
var obj ={token :token ,companyValue:companyValue }
And then make use of the json stringify function
var postData = JSON.stringify(obj);
After that in ajax call only change the url:
url: "http://webservice/CompanySave/"

Post File and data with ajax

I have read in other post on SO, similar to what is happening to me, but I still can not get the solution
$('#edit-continue').on('click', function(e) {
e.preventDefault();
var photo = new FormData(); <-----
jQuery.each(jQuery('#photo')[0].files, function(i, file) {<----- SO suggest for file upload
photo.append('file-' + i, file); <-----
});
$.ajax({
type: "POST",
url: "/templates/staycation/common/edit-profile.php",
data: {
id: $('#id').val(),
email: $('#email').val(),
birthday: $('#birthday').val(),
gender: $("input[name='gender']:checked").val(),
photo: photo,
},
success: function(data) {
console.log('pass');
console.log(data);
},
error: function(data) {
console.log('not pass');
console.log(data);
},
cache: false,
contentType: false,
processData: false, <------ i think my error is here
});
if i leave processData: false, , the post arrives empty, by making echo of my array, all data is empty, in the other case, if I comment, the console throws Uncaught TypeError: Illegal invocation
I need to do is send the values entered by the user such as "email", "gender", ... and profile picture, to make an update to the database and to save the image to a folder
this is what working perfectly for me
// formData will wrap all files and content of form
var formData=new FormData($('#formId')[0]);
// you can add more data ot formData after this to
$.ajax({
url : 'upload.php',
type : 'post',
data : formData,
processData:false,
contentType:false,
success : function(e)
{
alert('uploaded successfully');
},
error : function()
{
alert('hello from here');
}
});

How to use $.ajax() for input field text AND FILE upload? [duplicate]

This question already has answers here:
jQuery AJAX file upload PHP
(5 answers)
Closed 8 years ago.
This is my code
$.ajax({
type: 'post',
url: '../lib/upload.php',
data: new FormData( $("#niceidentifier") ),
processData: false,
contentType: false,
success: function (response) {
if(response == 'success') {
return true;
}
else {
alert(response);
console.log(response);
}
}
});
The HTML form is just basic HTML (enctype included and method post) but unfortunately NO data is passed. How can I upload a file AND pass the input data once?
It's not as simple to pass files and other data, such as text, together in the same POST request. The only way to achieve that is making multipart/form-data request.
http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2
I use ajaxForm to upload files asynchronously via ajax, it is much easier than trying to implement your own.
http://malsup.com/jquery/form/
For a cross browser solution I think it is better to use
$("#form_id").ajaxSubmit();
You can use FormData to pass the File. and processData,contentType set to false compulsory. because you are not going to process file in client side.
// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
data.append('myFile', value); //No I18N
});
$.ajax({
url: '/your-url',
type: 'POST',
data: data,
cache: false,
dataType: 'json', //No I18N
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
// do something
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
}
});
OR you can send file with data as following:
$( '#formId' )
.submit( function( e ) {
e.preventDefault();
$.ajax({
url: '/your-url',
type: 'POST',
data: new FormData( this ),
cache: false,
dataType: 'json', //No I18N
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
// do something
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
}
});
});

Categories

Resources