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

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.

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

Jquery ajax add variable with serialize [duplicate]

I want to add extra data after i use $('#myForm').serialize() + extra data
$.ajax({
type: 'POST',
url: $('#myForm').attr('action'),
data: $('#myForm').serialize(), // I WANT TO ADD EXTRA DATA + SERIALIZE DATA
success: function(data){
alert(data);
$('.tampil_vr').text(data);
}
});
What kind of data?
data: $('#myForm').serialize() + "&moredata=" + morevalue
The "data" parameter is just a URL encoded string. You can append to it however you like. See the API here.
Personally, I'd append the element to the form instead of hacking the serialized data, e.g.
moredata = 'your custom data here';
// do what you like with the input
$input = $('<input type="text" name="moredata"/>').val(morevalue);
// append to the form
$('#myForm').append($input);
// then..
data: $('#myForm').serialize()
That way, you don't have to worry about ? or &
You can do it like this:
postData[postData.length] = { name: "variable_name", value: variable_value };

Making Key Value pair for the form elements in JavaScript

I have a module where the forms created are dynamic. So the number of inputs can defer always. Also, the array key can also defer.
My current method of posting form is this:
name = form_options[option_1] value = 1
On submitting the form using POST, I get the form as array in $_POST, which looks like this.
form_options(
option_1 => 1
)
But, now I am trying to implement the same thing using AJAX. So, I would need a common module to get all form values.
I found a way to do it.
var objectResult = $('#options_form').serializeArray();
console.log(objectResult);
This gives me a result like this:
0: Object
name: "form_options[option_1]"
value: "1"
How can parse this result to get an array like $_POST array, which I can send as data in AJAX.
P.S: All the form elements have name field as form_options[key]
You should use this for get post data in PHP file.
// You can use like this
var objectResult = $('#options_form').serializeArray();
$.ajax({
type: "POST", // Enter Request type GET/POST
url: 'action.php', // Enter your ajax file URL here,
dataType: 'json', // If you are using dataType JSON then in php file use die( json_encode($resultArray) );
data: objectResult, // Put your object here
beforeSend: function(){
alert('before');
},
error: function(data) {
console.log(data);
},
success: function(response){
console.log(response);
}
});
// In php file get values like this way
$_POST['form_options']
try like this,
In JQuery:
var objectResult = $('#options_form').serializeArray();
$.ajax({
type: 'POST',
url: 'yoururl'',
data: objectResult ,
success:function(data){
alert(data);
}
});
In your php:
<?php echo var_dump($_POST);?>
You can use jquery serialize with ajax directly, there is no need to use serializeArray:
$.ajax({
type:"post",
url:"formHandleSkript.php",
data: $("#options_form").serialize(),
success: function(response){
$(".result").html(response);
}
});
For more information see http://api.jquery.com/serialize/

Ajax Error Potentially Due to Incorrect Data Object Being Passed

Hi I am new to ajax and I am attempting to pass a Json to a Database, but I am not that far yet. Currently I am attempting to be verified that the data I am passing is being done successfully. However, I always drop into the ajax error method. I will upload my code and the way the data looks and then the error.
Thank you for your help!
<script>
function updateTable()
{
alert("Do i try to update table?");
document.getElementById("testLand").innerHTML = "Post Json";
//echo new table values for ID = x
}
function popupClick (){
var popupObj = {};
popupObj["Verified_By"] = $('#popupVBy').val();
popupObj["Date_Verified"] = $('#popupDV').val();
popupObj["Comments"] = $('#popupC').val();
popupObj["Notes"] = $('#popupN').val();
var popupString = JSON.stringify(popupObj);
alert(popupString);
$.ajax({
type: "POST",
dataType: "json",
url: "popupAjax.php",
data: popupObj,
cache: false,
success: function(data)
{
alert("Success");
updateTable();
},
error: function(data)
{
alert("there was an error in the ajax");
alert(JSON.stringify(data));
}
});
}
</script>
JSON Being Passed shown in var popupString:
Error:
popupAjax.php file (warning it's testy)
<?php
echo "Testing tests are testy";
?>
You are specifying the dataType as json. But this is the returned data type, not the type of the data you are sending.
You are returning html / text so you can just remove the dataType line:
type: "POST",
url: "popupAjax.php",
If you do want to return json, you need to build your datastructure on the server-side and send it at the end. In your test-case it would just be:
echo json_encode("Testing tests are testy");
But you could send a nested object or array as well.
As an additional note, you can use .serialize() on your form (if you use a form...) so that jQuery automatically builds an object that you can send in the ajax method. Then you don't have to do that manually.

How to send a parameter in data attribute of $.ajax() function in following scenario?

I've written one AJAX function code as follows :
$('#form').submit(function(e) {
var form = $(this);
var formdata = false;
if(window.FormData) {
formdata = new FormData(form[0]);
}
var formAction = form.attr('action');
$.ajax({
type : 'POST',
url : 'manufacturers.php',
cache : false,
data : formdata ? formdata : form.serialize(),
contentType : false,
processData : false,
success: function(response) {
if(response != 'error') {
//$('#messages').addClass('alert alert-success').text(response);
// OP requested to close the modal
$('#myModal').modal('hide');
} else {
$('#messages').addClass('alert alert-danger').text(response);
}
}
});
e.preventDefault();
});
Now here in data attribute I want to send some additional parameters with values in data attribute. How should I send these parameters to PHP file?
For clear understanding of my issue refer the following AJAX function code that I've written previously :
function GetPaymentRequest(status){
var status = $('#status_filter').val();
$.ajax({
type: "POST",
url: "view_payment_request.php",
data: {'op':'payment_request_by_status','request_status':status},
success: function(data) {
// alert(data);
}
});
}
In above function code you can see that I've passed few parameters with values viz. 'op':'payment_request_by_status','request_status':status in data attribute.
Exactly same parameters I want to pass in first AJAX function code. The already mentioned parameter "formdata ? formdata : form.serialize()" should also be there.
How should I do this? Can someone please help me in this regard?
Thanks in advance.
Add by using $.param
form.serialize() + '&' + $.param({'op':'payment_request_by_status','request_status':status});
or use serializeArray() and push new items
var data = form.serializeArray();
data.push({name:'op',value:'payment_request_by_status'}).push({name:'request_status',value:status});
then pass data
What you can do is, add two hidden fields to your already existing form, name one of them as op and set the value as payment_request_by_status and another one as request_status and the value based on the status.
When the form is serialized, it will automatically send these values also.

Categories

Resources