jQuery How to retrieve and alert JSON data - javascript

JSON:
[
{
"ID":"25",
"Serial":"1",
"Purchase_id":"8",
"Item":"23",
"Unit":"1",
"HSN":"84212120",
"Quantity":"10",
"Purchase_rate":"100",
"Discount":"10",
"Discount_2":"5",
"Net_rate":"85.5",
"CGST_Percentage":"9",
"SGST_Percentage":"9",
"IGST_Percentage":"0",
"Rate_after_tax":"100.89",
"CGST":"76.95",
"SGST":"76.95",
"IGST":"0",
"Net_amount_without_tax":"855",
"Net_amount":"1008.9"
}
]
jQuery:
$.ajax({
method: "POST",
url: formsubmission,
data: data,
success: function(response) {
var data = JSON.parse(response);
alert(data.ID);
}
})
Anyone can please help me why alert is coming with an undefined message. How can I resolve i8t and How can I alert 25 instead of undefined?

The object is at index 0 of the resulting Array of the parsed response. You can use bracket notation to reference element at index 0 of the JavaScript object
let response =`[{"ID":"25","Serial":"1","Purchase_id":"8","Item":"23","Unit":"1","HSN":"84212120","Quantity":"10","Purchase_rate":"100","Discount":"10","Discount_2":"5","Net_rate":"85.5","CGST_Percentage":"9","SGST_Percentage":"9","IGST_Percentage":"0","Rate_after_tax":"100.89","CGST":"76.95","SGST":"76.95","IGST":"0","Net_amount_without_tax":"855","Net_amount":"1008.9"}]`;
let data = JSON.parse(response);
alert(data[0].ID);

var response =`[{"ID":"25","Serial":"1","Purchase_id":"8","Item":"23","Unit":"1","HSN":"84212120","Quantity":"10","Purchase_rate":"100","Discount":"10","Discount_2":"5","Net_rate":"85.5","CGST_Percentage":"9","SGST_Percentage":"9","IGST_Percentage":"0","Rate_after_tax":"100.89","CGST":"76.95","SGST":"76.95","IGST":"0","Net_amount_without_tax":"855","Net_amount":"1008.9"}]`;
var data = JSON.parse(response);
for (var i = 0; i < data.length; i++) {
alert(data[i].ID);
}

Related

AJAX returns Undefined error when displaying an Array of objects using jQuery in PHP on console

I am trying to read a JSON through jQuery and AJAX and some objects like the SUM(amountbet) object in the Array are returning as "undefined"on console.
The above image shows the SUM(amountbet) object as undefined on the console.
But when I am trying to access the "SUM(amountbet)" object it returns me "undefined" on console but when returning the horsename object the value is displayed perfectly. What am i doing wrong here?
Here is my AJAX, jQuery code where i am trying to display each objects in that Array comming from an SQL Query:
$(document).ready(function(){
var racenumberr = $(this).attr("RaceNumber");
var data = new FormData();
data.append("RaceNumber", racenumberr);
$.ajax({
url:"ajax/horses.ajax.php",
method: "POST",
data: data,
cache: false,
contentType: false,
processData: false,
dataType: "json",
success: function(response) {
console.log("Horse Information Displayed In Array",response);
var len = response.length;
for (var i = 0; i < len; i++) {
var horsename = response[i].horsename;
var totalbetting = response[i].totalbetting;
var totalpayout = response[i].payout;
console.log("Horse Names",horsename);
console.log("Horse Payouts",totalbetting); // <-- object is displayed undefined on console
}
}
})
});
object totalbetting is not defined, SUM(amountbet) create json object and convert value to integer

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]])
}

Delete key/value pair from json array obtained from ajax response if key is found

I am fetching data from one list in sharepoint and storing it in json array to pass it onto another function to create a new item in Sharepoint list.The first function is:
$.ajax({
url: someSharepointListUrl,
type: "get",
headers: {"Accept": "application/json;odata=verbose"},
success: function (data) {
var array = new Array();
for (var i=0; i< data.d.results.length; i++) {
var it=data.d.results[i];
array.push({
AllLinks: it.AllLinks,
LinkURL: it.LinkURL.Url
});
}
dataCharts=JSON.stringify(array);
alert(dataCharts);
AddDefaultLinks(dataCharts);
},
error: function (data) {
alert(data.responseJSON.error);
}
});
The item is stored in the list as as:[{"Name":"Name1","URL":"http://www.name1.com"},{"Name":"Name2","URL":"http://www.name2.com"}]
The second function which fetches data from list after item is created is as follows:
$.ajax({
url: url,
type: "get",
headers: {"Accept": "application/json;odata=verbose"},
success: function (data) {
var c = [];
var stringData = JSON.stringify(data.d.results[0].AllLinks);
//alert(stringData);
c.push(JSON.parse(stringData));
alert(c);
var xonly = c.filter(function (entry){
return entry.AllLinks != x;
});
alert(xonly);
},
error: function() {
alert('fail');
}
});
I need to match if a value exists in this newly created list Item.If yes then delete it eg Lin.
value of c(json array) here is:[{"Name":"Name1","URL":"http://www.name1.com"},{"Name":"Name2","URL":"http://www.name2.com"}]
`
entry.AllLinks doesnt filter data here.AllLinks is undefined in entry.AllLinks.Please help
Use Array.findIndex() to find the desired value inside array, and use Array.splice() method to remove that object.

How to build JSON string for JQuery DataTable?

I have created a code which fetches data using the Ajax Call and populate it to the data table UI.
My code is as below:
jQuery.ajax(
{
url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/GetByTitle('Events')/items?$select=Title,Session_x0020_Room,Session_x0020_Date,StartTime,EndTime,Duties,OnsiteContactEmail",
type: "GET",
headers: { "Accept": "application/json;odata=verbose" },
dataType: "json",
success: function (data, textStatus, xhr) {
if (data.d.results.length > 0) {
var resColl = data.d.results;
var strData= new Array();
for(var i=0; i < resColl.length; i++){
var arr = new Array();
arr.push(resColl[i].Title);
arr.push(resColl[i].Session_x0020_Room);
strData[i] = JSON.stringify(arr);
}
$('#example').DataTable({
data:strData,
columns: [
{ title: "Event" },
{ title: "Room" }
]
});
}
},
error: function (data, textStatus, xhr) {
console.error("Error while getting the data from Events list");
}
});
In strData object I am getting this value: "["Asian Women in Computing","Room 1"]"
But in the table of HTML I am not getting proper output.
What am I missing?
I'm assuming that DataTable expects an array of arrays that exists of strings. You have an array of JSON strings because you convert the array arr to a JSON string and push it to strData, which DataTable will later use.
var resColl = data.d.results;
var strData= new Array();
for(var i=0; i < resColl.length; i++){
var arr = new Array();
arr.push(resColl[i].Title);
arr.push(resColl[i].Session_x0020_Room);
strData[i] = arr;
}
Don't convert arr to a JSON string and it should print fine.

Cannot read property of undefined after JSON parse

I have done an ajax request in my code and it works good. After that I want to extract only the necessary info and re-post it to another script. Until now here is my code:
$.ajax({
type: "POST",
url: url,
data: {xhr_id: xhr_id},
success: function (jsondata) {
var product_data = [];
for (var i = 0; i <= 3; i++) {
//alert(jsondata.products[i].product_description.toSource());
product_data[i] = {};
product_data[i]["product" + i] = jsondata.products[i].product_description;
//alert(product_data[i]["product" + i].toSource());
}
},
dataType: "json"
});
The problem is that both the alerts work fine, displaying the information I want. However, I get an error message of "Uncaught TypeError: Cannot read property 'product_description' of undefined" which breaks the script and prevents me from doing anything else. What am I doing wrong, any ideas?
'product_description' of undefined" what it means is that your are trying to access property on undefined variable. That implies "jsondata.products[i]" resulted in undefined value which have occured due to index out of range.How many records are returned in jsondata 3 or 4,check and adjust the condition in for loop
The parameter in the success() function of $.ajax is a string. You have to put it through a parse function to make json. See your code below modified but not tested.
$.ajax({
type: "POST",
url: url,
data: {xhr_id: xhr_id},
success: function (jsondata) {
var oData;
try { oData=jQuery.parseJSON(jsondata) }
catch(err) {
alert("Problem parsing json string : " + jsondata)
return false
}
var product_data = [];
for (var i = 0; i <= 3; i++) {
//alert(oData.products[i].product_description.toSource());
product_data[i] = {};
product_data[i]["product" + i] = oData.products[i].product_description;
//alert(product_data[i]["product" + i].toSource());
}
},
dataType: "json"
});

Categories

Resources