How can send array as an data using ajax - javascript

Please see attached jsfiddle link, I need to collect data from multiple forms and combined the data as Single data array send it to server(spring mvc controller) to persist using ajax.post
Please let me know best way to do it, will my array be converted to Json by ajax call or I have to do some magic on it.
Thanks
http://jsfiddle.net/6jzwR/1/
<form id="form1" name="formone" class="myclass">
<input type="text" id="txt11" name="txt11" value="name1" />
<input type="text" id="txt12" name="txt12" value="name2" />
</form>
<form id="form1" name="formtwo" class="myclass">
<input type="text" id="txt21" name="txt21" value="name3" />
<input type="text" id="txt22" name="txt22" value="name4" />
</form>
<input type="button" id="button" value="Click Me" />
(function ($) {
$(document).ready(function () {
alert("serialize data :" + $('.myclass').length);
var mydata = null;
$('#button').on('click', function (e) {
$('.myclass').each(function () {
alert("serialize data :" + $(this).serialize());
if ((mydata === null) || (mydata === undefined)) {
mydata = $(this).serializeArray();
alert("My data is null");
} else {
mydata = $.merge(mydata, $(this).serializeArray());
alert("My data final data after merger " + test);
}
});
});
});
}(jQuery));

Try this:
var array = $('input[type="text"]').map(function() {
return $(this).val();
}).get();
alert(JSON.stringify(array));
Demo.

You can put all the forms' data in an array and join them with &
var formdata = []
$('.myclass').each(function(){
formdata.push($(this).serialize());
});
var data = formdata.join('&');
http://jsfiddle.net/6jzwR/3/

Related

get checkbox values from form and add to JSON string using JavaScript

attempting to pull form values and put them into localStorage via JSON string. This code works for everything but checkbox values. How do i also get checkbox values? Please and thanks!
<form id="myForm">
<input type="submit" name="submit" value="submitOrder">
</form>
const userOrder = {};
function getValues(e) {
// turn form elements object into an array
var elements = Array.prototype.slice.call(e.target.elements);
// go over the array storing input name & value pairs
elements.forEach((el) => {
if(el.type !== "submit" && el.type !=="button") {
userOrder[el.name] = el.value;
}
});
// finally save to localStorage
localStorage.setItem('userOrder', JSON.stringify(userOrder));
}
document.getElementById("myForm").addEventListener("submit", getValues);
console.log(localStorage.getItem('userOrder'));
use the .checked attribute of a checkbox to tell if it is checked or not
const userOrder = {};
function getValues(e) {
e.preventDefault();
// turn form elements object into an array
//you can also use Array.from(e.target.elements)
var elements = Array.prototype.slice.call(e.target.elements);
console.log(elements);
// go over the array storing input name & value pairs
elements.forEach((el) => {
if(el.type == "checkbox") {
userOrder[el.name] = el.checked;
}
});
console.log(userOrder);
// finally save to localStorage
//localStorage.setItem('userOrder', JSON.stringify(userOrder));
}
document.getElementById("myForm").addEventListener("submit", getValues);
//console.log(localStorage.getItem('userOrder'));
<form id="myForm">
<input type="checkbox" name="checkbox-0">
<input type="checkbox" name="checkbox-1">
<input type="checkbox" name="checkbox-2">
<input type="submit" name="submit" value="submitOrder">
</form>
You can use JQuery serialize() function.
Then, you can do something like this:
function onSubmit( form ){
var data = JSON.stringify( $(form).serializeArray() ); // <-----------
console.log( data );
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form onsubmit='return onSubmit(this)'>
<input name='user' placeholder='user'><br>
<input name='password' type='password' placeholder='password'><br>
<input type='checkbox' name='remember-me'>
<br />
<button type='submit'>Try</button>
</form>

Send only filled fields via GET

Look at simple form below:
<form method="GET" action="index.php">
<input type="text" name="price_min" >Min
<input type="text" name="price_max" >Max
</form>
When I send form with filled only one field, in my url I get empty values for not filled keys
(ex. index.php?price_min=).
Question:
How to remove empty keys from url?
You can parse serialized string and remove blank values. Then you can use post to necessary api using jQuery.
Sample
JSFiddle
$("#btn").on("click", function() {
var formjson = $("#frmTest").serialize();
var result = formjson.split("&").filter(function(val) {
return val.split("=")[1].length > 0;
}).join("&")
console.log("Serialized String:", formjson);
console.log("Processed String:", result);
// $.get('action.php', formjson, function(response){ ... })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form id="frmTest">
<input type="text" name="price_min">Min
<input type="text" name="price_max">Max
</form>
<button id="btn">Test Serialize</button>
Use jQuery to send the fields like this
$('your_form').submit(function() {
var min_price = $("#min_price").val();
var max_price = $("#max_price").val();
var string = "";
if(min_price.length > 0){
string += "min_price="+min_price
}
if(max_price.length > 0){
string += "&max_price="+max_price
}
window.location.href = 'index.php?'+string;
});
Hope it helps!

Merging List of JSONs into one JSON in javascript

I have an HTML form and I'm trying to stringify and parse its content into JSON on submission using javascript
for example:
<form id="form1" enctype="multipart/form-data">
<input type="hidden" name="presented" value="1" />
<input type="checkbox" name="RESPONSE" value="ch1">ch1</input>
<input type="checkbox" name="RESPONSE" value="ch2">ch2</input>
<input type="checkbox" name="RESPONSE" value="ch3">ch3</input>
<input id="submit_button" name="submit" type="submit"/>
</form>
and the javascript:
$(document).ready(function () {
$("#submit_button").click(function (e) {
e.preventDefault();
var formData = JSON.parse(JSON.stringify(jQuery('#form1').serializeArray()));
alert(JSON.stringify(formData));
});
});
I'm getting an output like this (considering that only the first two checkboxes are checked):
[{"name":"presented","value":"1"},
{"name":"RESPONSE","value":"ch1"},
{"name":"RESPONSE","value":"ch2"}]
but I'm expecting this result in one JSON with arrays for duplicated keys:
{"presented" : "1", "RESPONSE" : ["ch1", "ch2"]}
jsfiddle here
You will need to write your own serializer. For example to group values of the elements with the same name you could do something like this using Array.prototype.reduce:
$("#submit_button").click(function (e) {
e.preventDefault();
var formData = jQuery('#form1').serializeArray().reduce(function(prev, curr) {
if (prev.hasOwnProperty(curr.name)) {
prev[curr.name] = $.isArray(prev[curr.name]) ? prev[curr.name] : [prev[curr.name]]
prev[curr.name].push(curr.value);
}
else {
prev[curr.name] = curr.value;
}
return prev;
}, {});
document.querySelector('pre').innerHTML = JSON.stringify(formData, null, 4);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" enctype="multipart/form-data">
<input type="hidden" name="presented" value="1" />
<input type="checkbox" name="RESPONSE" value="ch1">ch1</input>
<input type="checkbox" name="RESPONSE" value="ch2">ch2</input>
<input type="checkbox" name="RESPONSE" value="ch3">ch3</input>
<input id="submit_button" name="submit" type="submit"/>
</form>
<pre></pre>
I think that your new object's value should always be an array for consistency. Here's how to build it:
var arr = [{"name":"presented","value":"1"},
{"name":"RESPONSE","value":"ch1"},
{"name":"RESPONSE","value":"ch2"}];
var newObj = {};
arr.forEach(function(item){
if(!newObj.hasOwnProperty(item.name)){
newObj[item.name] = [];
}
newObj[item.name].push(item.value);
});
And here's a way to build it exactly like you want it:
var newObj = {};
arr.forEach(function (item) {
if (!newObj.hasOwnProperty(item.name)) {
newObj[item.name] = item.value;
} else {
if (Object.prototype.toString.call(newObj[item.name]) !== '[object Array]') {
var newItem = newObj[item.name];
newObj[item.name] = [newItem];
}
newObj[item.name].push(item.value);
}
});
Think other than JSON parsing library. It's very simple Java Program using String.split() method that convert Json String into name> without using any library.

CKEDITOR: get data from multiple instance names in Javascript

Because I have multiple textareas in HTML code, I pass the id value through Javascript to retrieve the data in each textareas. However, in the JS function, the "CKEDITOR.instances.id" doesn't represent as expected such as CKEDITOR.instances.editor_1, CKEDITOR.instances.editor_2, or CKEDITOR.instances.editor_4, therefore, I don't have any data retrieved. Anyone knows how to fix this please let me. Heaps of thanks.
HTML code:
<textarea name="edit_1"></textarea>
<input type="button" value="submit" onClick="getValue('edit_1')" />
<textarea name="edit_2"></textarea>
<input type="button" value="submit" onClick="getValue('edit_2')" />
<textarea name="edit_2"></textarea>
<input type="button" value="submit" onClick="getValue('edit_3')" />
JS code:
var getValue = function(id) {
var content = CKEDITOR.instances.id.getData();
alert(content);
};
Try adding [] between id
var getValue = function(id) {
var content = CKEDITOR.instances[id].getData();
alert(content);
};
i had to do something like this as i was binding events to actions with multiple instances.
and trying to get the data but it would always return null for any one but the last... using the event (e.editor) worked though.
var editors = CKEDITOR.instances;
for (var x in editors) {
if (editors[x]) {
var thisName = editors[x].name;
if (editors[thisName]) {
editors[thisName].on('focus', function (e) {
socket.emit('ckeditor_field_type_edit', user, e.editor.name);
});
editors[thisName].on('key', function (e) {
var data = e.editor.getData();
socket.emit('ckeditor_field_type_typing', user, e.editor.name, data);
});
editors[thisName].on('blur', function (e) {
var data = e.editor.getData();
setTimeout(function () {
socket.emit('ckeditor_field_type_edit_finish', user, e.editor.name, data);
}, 1000);
});
}
}
}

How do I keep the previous value sent to JSON?

I would like to store the value of a input to JSON (on submit). If the User fill out the input again then submit I would like to add the new value to JSON keeping the previous one.
I use the following to add the input value to JSON but I'm not sure how to keep the previous value sent to JSON.
http://jsfiddle.net/ABE4T/
HTML:
<form method="post" name="myForm" id="myForm">
<input type="text" name="element" />
<input type="submit" value="Add" name="submit" />
</form>
<div id="display"></div>
Javascript:
$.fn.serializeObject = function()
{
var arrayData = this.serializeArray();
var objectData = {};
$.each(arrayData, function(){
if(objectData[this.name] != null){
if(!objectData[this.name].push){
objectData[this.name] = [objectData[this.name]];
}
objectData[this.name].push(this.value || '');
}
else{
objectData[this.name] = this.value || '';
}
});
return objectData;
};
$(document).ready(function(){
$("#myForm").submit(function(){
$('#display').text(JSON.stringify($("#myForm").serializeObject()));
return false;
});
});
Use .append() function instead of .text() function.
DEMO fiddle
You can maintain an array to hold all the values like this
$(document).ready(function(){
var values = [];
$("#myForm").submit(function(){
values.push($("#myForm").serializeObject());
$('#display').text(JSON.stringify(values));
return false;
});
});
Working Fiddle
You are overwriting the value in #display.
Change this line
$('#display').text(JSON.stringify($("#myForm").serializeObject()));
to
$('#display').text($('#display').text() + JSON.stringify($("#myForm").serializeObject()));
Fiddle

Categories