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

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
});

Related

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

send a form with serialize() function and extra data in ajax()

I'm programming a web page for a company in CI3, and I've another problem.
I need to send to wizard.php(controller)a serialized form and a javascript variable, but, I think that I can't send 2 variables at the same time, here is my code.
var idCompany =5;
$(document).on('submit', '#period-form', function(event) {
event.preventDefault();
$.ajax({
url: '<?php echo base_url()?>wizard/insertPeriod/'
type: 'POST',
dataType: 'json',
data: $("#period-form").serialize(),
success : function (json) {
$("#alert").append(json.response_alert);
},
error : function (xhre) {
console.log(xhre);
}
})
});
As you can see, idCompany is an attribute, it has value but, I put value in another function. is possible add values to a serialized form? or how I can send a serialized form and a variable at the same time?
The serialize function simply creates an URL query string from all the form elements. So you can manually add the variable to the result of the serialize() function like this:
data: $("#period-form").serialize() + '&idCompany=' + idCompany
var data = $('#period-form').serializeArray();
data.push({ name: "<somename>", value: "<somevalue>" });
You can use push method to add more name - value pairs.

Javascript/Ajax/Json: Sending objects and arrays

I have a form where people enter their clients into.
This form allows the user to add as many phone numbers, emails, and addresses as they want.
Phone and email have type and data fields for each added row (phone_type, phone_data) while Address has type, street, city, state, and zip fields for each row (address_type, address_street, address_city, address_state, address_zip).
So for example, when the user adds a phone field it adds:
<input type="text" name="phone_type[]" />
<input type="text" name="phone_data[]" />
I need to send the form data over Ajax to a PHP to process and store in database.
I've thought of storing it in array within an object.
phone = new Object();
var phone.data = new Array(),
phone.type = new Array();
$("input[name='phone_data[]']").each(function() {
if($(this).val() != '') {
phone.data.push($(this).val());
phone.type.push($('select[name="phone_type[]"]').val());
})
This doesn't seem to work. Am I even approaching this correctly?
Also, once I get it into an object that I send over Ajax to a PHP page, how do I grab the values?
serialize your form... use data of ajax to sent the serialize data to the server...
data:$('#YourFORMID').serialize();
here is the documentaiotn have alook to the examples...
http://api.jquery.com/jQuery.post/
and to grab the data in your PHP (if you are using ajax type as post)
$data=$_POST['phone_data'];
$type=$_POST['phone_type'];
if ajax type : GET
$data=$_GET['phone_data'];
$type=$_GET['phone_type'];
Are you trying to reinvent jQuery's serialize()
var frm = $("#myForm");
var values = frm.serialize();
//make Ajax call
$.post("someUrl", values, function(){} );
http://jsfiddle.net/BZcja/
You can most definitely use jQuery serialize(). In your event which triggers the processing you can do the following:
$.ajax({
type: "POST",
url: "your_php_processing_page.php",
data: $("#FormID").serialize(),
dataType: "json",
success: function(data){
// do stuff here
},
error: function() {
// do stuff here
}
});
In your_php_processing_page.php you can get the values as follows:
$phone_types = $_POST["phone_type"];
$phone_data = $_POST["phone_data"];

submitting form and variables together through jquery

I'm using 2 types of submit.
There is $.post
$.post('servers_side.php', { var1: var1, var2:var2},
function(result)
{
some code...
});
which sends separate variables to server side script.
And there is AjaxSubmit plugin which submits the whole form
$('#form').ajaxSubmit({success: function(result)
{
some code...
}
});
But now I have the following task let's say I have a form and a few variables which I must submit at the same time.
So Is that possible to submit form + some variables together ?
Update
And here is how you can submit:
var Vars = {var1: var1, var2:var2};
var varsData = $.param(Vars);
// form data
var formData = $('#formID').serialize();
var data = varsData + '&' + formData;
$.ajax({
type: 'POST',
url: 'servers_side.php',
data: data,
success: function(res){ alert (res) }
})
You can use jQuery.param() to convert an array or an object into url-friendly name-value paris. You may also need to use jQuery.serialize() to convert form data into name-value paris. Here is how you can go about:
var Vars = {var1: var1, var2:var2};
var varsData = $.param(Vars);
// form data
var formData = $('#formID').serialize();
var data = varsData + '&' + formData;
Now data contains all data of your custom vars and form elements you can send in ajax request.
Well, it's possible but code might look messy. As best practice you should add some hidden fields
<form>
.
.
.
<input type="hidden" name="var1" id="var1" />
<input type="hidden" name="var2" id="var2" />
<input type="hidden" name="var3" id="var3" />
.
.
.
</form>
And use this JavaScript to set values to these hidden fields
$("#var1").val("some data 1");
$("#var2").val("some data 2");
$("#var3").val("some data 3");
And you can carry on with your existing $.post() code

Push form name into POST data sent by Ajax

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'),
....

Categories

Resources