Push form name into POST data sent by Ajax - javascript

I'm collecting all data from form input fields with serialize() function. But it doesn't include submit button value even if I pressed submit button. How to push form name into POST data (IN my case i wanna push form name into formData variable)?
The code looks like that
$("#signup_form").submit(function () {
var form = $(this),
formData = form.serialize(),
formUrl = form.attr('action'),
formMethod = form.attr('method');
....

Append it to the query string generated by serialize I guess. I'm not quite sure what you're doing with the form data in the rest of your function, full code may help, but the snippet below is probably sufficient.
$("#signup_form").submit(function () {
var form = $(this),
formData = form.serialize() + '&formName=' + form.attr('name'),
formUrl = form.attr('action'),
formMethod = form.attr('method'),
....

Related

Textarea value not resetting in post action with Ajax

I'm using PHP and Ajax to post without page refresh. Everything works fine but the textarea content is not reset after submitting the form.
This is my Ajax code:
$("#new_post__add").submit(function(event){
event.preventDefault();
var post_url = $(this).attr("action");
var request_method = $(this).attr("method");
var form_data = $(this).serialize();
$.ajax({
url : post_url,
type: request_method,
data : form_data
}).done(function(response){ //
$("#load_data").html(response);
});
});
How can I reset the textarea value after successfully submitting the form? can you please edit my code?
You can also reset all elements within the form by doing any of the following
$('#new_post__add').trigger('reset');
$('#new_post__add')[0].reset();
document.getElementById('#new_post__add').reset();
Inside the done callback, you can target the text area element and clear it.
textarea.value = '';
$("#new_post__add").submit(function(event){
event.preventDefault();
var post_url = $(this).attr("action");
var request_method = $(this).attr("method");
var form_data = $(this).serialize();
$.ajax({
url : post_url,
type: request_method,
data : form_data
}).done(function(response){ //
$("#load_data").html(response);
$('#new_post__add textarea').val(""); //this is assuming there is only one textarea inside your form
});
});
Try using success instead of done. Depending on the version, success may or may not be deprecated.
$("#new_post__add").submit(function(event){
event.preventDefault();
var post_url = $(this).attr("action");
var request_method = $(this).attr("method");
var form_data = $(this).serialize();
$.ajax({
url : post_url,
type: request_method,
data : form_data
}).success(function(response){ //
$("#load_data").html(response);
});
});
If it still doesn't work, I'd add fail and always handlers with console.log output to see what's happening. If you're sure success is not deprecated in your version, then the equivalent are error and complete. Or maybe I've mixed versions. Hell, you can have all six, and see which get called!

Create FormData excluding not provided input file

I submit a form manually via jQuery. I use FormData with all input elements from this form.
See code below:
$("#submit-form").on('submit', function (event) {
event.preventDefault();
var form = $('#submit-form')[0];
var data = new FormData(form);
$.ajax({
type: "POST",
url: "my-best-handler",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 60000
});
});
One of input elements is file and it's optional to set it. When it's not set, I don't need to use it in FormData and be sent with other elements to request handler.
The problem is that currently it will be sent even if it's not set.
I'm curious how I can exclude it from FormData if it's not set.
In worst case I can create FormData manually like here.
But I hope there is "black list" like approach by removing just not set file from FormData OR any other elegant way.
Update:
I came with the following solution:
if (!$("#input-file").val()) {
data.delete('input-file');
}
You can use the delete() function to remove your field
var form = $('#submit-form')[0];
var data = new FormData(form);
if (!$("#input-file").val()) {
data.delete('input-file');
}
Disabling input approach.
Disabled form controls never get submitted
$("#submit-form").on('submit', function (event) {
event.preventDefault();
// disable before creating FormData
$(this).find(':file').prop('disabled', function(){
return !this.files.length;
});
var form = $('#submit-form')[0];
var data = new FormData(form);
As mentioned in comments should re-enable in ajax success callback

Submit form data as JSON

I have to recreate a form that was originally created using Jotform - it is here. I am struggling in one area. It is a pretty simple form, the only caveat being the ability to duplicate a form field form multiple entries. That part can be seen here. When the form is duplicated, I need to submit the form data as a JSON array. In the fiddle, I didn't put the regular form fields, here is how they and the cloned field need to submit the data.
q2_fullName[first]:test
q2_fullName[last]:test
q1_currentCommission1:[{"Instruments":"a","Commissions":"1","Margins":"a"},{"Instruments":"b","Commissions":"2","Margins":"b"},{"Instruments":"c","Commissions":"3","Margins":"c"}]
normally in my $.ajax handler, I just serialize the data, but that doesn't work in creating the json array for the cloned fields. Normally like so:
submitHandler: function(form) {
var dataString = $(form).serialize();
$.ajax({
type:'POST',
url: form.action,
data: dataString,
dataType: "json",
beforeSend: function(data){
//before send
},
success: function(data){
//success function
}
});
return false;
},
I need to somehow serialize the non cloned fields (I think) and create a json array out of the cloned values and assign them a key name
You can build the post data and the json string like this :
var data = {
// get/set the firstname etc
"q2_fullName":{
"first":"", // get firstname ie $("#first_2").val(),
"last":""
},
"q1_currentCommission1" :""
},
commisions = [];
$('.InsContain').each(function() {
var $inputs = $(this).find('input');
commisions.push({
"Instruments" : $inputs.eq(0).val(),
"Commissions" : $inputs.eq(1).val(),
"Margins" : $inputs.eq(2).val()
});
});
data.q1_currentCommission1 = JSON.stringify(commisions);
Posted data :
q2_fullName[first]:aaa
q2_fullName[last]:123
q1_currentCommission1:[{"Instruments":"1","Commissions":"1","Margins":"1"}]
Update fiddle here

How to send image to .net Webservice using Ajax in IE8?

The folowing post is related to: How to send image to PHP file using Ajax?
I managed to get this working as per the above post, but it fails to work on IE8.
Is there a way to get this to work on ie8+?
Here is my code:
$("form[name='uploader']").submit(function(e) {
var formData = new FormData($(this)[0]);
$.ajax({
url: dotnetpage,
type: "POST",
data: formData,
async: false,
success: function (msg) {
$('.js-ugc-image').attr('src', msg);
},
cache: false,
contentType: false,
processData: false
});
e.preventDefault();
});
IE 8 does not have formdata, you can use a hidden iframe and post it and read the results.
I've used a technique that was something like this
Clone the form, move original form into a hidden iframe (this needs to be done because you cant clone or set input type files value on IE) and then submit and read the result of the submit.
Something like this which is a code i used before and worked:
var $form = $('your form');//GET YOUR FORM
//Create Hidden iframe
var _hiddenIframe = $('<iframe id="_hiddenframe" style="display:none;"></iframe>');
//Create Copy Form and add the attributes of the original
var _copyForm = $('<form id="_copyForm" name="_copyForm" style="">');
_copyForm.attr({'method':$form.attr('method'),'action':$form.attr('action'), 'enctype':$form.attr('enctype')});
//Get original fields
$original = $form.children('*');
//Clone and append to form
$original.clone(true).appendTo($form);
//send the original fields to hidden form
$original.appendTo(_copyForm);
//Add the iframe to the body
_hiddenIframe.appendTo('body');
//Add the form to the hidden iframe
_copyForm.appendTo(_hiddenIframe.contents().find('body'));
var $r;
//submit the form
_copyForm.submit();
//after it reloaded(after post)
_hiddenIframe.on('load',function(){
//read result (maybe a json??)
$r = $.parseJSON(_hiddenIframe.contents().find('body').text());
//Do something with the result
if($r.result=='ok'){
//Do Something if ok
}
else{
//Do Something if error
}
});
No,sorry, IE8 doesn't support the FormData object. (See http://caniuse.com/#search=formdata)
Whay you can do is embed the <input type='file > tag in a separate form and submit it using jQuery.

How to simply send a request parameter with jquery form submit?

I am able to submit a form as Post type using the following in my javascript:
$("#receiptsForm").submit();
But I also want send across a parameter myparam as well with the request which I'll be retrieving in my spring controller using httpServletRequest.getParameter("myparam"):
var myparam = "abc";
$("#receiptsForm").submit();
What's the best I can do?
try this
function form_submit()
{
//var myparam = "abc";
// add hidden field to your form name="myparam" and value="abc"
$('#receiptsForm').append('<input type="hidden" name="myparam " value="abc" />');
$("#receiptsForm").submit();
}
Try this,
var input = $("<input>")
.attr("type", "hidden")
.attr("name", "mydata").val("bla");
$('#receiptsForm').append($(input));
$('#receiptsForm').submit();
Try using serializeArray
var data = $('#receiptsForm').serializeArray();
data.push({name: 'myparam', value: 'MyParamValue'});
You can send the data like:
$.ajax({
...
data: data,
...
});
Looks like you are using jquery..there are a couple of ways this can be done..either you can make it a object and then pass it as data in an ajaxrequest
var myparam = "abc";
var data_to_be_sent = {"myparam":myparam};
then in the data field of the ajax request, you can
data : data_to_be_sent.
Or you simply have a hidden field in the form and then on submit you can give it a value of myparam
There are two ways that spring to mind
a) include a hidden form field called myparam in your form, and the use jquery to populate it with abc before submitting.
b) use Jquery's ajax to call a ajax post, and before doing this set the data parameter.
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});

Categories

Resources