I want to receive the value thought iterator, when I use
$('#someModal').find('input[name=nameProBangHHModal]').val(data[0].TenNhanQuyCach);
it works as expected.
But when I use an iterator, the return shows [object Object].TenNhanQuyCach - not the data returned.
I try to search for other topic but I'm stuck on this. How to get the data returned in array[data[0]] with the value from the iterator method?
Thank you for your time!
$.ajax({
url: 'someurl to retrive data',
type: 'POST',
data: {id:id},
success: function(data,status) {
var tenCot = ['nameProBangHHModal','valueBangHHModal',];
var tenCotTrongCsdl = ['TenNhanQuyCach','DonViTinh',];
console.log(tenCotTrongCsdl[0]);
for (i=0;i <= tenCot.length - 1;i++) {
$('#someModal').find('input[name="' + tenCot[i] + '"]').val(data[0]+'.'+tenCotTrongCsdl[i]');
}
oh i find out the answer after search topic for array: this one: How can I access and process nested objects, arrays or JSON?.
and find out that need to use [] for variable, not the ".".
this one work for me:
$('#someModal').find('input[name="' + tenCot[i] + '"]').val(data[0][tenCotTrongCsdl[i]]);
I am banging my head trying to figure this out. And it should not be this hard. I am obviously missing a step.
I am pulling data from: openaq.org
The object I get back is based on a JSON object.
For now, I am using jQuery to parse the object and I am getting to the sub portion of the object that hold the specific parameter I want but I can't get to the specific key,value pair.
The object does not come back in the same order all the time. So when I tried to originally set up my call I did something like
obj.results.measurements[0].
Well since the obj can come back in an random order, I went back to find the key,value pair again and it was the wrong value, throwing my visual off.
That said, I have looked at use jQuery's find() on JSON object and for some reason can not get what I need from the object I am given by openaq.org.
One version of the object looks like this:
{"meta":{"name":"openaq-api","license":"CC BY 4.0d","website":"https://u50g7n0cbj.execute-api.us-east-1.amazonaws.com/","page":1,"limit":100,"found":1},"results":[{"location":"Metro Lofts","city":null,"country":"US","coordinates":{"latitude":39.731,"longitude":-104.9888},"measurements":[{"parameter":"pm10","value":49.9,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"},{"parameter":"pm1","value":24,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"},{"parameter":"um100","value":0,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"um025","value":0.28,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"um010","value":4.1,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"pm25","value":41.1,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"}]}]}
I am trying to get the "pm25" value.
The code I have tried is this:
function getAirQualityJson(){
$.ajax({
url: 'https://api.openaq.org/v2/latest?coordinates=39.73915,-104.9847',
type: 'GET',
dataType: "json"
// data: data ,
}).done(function(json){
console.log("the json is" + JSON.stringify(json));
console.log("the json internal is" + JSON.stringify(json.results));
var obj = json.results;
var pm25 = "";
//console.log(JSON.stringify(json.results.measurements[0]["parameter"]));
$.each(json.results[0], function(i,items){
//console.log("obj item:" + JSON.stringify(obj[0].measurements));
$.each(obj[0].measurements, function(y,things){
//console.log("each measurement:" + JSON.stringify(obj[0].measurements[0].value));//get each measurement
//pm 2.5
//Can come back in random order, get value from the key "pm25"
// pm25 = JSON.stringify(obj[0].measurements[2].value);
pm25 = JSON.stringify(obj[0].measurements[0].value);
console.log("pm25 is: " + pm25); // not right
});
});
//Trying Grep and map below too. Not working
jQuery.map(obj, function(objThing)
{ console.log("map it 1:" + JSON.stringify(objThing.measurements.parameter));
if(objThing.measurements.parameter === "pm25"){
// return objThing; // or return obj.name, whatever.
console.log("map it:" + objThing);
}else{
console.log("in else for pm25 map");
}
});
jQuery.grep(obj, function(otherObj) {
//return otherObj.parameter === "pm25";
console.log("Grep it" + otherObj.measurements.parameter === "pm25");
});
});
}
getAirQualityJson();
https://jsfiddle.net/7quL0asz/
The loop is running through I as you can see I tried [2] which was the original placement of the 'pm25' value but then it switched up it's spot to the 3rd or 4th spot, so it is unpredictable.
I tried jQuery Grep and Map but it came back undefined or false.
So my question is, how would I parse this to get the 'pm25' key,value. After that, I can get the rest if I need them.
Thank you in advance for all the help.
You can use array#find and optional chaining to do this,
because we are using optional chaining, undefined will be returned if a property is missing.
Demo:
let data = {"meta":{"name":"openaq-api","license":"CC BY 4.0d","website":"https://u50g7n0cbj.execute-api.us-east-1.amazonaws.com/","page":1,"limit":100,"found":1},"results":[{"location":"Metro Lofts","city":null,"country":"US","coordinates":{"latitude":39.731,"longitude":-104.9888},"measurements":[{"parameter":"pm10","value":49.9,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"},{"parameter":"pm1","value":24,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"},{"parameter":"um100","value":0,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"um025","value":0.28,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"um010","value":4.1,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"pm25","value":41.1,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"}]}]}
let found = data?.results?.[0]?.measurements?.find?.(
({ parameter }) => parameter === "pm25"
);
console.log(found);
You can iterate over measurements and find the object you need:
const data = '{"meta":{"name":"openaq-api","license":"CC BY 4.0d","website":"https://u50g7n0cbj.execute-api.us-east-1.amazonaws.com/","page":1,"limit":100,"found":1},"results":[{"location":"Metro Lofts","city":null,"country":"US","coordinates":{"latitude":39.731,"longitude":-104.9888},"measurements":[{"parameter":"pm10","value":49.9,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"},{"parameter":"pm1","value":24,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"},{"parameter":"um100","value":0,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"um025","value":0.28,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"um010","value":4.1,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"pm25","value":41.1,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"}]}]}';
const json = JSON.parse(data);
let value = null;
const measurements = json?.results?.[0]?.measurements ?? null;
if(measurements)
for (const item of measurements)
if (item.parameter === 'pm25') {
value = item.value;
break;
}
if (value) {
// here you can use the value
console.log(value);
}
else {
// here you should handle the case where 'pm25' is not found
}
Trying to pass the list of selected subjects to Controller, but the bean is not receiving the list of subjects.
Here's the code that I'm trying:
$("#submitCreateStudent").click(function() {
var selSubjectIds = new Array();
$('#subjectsTableInCreateStudent').find('.jtable-data-row').each(function() {
if (selSubjectIds.length < 1) {
selSubjectIds.push($(this).attr('data-record-key') + '$');
} else {
selSubjectIds += $(this).attr('data-record-key') + '$';
}
});
if (validateCreateStudentForm()) {
var data = new FormData();
data.append('firstName', $("#firstNameInCreateStudent").val());
data.append('lastName', $("#lastNameInCreateStudent").val());
data.append('address', $("#studentAddressInCreateStudent").val());
data.append('collegeName', $("#studentCollegeNameInCreateStudent").val());
data.append('phoneNumber', $("#phoneNumberInCreateStudent").val());
data.append('email', $("#emailInCreateStudent").val());
data.append('studentDepartment', $("#departmentInCreateStudent").val());
data.append('studentBranch', $("#branchInCreateStudent").val());
data.append('DateOfBirth', $("#dobInCreateStudent").val());
data.append('DateOfReport', $("#dorInCreateStudent").val());
data.append('loginUserName', $("#studentUserNameInCreateStudent").val());
data.append('loginPassword', $("#passwordInCreateStudent").val());
data.append('studentSubjects', selSubjectIds);
// data.append('skipInitialTraining', skipInitialTraining);
$("#maskingId").mask("Saving...");
$.ajax({
url: "AddStudent.do",
data: data,
//
//Remaining code goes here.
});
});
All the details are coming to controller class except for the list of subjects which are selected check boxes.
By default, jQuery supports json format submissions
data :{‘selSubjectIds’:selSubjectIds} or $(this).serialize();
Thanks to Everyone for your efforts.I found my self a way to solve
this as Follows
var arr = "";
$('#subjectsTableInCreateStudent').find('.jtable-data-row').each(function() {
var record = $(this).data('record');
arr += record.subjectId + seperatorForGridCells;
});
Here the arr variable stores every ID as a String by concating with
Some seperator "seperatorForGridCells". Then i used StringTokenizer to
seperate each id and parsed each id from string type to int.
I have a below set of code to get the table data in an array and pass the same to servlet through ajax call. But i am getting null. Please someone help me on what my mistake / how to get the required data since i am new to this servlet and web app. So far i tried with some examples given in SO. but i am clueless to get my expected data.
var myTableArray = [];
$("table#itemtable tr").each(function() {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function() { arrayOfThisRow.push($(this).text()); });
myTableArray.push(arrayOfThisRow);
}
});
alert(myTableArray);
$.ajax({
url:"insertmasteritem",
type:"POST",
dataType:'json',
data: {json:myTableArray},
success:function(data){
// codes....
},
});
Servlet code
String[] myJsonData = request.getParameterValues("json[]");
System.out.println("myJsonData.length"+myJsonData.length);
for (int i = 0; i < myJsonData.length; i++) {
String[] innerArray=myJsonData[i].split(",");
System.out.println(myJsonData[i]);
}
Send your Json data like this
$.ajax({
url:"insertmasteritem",
type:"POST",
dataType:'json',
data:myTableArray,
success:function(data){
// codes....
},
});
and In Servlet Class
JSONObject jsonObj= new JSONObject(request.getParameter("myTableArray"));
Iterator it = jsonObj.keys();
while(it.hasNext())
{
String jsonKey = (String)it.next();
String jsonValue = jsonObj.getString(jsonKey);
System.out.println(jsonKey + " --> " + jsonValue );
}
Well, you need to send a properly formatted JSON object (as a string) to the servlet. Possibly the easiest way to do this is to create some javascript objects and fill an array with these objects. The array data should then be
converted to a JSON string (using JSON.stringify). I'm going to hardcode object values (but you will get them from your table)
Javascript code
function generateJson(){
var myObjArr = [];
//you will typically have just one object (e.g. myObj, which you will fill in your ajax table loop
//myObj.v1 = v1_val;
//myObj.v2 = v2_val;
...
//myObjArr[i] = myObj; //
myObj1 = { "v1": "Orange", "v2": "ABC", "v3":10,"v4":"OK" };
myObj2 = { "v1": "Apple", "v2": "XYZ", "v3":25,"v4":"OK" };
myObjArr[0] = myObj1;
myObjArr[1] = myObj2;
var jsonObjStr = JSON.stringify(myObjArr);
//you can now use jsonObjStr to send your data to the servlet
// document.getElementById("json").innerHTML = jsonObjStr;//this is just added for testing purposes
}
The generated JSON
[{"v1":"Orange","v2":"ABC","v3":10,"v4":"OK"},{"v1":"Apple","v2":"XYZ","v3":25,"v4":"OK"}]
As you can see, the json string starts with a [ (which denotes an array). You may have to change this to start with a { (and with a } ) depending on how your JSON parser works ({} denote an object).
For the servlet part, it depends on the actual JSON parser you're using. Try to use some of the suggestions provided by others. I can provide some code using Jackson though, but you will have to add the Jackson library to your classpath.
why you are getting parameter value as JSON[]
String[] myJsonData = request.getParameterValues("json[]");
I would like to pass a Dictionary> to client using JavaScript.
I did look at this post and I didn't understand exactly how to proceed.
In case I'm doing something wrong I'll explain what I want to do.
The dictionary contains the 'name' key of all worksheets in the Excel file, and the 'value' is the column value of the first row in that worksheet.
The UI of the client should have two "drop list", the first will contain the key which is all the names of the worksheet in the Excel file.
The second contain all the column value of the first row of the worksheets that will choose in the first drop list – which is actually a List as the value in the dictionary.
So all the back end C# code is working fine. Now I need help in the front end JavaScript.
How do I parse the data to a key value so I can do a "search" on the keys as the client chooses some "key" in the first drop list so I can get back the relevant values as a list?
Thanx!
var ajaxRequest = $.ajax({
type: "POST",
url: "http://localhost:1894/api/Values",
contentType: false,
processData: false,
data: data,
success: function(dataTest) {
}
});
This is the JSON that I get back from the server:
{"First":["Name","Link","User","Pass"],"Sec":["test01"]}
How would I perform a search on this like in C#? I want to be able to do something like this: "dict.TryGetValue(key, out value); and the out value would return as an array of string or as a List.
Try this(you don't need var ajaxRequest variable you can directly call like this:
$.ajax({
type: "POST",
url: "http://localhost:1894/api/Values",
dataType: "json",
data: data,
success: function(dataTest) {
//dataTest should contain your data in a javascript object
for(var i = 0; i < dataTest.First.length; i++)
{
window.alert("" + dataTest.First[i]);
}
for(var i = 0; i < dataTest.Sec.length; i++)
{
window.alert("" + dataTest.Sec[i]);
}
//etc...
//this should print the values returned if you showed me exactly how your JSON is...
}
});
The javascript object will contain properties with an array as the value for each property. Think of it like a map of <String, String[]>. So your returned object dataTest will have properties First and Sec and for First the value associated with the key First will be ["Name","Link","User","Pass"] which is just an array. Same for Sec. So `dataTest.First[0] will equal "Name" and dataTest.First[1] will equal "Link" etc...
*****************************************UPDATE**************************************
You can save your dataTest to a global variable in this example (myObject) then you can access like this:
var key = "First";
// Or if you want to get your key from a dropdown (select) element then you could do like this:
var key = document.getElementById("myselect").options[document.getElementById("myselect").selectedIndex].innerHTML;
if(myObject[key] != undefined)
{
//That means there is values for this key.
//Loop through values or do whatever you want with myObject[key].
for(var i = 0; i < myObject[key].length; i++)
{
window.alert("" + myObject[key][i]);
}
}