Submit form data as JSON - javascript

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

Related

How to detect that my select form have been change by ajax success

I have two form input ( text and select form ).
The select form change by ajax success when user search the employee data.
Now, i want the other jquery function that can automatically detect when the select form have been change by ajax success and retrieve the new value of select form to use by other function to make new data in my input text.
my Search Employee Function
function search_personal_result(formObj, urlres, responseDIV, disable_data, modal_class,result_data)
{
disable_data=disable_data||false;
modal_class=modal_class||false;
result_data=result_data||false;
var loading = '<p>Loading ...</p>';
$.ajax({
url: site_url+'/'+urlres,
beforeSend: function(){
$(responseDIV).html(loading);
},
data: $(formObj).serialize(),
type: "post",
dataType: "html",
success: function(response){
//proceed data result here
if(result_data==false){
var obj = jQuery.parseJSON(response);
$.each(obj, function (index, value) {
if(result_data==false){
for(var j in value){
//My SELECT Form Changed here
$('#VCIDSBU').val('MY NEW VALUE');
}
}
});
}
},
error: function(){
alert("Terjadi kesalahan!");
},
});
}
If the user search the employee data using search_personal_result, my select form have been successfully changes.
Now that i need is, how to make the other jQuery function that can detect that my SELECT Form have been changed by search_personal_result
I have try using
$(function () {
$('#form_create_sp').on('change','SELECT#my_select_id',function(){
alert('it changes');
});
})
It can only detect when the user manually change the select form. but not working when the select form changed by search_personal_result
Thanks for all expert here
You could always do some sort of console.log("Success"); Function based on if it sent or not.

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/

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.

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"];

jQuery AJAX with Multiple Array data Parameters

I've successfully posted a single array, but I can't figure out how to send more than one array in an AJAX post. Here is my code for one array:
var a = new Array();
// fill array
var a_post = {};
a_post['array1[]'] = a;
$.ajax({
url: "submitOrder.php",
data: a_post,
type: 'post',
success: function(data) {
alert(data);
}
});
And in submitOrder.php I have:
$array1= $_POST['array1'];
foreach ($array1 as $a => $b)
echo "$array1[$a] <br />";
This works fine. However, when I try to add a second array b_post to the data: field, it doesn't work. I tried data: {a_post, b_post}, and a few variations of that, but I can't get it to work properly. While I'm at it, how would I then load submitOrder.php after posting rather than show an alert of the data?
UPDATE
Using Nicolas' suggestion, I got this to work changing the data field to:
data: {'array1':JSON.stringify(a), 'array2':JSON.stringify(b)},
However, I also need to add the rest of the form data that has been input by the user. I can get this data with $(this).serialize() but if I try to add that to the data field, it does not work. How can I add this data to the above line?
Thanks.
SOLUTION
What ended up working the way I originally had hoped for (with Nicolas' help):
var formData = $(this).serializeArray();
var a_string = JSON.stringify(a);
formData.push({name: 'array1', value: a_string});
var b_string = JSON.stringify(b);
formData.push({name: 'array2', value: b_string});
$.ajax({
url: "submitOrder.php",
data: formData,
type: 'post',
success: function(data) {
alert(data);
}
});
The data should be encapsuled this way
data: {'first_array':JSON.stringify(array1),'second_array':JSON.stringify(array2)}
Then in PHP:
$array1 = json_decode($_POST['first_array']);
$array2 = json_decode($_POST['second_array']);
You can add the rest of the inputs as well.
data: {'first_array':JSON.stringify(array1),'second_array':JSON.stringify(array2),'input1':$(input[name="input1"]).val()}
Just repeat with all the inputs you want to send.
'input1':$(input[name="input1"]).val(),'input2':$(input[name="input2"]).val(),... etc

Categories

Resources