Send form using javascript/jquery - javascript

I would like to send the form in its entirety, using ajax.
The form has an Id which is 'FormId'.
const Url = '/CV/AutoSave/';
var testForm = $('#FormId');
var cvForm = new FormData(testForm[0]);
$.ajax
({
url: Url,
type: "POST",
contentType: "application/x-www-form-urlencoded",
data: cvForm,
success: function (result) {
console.log(result.Id)
}
});
When debugging the code I can see that testForm is equal to the entire form.
var cvForm = new FormData(testForm[0]);
Is empty for some reason.
The form has many fields, so I hope it is possible to send the entire form, instead of defining every single field in js before sending them.
Thanks in advance.

When you use FormData, the content type should be multipart/form-data, not application/x-www-form-urlencoded. You should also use processData: false to prevent jQuery from trying to serialize the FormData object.
$.ajax
({
url: Url,
type: "POST",
contentType: "multipart/form-data",
processData: false,
data: cvForm,
success: function (result) {
console.log(result.Id)
}
});
If the form doesn't have any file uploads, you can use $('#FormId').serialize() to serialize it in URL-encoded format, then your $.ajax call would work. You don't need the contentType option, it defaults correctly.

You need to set contentType to false so proper Content-Type header with correct boundary will be set. Also set processData to false to prevent jQuery serializing data
const Url = '/CV/AutoSave/';
var testForm = $('#FormId');
var cvForm = new FormData(testForm[0]);
$.ajax({
url: Url,
type: "POST",
processData: false,
contentType: false,
data: cvForm,
success: function (result) {
console.log(result.Id)
}
});

Related

Is it Possible to Upload Image Using HTTP GET

I've been using the following code to upload image to server. Is it possible to change it to pass file data using an object instead of form data and using GET instead of POST.
var uploadfileinfo = document.getElementById("upload-file-info").value;
var file_data = $('#a_imgfile').prop('files')[0];
var a_imgfile = document.getElementById("a_imgfile");
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'upload.php',
dataType: 'text',
cache: false,
async: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
alert(response);
},
error: function(err) {
alert(err);
}
});
Browser file upload will send form multipart contenttype, you cant send content type in GET request
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST
If you are looking for some workaround you can use some base64 encoder and pass your image to url query param
In GET request you can only get data or pass query paramerters. If you want to upload image change any other data it must be in POST request
Read more https://www.w3schools.com/tags/ref_httpmethods.asp

How to pass data in a jsp file to multiple servlet using javascript?

I have a jsp file which has a form. And the form has some text fields and image upload field.I need to send text data to one servlet and image to another servlet when I click the submit button. is this possible ?
Yes.. I think it is possible .. the way I know you have to use a javascript library like jquery. Below is how it happens
On form submit you prevent the post to servlet. Then you can use ajax like shown below to send 2 requests to 2 different servlets. Below shows one ajax call.. you can do another after that call. I trying to show you below
$("form").submit(function(evt){
evt.preventDefault();
var formData = new FormData($(this)[0]);
var author = $("#author").val();
$.ajax({
url: 'fileUploadServletUrl',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
success: function (response) {
alert(response);
}
});
$.ajax({
url: 'textDataServletUrl',
type: 'POST',
data: {'author':author },
async: false,
cache: false,
processData: false,
success: function (response) {
alert(response);
}
});
return false;
});

Send image with ajax , using jquery validator on submitHandler

I trying to send two images with ajax (inside submitHandler) after using jquery validator plugin and i don't know hoy i cant take and send this image by ajax.
My code here:
var submitHandler = function(form) {
var formData = form[0];
var formData = new FormData(formData);
$.ajax({
url: 'function/savePreInscripcion.php',
type: 'POST',
data: formData,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(data){
alert(data);
}
});
};
but this dont work..
this display this error:
TypeError: Argument 1 of FormData.constructor does not implement interface HTMLFormElement.
var formData = new FormData(formData);
so.. what's worng here?
Thnx for the help!,
I resolve this..
Just change a little party on my code..
var submitHandler = function(form) {
$.ajax({
url: 'function/savePreInscripcion.php',
type: 'POST',
data: new FormData(form),
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(data){
alert(data);
}
});
};
Just I change the call to the form and put this directly on the data whit the next code: "data: new FormData(form)" and it work fine! =)

ajax form submit redirect like a not ajax form

I have this code that I use to submit a form with a attachment file
$("#career_form").submit(function(e){
var this_current = $(this);
var formData = new FormData(this_current[0]);
var url = this_current.attr("action");
$.ajax({
url : url,
data: formData,
type: 'post',
cache: false,
async: true,
beforeSend: function(){ },
success: function(response){
if(response === true){
alert("successfully sent");
}
}
});
e.preventDefault();
});
but the form keeps redirecting me to its destination file "url in the action" like it wasn't an ajax submission but if I replace the 'data' argument with
data: $(this).serialize();
it works (ajax submit), any ideas, help, suggestions, recommendations?
give that e.preventDefault(); at the beginning of the function.
jQuery trys to transform your data by default into a query string, but with new formData it throws an error.
To use formData for a jquery ajax request use the option processData and set it to false like:
$.ajax({
url : url,
data: formData,
type: 'post',
cache: false,
async: true,
processData: false,
beforeSend: function(){ },
success: function(response){
if(response === true){
alert("successfully sent");
}
}
});
Thats the reason why it works with serialize, but not with formData in your example.
The e.preventDefault works correctly, but if there is an error before it will not work. By placing the e.preventDefault at the top of your function it will allways prevent the action, no matter if there is an error in later code or not.
You can edit the var formData = new FormData(this_current[0]); in your code and use the below line:
var formData = new FormData(document.querySelector("#career_form"));
Also, if you are using multipart form to send files in your form, you need to set following parameters in your ajax call.
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
Hope this helps. See more about using formData here.
Try this:
$("#career_form").submit(function(e){
e.preventDefault();
var fd = new FormData(document.querySelector("form"));
fd.append("CustomField", "This is some extra data");
$.ajax({
url: "change-status.php",
type: "POST",
data: fd,
processData: false,
contentType: false,
success: function(response){
if(response){
alert("successfully sent");
}
}
});
});

How can I send files along with other field's data to webmethod is asp.net using jquery ajax call?

I have a webform which has x number of textboxes and y number of dropdowns etc
I am using this code to send data to webmethod at the server:
$.ajax({
type: "POST",
url: "SupplierMaster.aspx/RegisterSupplier",
data: JSON.stringify({
id: $('#txtbidderid').val(),
bidamt: $('#txtbidamt').val()
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data, status) {
alert(data.d);
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});
Now the problem is that I also want to include file attachments on this form.
How do I add the files to data: of $.ajax method?
I do not want to use external plugins etc unless absolutely necessary.
Lets say I modify my data object to look like this :
var dataToSend = {};
dataToSend.id = $('#txtbidderid').val()
dataToSend.bidamt = $('#txtbidamt').val()
dataToSend.append( 'file', input.files[0] );
What would the webmethod armument look like?
For example lets suppose it looks like this as of now:
[WebMethod] public static string SubmitBid(string id, string bidamt.....)
You can try something like this. You may need to manipulate content type.
var dataToSend = new FormData();
dataToSend.append( 'file', input.files[0] );
$.ajax({
url: "SupplierMaster.aspx/RegisterSupplier",
data: dataToSend,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
You cannot send file as application/json; charset=utf-8 to the server and so i suggest you to use application/x-www-form-urlencoded as contentType and also data as FormData as below.
$.ajax({
url: "SupplierMaster.aspx/RegisterSupplier",
type: 'POST',
data: new FormData(formElement),//Give your form element here
contentType: false,
processData: false,
success: function () {
//do success
}
});

Categories