How to get form data with multi select in checkboxs - javascript - javascript

I have a form that I want to get all his values, and convert them to json object.
the problem is that I not get the multiselect fields, just one field.
this is my code
what I am missing?
let reportDropDowns = $('#getReport').serialize();
reportDropDowns = decodeURI(reportDropDowns);
let reportDropDownsJson = {};
reportDropDownsJson = JSON.parse('{"' + reportDropDowns.replace(/&/g, '","').replace(/=/g,'":"') + '"}', function(key, value) { return key===""?value:decodeURIComponent(value) });
this is my html

Instead of serializing the data directly via .serialize(), you should instead use .serializeArray() to get the data as an array. You can then manipulate the array into an object/JSON. Try this
let reportDropDownsJson = {};
$('#getReport').serializeArray().forEach(({name, value}) => {
if( reportDropDownsJson.hasOwnProperty(name) ){
if( !Array.isArray(reportDropDownsJson[name]) ){
reportDropDownsJson[name] = [reportDropDownsJson[name]];
}
reportDropDownsJson[name].push(value);
}else{
reportDropDownsJson[name] = value;
}
});

Related

How Do I Create a $_POST array from textarea input

Here is what I am trying to do.
I have a textarea input box, I would like to enter in data in an array format like this into that textarea box
'key1'='value1'
'key2'='value2'
'key3'='value3'
I then want to take this data and use it in my ajax call like so
var a = $("textarea#array_box").val().split('\n');
$.ajax({
url: 'index.php/controller/function',
type: "POST",
data: a,
success: function(data) {
console.log(data);
I am trying to get the data to pass in so that in the controller if i did one of the return statements below I would get the resulting output.
return $_POST['key1'] // should return 'value1'
return $_POST['key2'] // should return 'value2'
return $_POST['key3'] // should return 'value3'
How do I code this so that I can type into my textarea box an array, and pass that array into my controller as a $_POST?
based on your code, you can do something like this:
<?php
$tempvar=$_POST['data'];
$result = array();
foreach($tempvar as $tempitem){
$tempitem=str_replace("'","",$tempitem); //we get rid of the ' symbols
$t=explode("=",$tempitem); //' divide them by the "=" symbol
$result [$t[0]]=$t[1];
}
//the result variable now holds the array
echo $result['key1'] // value1
?>
You can use .filter(Boolean) to remove empty elements from a array; $.each() to iterate a array, .trim() to remove space characters, .replace() with RegExp /=(?=')/ to replace = with :; RegExp /'/g to replace ' with "; create a string to concatenate string at each iteration; JSON.stringify() following $.each(); pass result of JSON.stringify() to JSON.parse() as data to POST
$("button").click(function() {
var a = $("textarea#array_box").val().split("\n").filter(Boolean);
var textareaData = "";
$.each(a, function(key, value) {
textareaData += value.trim()
.replace(/=(?=')/, ":")
.replace(/'/g, '"')
+ (key < a.length - 1 ? "," : "");
});
textareaData = JSON.stringify("{" + textareaData + "}");
console.log(textareaData);
$.ajax({
url: "/echo/json/",
type: "POST",
data: JSON.parse(textareaData),
success: function(data) {
console.log(data);
}
});
});
jsfiddle https://jsfiddle.net/ahnegop3/3/
ajax data format must be {key:value,key,value} .So to getting that format , you need do a little loop with $.each and do assign key and value by like this
object[key] = value
var a = $("textarea#array_box").val().split('\n');
var temp = [];
$.each(a,function(i,v){
s = v.split("="); //split again with =
s[0] = s[0].replace(/'/g,""); //remove ' from string
s[1] = s[1].replace(/'/g,"");
temp.push(s[0],s[1]);
});
a = {};
//creating data objects
$.each(temp,function(i,v){
if(i % 2 == 0){
a[temp[i]] = temp[++i];
}
});

How to get records from object without knowing keyname?

I am struggling with the following:
I have a JSON feed with my data (https://api.myjson.com/bins/1sz7s). I iterate through all ReportItems in this object through javascript / jquery.
Problem I am having is I want to fetch 'records' that contain a specific value, but without knowing the key's name. Basically some kind of if_exists(ID):
$.each(tabledata.ReportItems, function (key, val){
var ID = "value";
if (ID in ReportItems) {
alert("Found!");
};
It's easy when you know the keyname:
$.each(tabledata.ReportItems, function (key, val){
var ID = "value";
if (ID == val.keyname) {
alert("Found!");
};
I guess this is what you are asking for:
var a = {"ReportItems":[{"Id":"cf92aefb-b857-49ce-b568-722329377e5d","CampaignId":"384f5c87-f8c7-43a6-9deb-76340dcf4cd4","CompanyId":"3ae13b97-7a09-4342-8953-c1d5a55687db","Name":"Item_7699","Price":1577.0,"Enabled":true,"Start":"2015-06-03T16:55:27.1388252+02:00","End":"2015-06-08T16:55:27.1388252","PublicationId":"19031fa7-2288-4466-94d6-6909d2ed2aa1","MediaId":"91089a91-a4d3-436a-b853-9370972006f3","ItemType":1,"DateStatistics":[{"Date":"2015-06-03T16:55:27.1388252","ScanCount":1138,"ResponseCount":8530},{"Date":"2015-06-04T16:55:27.1388252","ScanCount":4429,"ResponseCount":3556},{"Date":"2015-06-05T16:55:27.1388252","ScanCount":9822,"ResponseCount":121},{"Date":"2015-06-06T16:55:27.1388252","ScanCount":3791,"ResponseCount":3569},{"Date":"2015-06-07T16:55:27.1388252","ScanCount":7275,"ResponseCount":1922},{"Date":"2015-06-08T16:55:27.1388252","ScanCount":7243,"ResponseCount":141}]},{"Id":"47de9aaa-8424-4461-ba72-ae2922777650","CampaignId":"384f5c87-f8c7-43a6-9deb-76340dcf4cd4","CompanyId":"50ede412-4eb0-429b-8d73-a1bfef41ebbc","Name":"Item_7699","Price":1577.0,"Enabled":true,"Start":"2015-06-03T16:55:27.1418263+02:00","End":"2015-06-08T16:55:27.1418263","PublicationId":"19031fa7-2288-4466-94d6-6909d2ed2aa1","MediaId":"91089a91-a4d3-436a-b853-9370972006f3","ItemType":1,"DateStatistics":[{"Date":"2015-06-03T16:55:27.1418263","ScanCount":1138,"ResponseCount":8530},{"Date":"2015-06-04T16:55:27.1418263","ScanCount":4429,"ResponseCount":3556},{"Date":"2015-06-05T16:55:27.1418263","ScanCount":9822,"ResponseCount":121},{"Date":"2015-06-06T16:55:27.1418263","ScanCount":3791,"ResponseCount":3569},{"Date":"2015-06-07T16:55:27.1418263","ScanCount":7275,"ResponseCount":1922},{"Date":"2015-06-08T16:55:27.1418263","ScanCount":7243,"ResponseCount":141}]}],"Companies":{"8df135f4-db42-486c-8d8c-fbbdd561c25e":"Phillips","47d946e3-56db-4bc7-8472-3809eb48506d":"Bauknecht","3ae13b97-7a09-4342-8953-c1d5a55687db":"Capitol","fb017214-dbc1-4b71-8080-4f9b530f4b49":"Bosch","50ede412-4eb0-429b-8d73-a1bfef41ebbc":"LG Corp"},"Campaigns":{"0950aea6-69f3-42c1-99e5-25342c6262ae":"Campagne A","384f5c87-f8c7-43a6-9deb-76340dcf4cd4":"Campagne B"},"Media":[{"Id":"5999703b-a12e-49ad-b054-46875b88ff3a","Name":"Krant","Publications":{"e63f1212-5a21-4546-861c-640007989f08":"Telegraaf","13c3caa6-fcb8-4247-9cf7-8bfe0a0b5056":"Metro","3ddb7f5d-5e28-48ba-8345-5c4e3c7f76c0":"De Volkskrant"}},{"Id":"91089a91-a4d3-436a-b853-9370972006f3","Name":"Televisie","Publications":{"2eac3fd8-b8ed-47b7-8f14-664c3c55425a":"Rtl 4","defab016-d28e-4cf4-b814-0002169cf4cb":"MTV","19031fa7-2288-4466-94d6-6909d2ed2aa1":"Discovery Channel"}},{"Id":"e8610914-52b2-4b38-bc91-bf1bd6d63035","Name":"Radio","Publications":{"3585993c-56b4-4f7d-ac9c-a325eae2e78f":"SkyRadio","15e40597-e479-4a8f-9b25-f39ba90f2c19":"Radio 538","638e1141-f21c-42f1-acd1-652d265c32a1":"Slam FM"}}]};
var result = [];
$.each(a.ReportItems[0], function(k,v){
var specificValue = "cf92aefb-b857-49ce-b568-722329377e5d";
if(v == specificValue){
result[k]=v;
}
})
console.log(result);
Since you don't already know keynames, you can iterate through val properties to match value
$.each(tabledata.ReportItems, function (key, val){
var ID = "value";
for (var keyname in val) {
if (ID == val[keyname]) {
alert("Found!");
}
}
});

How to insert a json object into an unordered list

I have a json object that i created using obj = JSON.parse(data). "data" was recieved from a webserver. I know the object is correct because i can print single variables from it into a div or my list.
This is what is the json object is created from:
[{"name":"Staurikosaurus","group":"Saurischia","diet":"Carnivore","period":"Triassic"},{"name":"Diplodocus","group":"Saurischia","diet":"Herbivore","period":"Jurassic"},{"name":"Stegosaurus","group":"Ornithischia","diet":"Herbivore","period":"Jurassic"},{"name":"Tyrannosaurus","group":"Saurischia","diet":"Carnivore","period":"Cretaceous"}]
Literally all i want to do is put this into a to show up on a web page.
My current code:
function getJson(){$.get(MY URL, function(data) {
// String
//console.dir(data);
// Parse JSON
var obj = JSON.parse(data);
// JSON object
//console.dir(obj);
$('#myList').html("<li>"+obj[0].period+"</li><li>"+obj[2].period+"</li>");
//$('#myList').html("<li>obj[2].period</li>");
});
}
This successfully prints out the list with Triassic then Jurrasic.
I would prefer to do this in Jquery but javascript is okay.
Thank You.
You are not iterating through the list, just printing out the 0-th and 2nd element in the array. Try:
function getJson(){$.get(MY URL, function(data) {
// String
//console.dir(data);
// Parse JSON
var obj = JSON.parse(data);
// JSON object
//console.dir(obj);
var inner = '';
for(i=0; i < obj.length; i++) {
inner += "<li>"+obj[i].period+"</li>";
}
$('#myList').html(inner);
});
}
I'm sure there's a cleaner way using jQuery but that should work
If you're want to use the jQuery syntax, process like this:
var listElement = '';
$.each(obj, function(index, value) {
listElement += '<li>' + data[obj].period + '</li>';
})
$('#myList').html(listElement);

chrome.storage.local.get results in "Undefined" when called

I'm building a chrome extension, and I needed to save some data locally; so I used the Storage API . I got to run the simple example and save the data, but when I integrated it with my application, it couldn't find the data and is giving me "Undefined" result.
Here is my Code:
function saveResults(newsId, resultsArray) {
//Save the result
for(var i = 0; i < resultsArray.length; i++) {
id = newsId.toString() + '-' + i.toString();
chrome.storage.local.set({ id : resultsArray[i] });
}
//Read and delete the saved results
for(var i = 0; i < resultsArray.length; i++) {
id = newsId.toString() + '-' + i.toString();
chrome.storage.local.get(id, function(value){
alert(value.id);
});
chrome.storage.local.remove(id);
}
}
I am not certain what type of data you are saving or how much, but it seems to me that there may be more than one newsId and a resultsArray of varying length for each one. Instead of creating keys for each element of resultsArarry have you considered just storing the entire thing as is. An example of this would be:
chrome.storage.local.set({'results':[]});
function saveResults(newsId, resultsArray) {
// first combine the data into one object
var result = {'newsId':newsId, 'resultsArray':resultsArray};
// next we will push each individual results object into an array
chrome.storage.get('results',function(item){
item.results.push(result);
chrome.storage.set({'results':item.results});
});
}
function getResults(newsId){
chrome.storage.get('results', function(item){
item.results.forEach(function(v,i,a){
if(v.newsId == newsId){
// here v.resultsArray is the array we stored
// we can remove any part of it such as
v.resultsArray.splice(0,1);
// or
a.splice(i,1);
// to remove the whole object, then simply set it again
chrome.storage.local.set({'results':a});
}
});
});
}
This way you don't need to worry about dynamically naming any fields or keys.
First of All thanks to Rob and BreadFist and all you guys. I found out why my code wasn't working.
Storage.Set doesn't accept the key to be an 'integer' and even if you try to convert that key to be a 'string' it won't work too. So I've added a constant character before each key and it worked. Here's my code.
function saveResults(Id, resultsArray) {
var key = Id.toString();
key = 'a'.key;
chrome.storage.local.set({key : resultsArray});
}
function Load(Id) {
var key = Id.toString();
key = 'a'.key;
chrome.storage.local.get(key, function(result){
console.debug('result: ', result.key);
});
}

how to insert data in array inside form input elements

I have an array and it has some data in it. This array contains id, firstname, lastname, email, phone. I also have five form input elements. Now I want to add data in array in these elements. For example, ID should be inserted in ID form field, name should be inserted in name input element etc. how can I achieve this?
here is my code
insert_data_in_form: function(data) {
var form = $("#dataform");
var form_arr = new Array();
form.each(function(i) {
var form_el = form.children("input[type='textfield']");
form_arr.push(form_el);
console.log(data.length);
//for(var j = 0; j < 5; j++) {
form_el.val(data[i]);
//}
});
}
If the values in data array are in the same order as they are in the form then you can do this
insert_data_in_form: function(data) {
var formElems = $("#dataform input[type='text']");
formElems.each(function(i,elem) {
$(this).val(data[i]);
// or even better use the following faster way
// if they are always text boxes
// this.value = data[i];
});
}
Demo: http://jsfiddle.net/joycse06/AJhEW/
UPDATE (Alternate Way):
You can also achieve this using Implicit Looping with this .val(function(index,val) variant of the .val() function like this
var insert_data_in_form = function(data) {
var formElems = $("#dataform input[type='text']");
formElems.val(function(i) {
return data[i];
});
};
Demo: http://jsfiddle.net/joycse06/AJhEW/2/
el -> arr:
form_arr[form_el.attr('name')] = form_el.val();
arr -> el:
form_el.val(form_arr[form_el.attr('name')]);

Categories

Resources