I need to add "<message>" as a Content-ID to my ajax request for my multipart form. I have a pretty simple request using Backbone's save:
var data = new FormData();
data.append('message', new Blob([JSON.stringify(message.attributes)],{type: "application/json"}),'message');
data.append(document.getElementById('fileInput').files[0].name,document.getElementById('fileInput').files[0]);
message.save({},{
contentType: 'multipart/form-data',
data: data
});
The first part of the form, "message," should have a Content-ID header. Any idea on how to achieve this?
As Backbone.Model.save uses $.ajax to interact with server, you can set custom headers using $.ajax's options.
Using headers options:
message.save({},{
headers: {"Content-ID": "<message>" },
contentType: 'multipart/form-data',
data: data
});
Using beforeSend callback of $.ajax:
message.save({},{
beforeSend: function(xhr) {
xhr.setRequestHeader("Content-ID", "<message>");
},
contentType: 'multipart/form-data',
data: data
});
Related
I am trying to convert old javascript ajax call to angular by using $http method in Angular.
My old one is like
var payload ={'id':'id-abc'}
$.ajax({
type: 'post',
url: 'myurl/com',
dataType: 'json',
data: payload,
success: function (returndata) {
//parse returndata
});
});
in Angular way,
$http({
method: 'post',
url: ‘myurl/com’,
dataType: 'json',
data: payload
}).then(function(returndata) {
console.log(returndata);
})
The angular way gave me
Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response. Issue.
If I mimic the old way and setup the content-type header like
$http({
method: 'post',
url: ‘myurl/com’,
dataType: 'json',
data: payload,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(returndata) {
console.log(returndata);
})
The server response is saying I am missing a params (it doesn’t).
I don’t have the control on the server side so I am not sure how to covert the old $ajax request to the new Angular one. Any ideas? Thanks a lot!
$http default is to serialze data as json
To send form encoded you need to use $httpParamSerializerJQLike which also needs to be injected wherever you use it
$http({
url: myUrl,
method: 'POST',
data: $httpParamSerializerJQLike(myData),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
You could also set up global defaults for the header and a $httpInterceptor to do this transform instead of putting in each individual request
I am working on an app that sends a POST request to a web service. My POST request looks like this:
$.ajax({
type: 'POST', url: getEntityUrl(), cache: 'false',
contentType:'application/json',
headers: {
'api-key':'myKeyHere',
'Content-Type':'application/json'
},
data: {
firstName:'Jon',
lastName:'Smith'
},
success: function() { alert('good job'); },
error: function() { alert('oops'); }
});
When I execute this, I'm getting a 400 Bad Request. I watched the request in Fiddler. I noticed that the parameters I sent are being sent as "firstName=Jon&lastName=Smith". However, they need to be sent across as JSON like I have them defined in the data parameter. I confirmed this is the problem by modifying the request in the composer in Fiddler. What am I doing wrong?
Thanks
If you pass jQuery a plain object through the data parameter (as you do here) then it will encode the data as application/x-www-form-urlencoded.
Just setting the contentType is insufficient.
If you want to send JSON then you must encode it yourself. You can use JSON.stringify for that.
data: JSON.stringify({
firstName:'Jon',
lastName:'Smith'
}),
You need to stringify the data like following.
$.ajax({
type: 'POST',
url: getEntityUrl(),
contentType: 'application/json',
headers: {
'api-key': 'myKeyHere',
'Content-Type': 'application/json'
},
data: JSON.stringify({ firstName: 'Jon', lastName: 'Smith' }), //change here
success: function () { alert('good job'); },
error: function () { alert('oops'); }
});
I am trying to test whether we can convert our existing file upload form into a more ajax/html5 without changing much of the backend. So here is what I am doing on the test:
function sendFile() {
var data = new FormData();
var file = $('input[type=file]').get(0).files[0];
data.append("file1",file);
$.ajax({
type: 'post',
url: '/upload.jsp',
data: data,
contentType: 'multipart/form-data',
processData: false
});
}
So the file sending part is not the problem. The problem is that I am not getting any of my cookies. If I take the data: data param out then it sends the cookies just fine.
Any idea why?
Thanks.
You need to set the withCredentials $.ajax() setting:
function sendFile() {
var data = new FormData();
var file = $('input[type=file]').get(0).files[0];
data.append("file1",file);
$.ajax({
type: 'post',
url: '/upload.jsp',
data: data,
contentType: 'multipart/form-data',
processData: false,
xhrFields: {
withCredentials: true
}
});
}
I am uploading two different type of file with ajax by using two different function. The problem is->the timeout which is set for the first request has been set for other request also.. so if first file is too large and take almost 2 mins for uploading, then next file which is an image of very small size uploaded by next ajax request with a different time out will be also take same 2 mins for uploading..
here i am uploading file directly to amazon.
Below is the ajax function to upload my second file with a small timeout
xhr_request1=$.ajax({
url: 'uploader.php', //server script to process data
type: 'POST',
//Ajax events
beforeSend: function(){beforeSendHandler(fileLoading);},
success: function(response) {completeHandler(response,fileName,fileLoading,filePreview,fileUpload,filename);},
// error: function(xhr,tStatus,err ) {errorHandler(err,fileLoading,filePreview);},
// Form data
data: formData,
//Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: false,
processData: false,
timeout:50000
});
and below is next function to upload large files
xhr_request2=$.ajax({
url: 'contentuploader.php', //server script to process data
type: 'POST',
//Ajax events
beforeSend: function(){beforeSendHandler1(fileLoading1);},
success: function(response) {completeHandler1(response,fileName1,fileLoading1,filePreview1,fileUpload1,filename1);},
// error: function(xhr,tStatus,err ) {errorHandler(err,fileLoading,filePreview);},
// Form data
data: formData,
//Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: false,
processData: false,
timeout:1000000
});
you make manually object of form data as your required parameter
var fd = new FormData();
fd.append( 'file', input.files[0] );
$.ajax({
url: 'http://example.com/script.php',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
You can follow this link
1.) How to send FormData objects with Ajax-requests in jQuery?
Below is an Ajax request to a static web method at server. I want to send the file and its associated details to the server. Even if I send the data to the server, i'm not able to access the file at the server side using c#.net.
The most difficult part being accessing the FileUpload control in the static WebMethod.
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'UserProfile.aspx/EditProfile',
data: "{'file':'" + document.getElementById('FileUpload1').files[0] + "'}",
async: true,
success: function (response) {
$('#dialog-form').dialog("close");
}
});
Don't attempt to send the data as JSON, send it as formdata with FormData and you can read the file on the server side as if you used a regular form to upload the file.
var data = new FormData();
data.append('file', document.getElementById('FileUpload1').files[0]);
$.ajax({
type: 'POST',
url: 'UserProfile.aspx/EditProfile',
data: data,
async: true,
processData: false,
contentType: false,
success: function (response) {
$('#dialog-form').dialog("close");
}
});