Getting data from JSON Structure - javascript

My coldfusion component is returning a JSON format data. I am trying to access the values of that data in my front-end using Javascript. Can someone help me understand how to access the data values such as the "id", "firs_name" and "last_name"?
I am storing the the follow data in the variable called tempData. Below is the JSON structure I am getting:
{ "COLUMNS" : [ "id",
"FIRST_NAME",
"LAST_NAME"
],
"DATA" : [ [ "xxxx",
"Jes",
"Abr"
],
[ "xxx2",
"JESSIE",
"YU"
]
]
}
Below is my ajax call:
$.ajax({
type: "get",
url: "GROUPSLIST.cfc",
data: {
method: "getNames",
queryString: selectQuery
},
success: function(a) {
alert(a);
},
error: function(a) {
alert(a.responseText);
}
});

I am assuming your response is not parsed already. You can use something like following.
var tempData = '{"COLUMNS":["id","FIRST_NAME","LAST_NAME"],"DATA":[["xxxx","Jes","Abr"],["xxx2","JESSIE","YU"]]}';
//parse response if not already parsed
var respObj = JSON.parse(tempData);
var columns = respObj['COLUMNS'];
//create a column map to index like following
var colMap = {};
for(i = 0; i < columns.length; i++){
colMap[columns[i]] = i;
}
console.log(colMap)
var data = respObj['DATA'];
var text = ''
//use data[i][colMap['id']] to access data inside loop.
for(i = 0; i < data.length; i++){
text += data[i][colMap['id']] + ':' +data[i][colMap['FIRST_NAME']] + ' ' + data[i][colMap['LAST_NAME']] + '<br>';
}
document.getElementById('text').innerHTML = text;
<div id="text"></div>

This might be also help full while using DB query and access by column(ex:employee_id,employee_name)
Step-1
// return in serializeJSON format with true
<cffunction name="employeelistJson" returntype="any" returnformat="JSON">
<cfquery name="employeelist" datasource="yourdatasource">
select * from employee
</cfquery>
<cfset setJson = #serializeJSON(employeelist,true)#>
<cfreturn setJson />
</cffunction>
Step-2 access json data by name
success: function(response) {
//must be in caps
alert(response.DATA['EMPLOYEEID']);
alert(response.DATA['EMPLOYEENAME']);
},

Related

DataSet Value in Jquery C#

I have one page in which, URL contains Querystring Value.
QSecID=164&QTempId=55&QSecName=New%20Temp%20Bt
When the page loads them and tries to get the value it works fine.
$(document).ready(function() {
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
var urlName = getUrlParameter('QSecName');
alert(urlName);
getImageData(urlName); //Pass Query String Value to Function
});
Now I am passing this value to C#, ASPX.CS page and try to fetch the data based on QSecName.
But i got error. Here is my Jquery function.
function getImageData(name) {
// alert(nextDay);
$.ajax({
type: "POST",
url: "Section.aspx/GetImageData",
//data: '',
data: JSON.stringify({
"dataSecName": name
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert("Success");
alert(JSON.parse(data.d));
}
});
}
My C# Page returns the DataSet in Jquery.
[WebMethod()]
public static string GetImageData(string dataSecName)
//public static string GetRole()
{
clsSection objSectNew = new clsSection();
DataSet DS = new DataSet();
DS = objSectNew.GetImageDataByJQ(dataSecName);
return JsonConvert.SerializeObject(DS);
}
Edit Code 1
Here is my SQL Statement Which is get executed when i run the page and
DS = objSectNew.GetImageDataByJQ(dataSecName);
this method pass the query string value in to execute the Stored Procedure.
select mhp.ImageName,mhp.HotSpotID,imgdetail.XCordinate,imgdetail.YCordinate
from tbl_SOAPDetailsInfo e inner join M_ImageHotSpot mhp on e.ImgHotSpotName=mhp.ImgHotSpotNameByUser
inner join M_ImageHotSpotDetail imgdetail on mhp.HotSpotID=imgdetail.HotspotIDFK where e.SOAP_D_Name='New Temp Bt'
I want to use my XCordinate, YCordinate and ImageName to display image using jquery. but Inside the alert BOX
**[object] [object]**
error display. How can i get and assign this value X AND Y value and display in DIV.
Edit Code 2
ImageName XCordinate YCordinate
$parent in angularjs.png 1146 590
$parent in angularjs.png 1216 588
$parent in angularjs.png 1188 626
$parent in angularjs.png 1162 582
$parent in angularjs.png 1193 586
The Database Value. JSON FORMAT DATA
{"d":"{\"Table\":[{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1146\",\"YCordinate\":\"590\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1216\",\"YCordinate\":\"588\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1188\",\"YCordinate\":\"626\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1162\",\"YCordinate\":\"582\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1193\",\"YCordinate\":\"586\"}]}"}
So as per your question [object] [object] is not an error. It means you cannot fetch it in a correct manner.
Though I am not sure what kind of data you are sending from your back-end code in data But you could try following way,
var data = "{\"Table\":[{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1146\",\"YCordinate\":\"590\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1216\",\"YCordinate\":\"588\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1188\",\"YCordinate\":\"626\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1162\",\"YCordinate\":\"582\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1193\",\"YCordinate\":\"586\"}]}"
var obj = JSON.parse(data);
console.log(obj.Table);
var tableObj = obj.Table
console.log(obj.Table);
var arrayLength = tableObj.length;
for (var i = 0; i < arrayLength; i++) {
console.log(tableObj[i].ImageName);
console.log(tableObj[i].XCordinate);
console.log(tableObj[i].YCordinate);
alert(tableObj[i].YCordinate);
}
So now if you replace your code with above sample your code should look like below:
function getImageData(name) {
// alert(nextDay);
$.ajax({
type: "POST",
url: "Section.aspx/GetImageData",
data: JSON.stringify({
"dataSecName": name
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var obj = JSON.parse(data);
console.log(obj.Table);
var tableObj = obj.Table
console.log(obj.Table);
var arrayLength = tableObj.length;
for (var i = 0; i < arrayLength; i++) {
console.log(tableObj[i].ImageName);
console.log(tableObj[i].XCordinate);
console.log(tableObj[i].YCordinate);
alert(tableObj[i].YCordinate);
}
});
}
Note : Try to debug in browser console you would understand object notation more details.
See the screen shot how would you do that
Hope this would help

Get JSON array data by field name

I'm trying to get JSON data by field name like this data.name and it return the desired data, but I have 25 fields in the array and I want to make this dynamically, using data + "." + variable, when I alert it returns [Object object].name, so how I can make it executable?
I tried many ways but all failed, please help me doing this.
$.ajax({
type: "Get",
url: "/Home/Report_Data",
datatype: "json",
dataSrc: "",
contentType: 'application/json; charset=utf-8',
data: {
'Arrnagement': Arrnagement
},
success: function(data) {
var result = getElementsById("LD_name LD_Loan_Type LD_id LD_Full_Name_AR LD_GENDER LD_BIRTH_INCORP_DATE LD_PS_MOTHER_NAME LD_Street_AR LD_TEL_MOBILE LD_EMPLOY_STATUS_D LD_EMPLYRS_Name LD_MARITAL_STATUS LD_PS_PL_OF_BIR_AR LD_wifeName LD_Effective_Interest_Rate LD_Contract_amount LD_Repayment_Amount LD_Sector_name LD_NUM_REPAYMENTS LD_Loan_Maturity LD_Orig_Contract_Date LD_Loan_CCY LD_Arrangement LD_COLLATERAL_TYPE LD_Description LD_COLLATERAL_VALUE LD_COLLATERAL_Currency LD_GUARANTOR_ID LD_NATIONALITY LD_G_Full_Name_En LD_G_DATE_OF_BIRTH LD_G_PLACE_OF_BIRTH LD_G_MOTHER_NAME_EN LD_HOUSING_LOAN_AREA_CLASS LD_HOUSING_PROPERTY_NATURE LD_HOUSING_LOAN_PURPOSE LD_HOUSING_PROPERTY_AREA");
var jid;
for (var i = 0; i < result.length; i++) {
jid = (result[i].id.substring(3));
var resulting = data[0].jid;
alert(resulting);
if (result[i].innerHTML = data[0].jid != "undefined") {
result[i].innerHTML = data[0].jid;
} else {
result[i].innerHTML = "";
}
}
//jid = name;
//data[0].name returns "Joun"
//data[0]+"."+jid returns [object object].name but i need it to return "Joun"
This should work. I changed the dot notation while accessing the object property.
$.ajax({
type: "Get",
url: "/Home/Report_Data",
datatype: "json",
dataSrc: "",
contentType: 'application/json; charset=utf-8',
data: { 'Arrnagement': Arrnagement },
success: function (data) {
var result = getElementsById("LD_name LD_Loan_Type LD_id LD_Full_Name_AR LD_GENDER LD_BIRTH_INCORP_DATE LD_PS_MOTHER_NAME LD_Street_AR LD_TEL_MOBILE LD_EMPLOY_STATUS_D LD_EMPLYRS_Name LD_MARITAL_STATUS LD_PS_PL_OF_BIR_AR LD_wifeName LD_Effective_Interest_Rate LD_Contract_amount LD_Repayment_Amount LD_Sector_name LD_NUM_REPAYMENTS LD_Loan_Maturity LD_Orig_Contract_Date LD_Loan_CCY LD_Arrangement LD_COLLATERAL_TYPE LD_Description LD_COLLATERAL_VALUE LD_COLLATERAL_Currency LD_GUARANTOR_ID LD_NATIONALITY LD_G_Full_Name_En LD_G_DATE_OF_BIRTH LD_G_PLACE_OF_BIRTH LD_G_MOTHER_NAME_EN LD_HOUSING_LOAN_AREA_CLASS LD_HOUSING_PROPERTY_NATURE LD_HOUSING_LOAN_PURPOSE LD_HOUSING_PROPERTY_AREA");
var responseData = data[0];
var jid;
for (var i = 0; i < result.length; i++) {
jid = (result[i].id.substring(3));
var resulting = responseData[jid];
alert(resulting);
if (responseData[jid]) {
result[i].innerHTML = responseData[jid];
}
else {
result[i].innerHTML = "";
}
}
Try giving data[0][jid], we can give a variable in brackets also inorder to get the data
Hope it works
If do foo.bar you are getting a property with the name 'bar' on object foo. If you have some variable const bar = "qux" and you want to access property on some object with the same name as bar value /"qux"/ you just need to use square brackets - foo [bar], which will be the same as calling foo.qux; So, in your case you just need to use data[0][jid] instead of data [0].jid, supposing jid contains a string that is also a key in data[0].
You can just do data[0][variableName] and this will return the data you want. for example. If data had a json string [{ "Name" : "Jane Doe"}] You could execute it like this.
var variableName = "Name";
console.log(data[0][variableName])
This would return "Jane Doe".
if you have your field names in an array you can loop through them using $.each or a for loop.
For example say your json string is [{"First_Name" : "Jane", "Last_Name" : "Doe", "Age" : 32}] you could get all the values from the json string doing this.
var FieldNames = ["First_Name" , "Last_Name", "Age"]
$.each(FieldNames, function(i,item) {
console.log(data[0][item])
}
OR
var FieldNames = ["First_Name" , "Last_Name", "Age"]
for(var i = 0; i < FieldNames.length; i++) {
console.log(data[0][FieldNames[i]])
}

JSON.stringify and $http request

I have a JS String, like so:
user_fav = "21,16";
This has to go thru a function where it becomes a JSON array with an id key, like so:
{"id":21},{"id":16}
And this goes into an $http request:
return $http({
method: 'GET',
url: getUrl('products'),
params: {
pageSize: 2000,
pageNumber: 1,
"filter": { "q": { "$or": [{"id":21},{"id":16}] } }, // <-- HERE
sort: []
}
});
Now if I run the above $http request everything works fine, but if I convert the String (user_fav) into that JSON and send this to the $http request it fires an error. This is my converter:
user_fav = "21,16";
var user_fav_to_array = "";
var splitFav = user_fav.split(",");
for (var i = 0; i < splitFav.length; i++) {
user_fav_to_array += JSON.stringify({ id: parseInt(splitFav[i]) }) + ',';
}
var JSONFavs = user_fav_to_array.substring(0, user_fav_to_array.length - 1);
//Result: JSONFavs => {"id":21},{"id":16}
So this gives an error:
return $http({
method: 'GET',
url: getUrl('products'),
params: {
pageSize: 2000,
pageNumber: 1,
"filter": { "q": { "$or": [JSONFavs] } }, // <-- HERE
sort: []
}
});
Madame and messier the error is 417 (Critical Exception), this is coming from the Backand.com syste
Have a look at the code below. What your code actually doing is assigning a Json STRING to $or property. But really needed is to assign array of items (as expected). Let me know if you have any questions
user_fav = "21,16";
//Dont need this
//var user_fav_to_array = "";
// New Variable to save array items
var arrayData =[];
var splitFav = user_fav.split(",");
for (var i = 0; i < splitFav.length; i++) {
// don't need this
//user_fav_to_array += JSON.stringify({ id: parseInt(splitFav[i]) }) + ',';
// Just create a simple javascript object with id and put it into array at i index
arrayData[i]={ id: parseInt(splitFav[i]) };
}
//var JSONFavs = user_fav_to_array.substring(0, user_fav_to_array.length - 1);
// Then in Http Request filter, it should be just like this "$or": arrayData
"filter": { "q": { "$or": arrayData } }
This might have to deal with your variable - var user_fav_to_array = "";
You may want to change it to the following var user_fav_to_array = [];
Since it has the quotations it may be causing your variable to behave in a way that you don't want it to. Unless strings are treated as arrays in javascript.

How get parametrs from json?

Full code:
$.post('test.php', {
id: id
},function (data) {
console.log(data);
var Server = data.response.server;
var Photo = data.response.photo;
console.log(Server);
console.log(Photo);
});
in data i get json:
{
"server":9458,
"photo":
"[{\"photo\":\"0d6a293fad:x\",\"sizes\":
[[\"s\",\"9458927\",\"1cb7\",\"PX_xDNKIyYY\",75,64],
[\"m\",\"9458927\",\"1cb8\",\"GvDZr0Mg5zs\",130,111],
[\"x\",\"9458927\",\"1cb9\",\"sRb1abTcecY\",420,360],
[\"o\",\"9458927\",\"1cba\",\"J0WLr9heJ64\",130,111],
[\"p\",\"9458927\",\"1cbb\",\"yb3kCdI-Mlw\",200,171],
[\"q\",\"9458927\",\"1cbc\",\"XiS0fMy-QqI\",320,274],
[\"r\",\"9458927\",\"1cbd\",\"pU4VFIPRU0k\",420,360]],
\"kid\":\"7bf1820e725a4a9baea4db56472d76b4\"}]",
"hash":"f030356e0d096078dfe11b706289b80a"
}
I would like get parametrs server and photo[photo]
for this i use:
var Server = data.server;
var Photo = data.photo;
console.log(Server);
console.log(Photo);
but in concole i get undefined
Than i use code:
var Server = data.response.server;
var Photo = data.response.photo;
console.log(Server);
console.log(Photo);
But now in console i see:
Uncaught TypeError: Cannot read property 'server' of undefined
Why i get errors and how get parametrs?
P.S.: All code php and jquery find here
Just set proper data type json, the default one is string.
And your data is directly under data variable!
$.post('test.php', {
id: id
},function (data) {
console.log(data);
var Server = data.server;
var Photo = data.photo;
console.log(Server);
console.log(Photo);
}, 'json');
Another solution is setting proper header in you PHP response:
Content-Type text/javascript; charset=UTF-8
then jQuery Intelligent Guess, will set proper data type itself.
You can use parseJSON method, exposed by jQuery. This enables you to map the properties to a type, of sorts, such as:
var results = jQuery.parseJSON(jsonData);
for (int i = 0; i < results.length; i++) {
alert(results[i].name + ":" + results[i].date);
}
You may need to tweak the inputs and exact use of the outputs in accordance with your data and requirements.
getJSON() will parse the JSON for you after fetching, so from then on, you are working with a simple Javascript array ([] marks an array in JSON).
You can get all the values in an array using a for loop:
$.getJSON("url_with_json_here", function(data){
for (var i=0, len=data.length; i < len; i++) {
console.log(data[i]);
}
});
Another example:
Parse a JSON string.
var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" )
;

jQuery : update the database with all of the data from the ajax-request

am trying to update database.
For that iam doing like this
From js code
var data = {
"jobid": $('#jobid').val(),
"names": $('#names').val(),
"scripttype": $('#testscripts').val()
};
var msg="";
for(i = 1; i <=4; i++) {
data["Param" + i + "Key"] = $('#key' + i).val();
data["Param" + i + "Value"] = $('#value' + i).val();
}
$.ajax({
type: 'post',
url: "/save",
dataType: "json",
data: data
});
in node.js side
jobsCollection.update({
_id: id
}, {
$set: {
names: record.names,
script: record.scripttype,
// i dont know what should i place in this part???
// i have to set paramkey and paramValues
}
},
{
upsert: true
},
function (err, result) {
if (!err) return context.sendJson([], 404);
});
in record.names and record.scripttype getting proper values.
I don't know how to set values got from the for loop for updating
request going
Request: /save
{ jobid: '',
names: 'first',
scripttype: 'fow',
Param1Key: '1',
Param1Value: 'oneeeeee',
Param2Key: '2',
Param2Value: 'twoooooooo'
etc........
............
}
Since the property names are dynamic, you'll need to use the indexer-style property accessor of JavaScript as shown below.
Just reverse the process basically. I'm not sure where the data is located at the point you're calling update, so I called it sourceData in the example below;
// create an object with the well known-property names
var set = {
names : record.names,
script : record.scripttype
};
// now loop through the params and set each one individually
for(i = 1; i <=4; i++) {
var key = "Param" + i + "Key"; // build a key string
set[key] = sourceData[key]; // grab the data and set it
key = "Param" + i + "Value"; // and repeat
set[key] = sourceData[key];
}
then, pass it to your update:
jobsCollection.update({
_id: id
}, {
$set: set // pass the object created above
}, /* etc. */
If you don't know the count of Params, you could:
send it
use instead for .. in to loop through all the properties
For #2:
for(var key in sourceData) {
// you could filter the property names here if you'd like
// (like if only Params# were important)
set[key] = sourceData[key];
}

Categories

Resources