How to parse json value (Javascript Ajax) - javascript

I need to check the status of BranchName every 10 seconds
Need to get "BranchName, status" value,But the result is not smooth.
I'm not familiar with parsing json of javascript.
How can i do?
Thank you!
get "BranchName, status" value, like this:
BranchNameA
1
BranchNameB
1
The get request returns value(json) like this:
[
{
"BranchNameA":{
"branchNumber":"X20001",
"companyId":"64400001",
"shopName":"BOLLYTEST",
"status":"1",
"statusText":"Online",
"statusMessage":"bbbb",
"errorMessage":"",
"connectTime":"xxxxxx",
"disconnectTime":"",
"CheckModel":{
}
}
},
{
"BranchNameB":{
"branchNumber":"X20001",
"companyId":"64400001",
"shopName":"BOLLYTEST",
"status":"1",
"statusText":"Online",
"statusMessage":"bbb",
"errorMessage":"",
"connectTime":"xxxxxx",
"disconnectTime":"",
"CheckModel":{
}
}
}
]
code:
<script>
getApi()
function getApi() {
setTimeout(getApi, 10 * 1000);
$.ajax({
url: "(api)",
type: "Get",
dataType: "json",
success: function (data) {
console.log(JSON.stringify(data));
let user = JSON.parse(data);
var jsonData = JSON.parse(data);
for (var i = 0; i < jsonData.fields.length; i++) {
var Status= jsonData.fields[i];
console.log(counter.status);
}
}
})
}
</script>

This will solve:
success: function (data) {
var jsonData = apiData;
console.log(jsonData);
for (i in jsonData)
{
data = jsonData[i];
keys = Object.keys(data);
console.log(keys[0]);
console.log(data[keys[0]].status);
}
}

Related

Infinite loop to output all values from an array

From the function django I return JSON to JS
paymentparking = paidparking.objects.filter(expirationdate__range=(startdate, enddate)).values('expirationdate','price')
return JsonResponse({'result': list(paymentparking)})
Here I need to get all the expirationdate values. How can this be done and how can the cycle be organized?
$.ajax({
type: "POST",
url: "statistics",
data: {
'startdate': finalDateStrStart,'enddate': finalDateStrEnd,
},
dataType: "json",
cache: false,
success:function (data) {
for (let i = 0; i < 100; i++)
{
console.log(data.result[i].expirationdate)
}
}
});
You could maybe do something like this:
success: function (data) {
if(data.result) {
for (let i = 0; i < data.result.length; i++) {
console.log(data.result[i].expirationdate)
}
}
}
Use Array.map() to iterate over elements and return an array of expirationdate.
success: function (data) {
data?.result && data.result.map(obj => console.log(obj.expirationdate));
}

Split html table values using java script

I am working in rails application and From UI I need to select around 500 parameters(comma separated) in a table for execution. I am sending those selected data in AJAX call. I am unable to post huge string values hence I am planning to get the length of selected parameters if selected parameters count exceeds length 200. I need to split two or three batches and send for execution. How to implement this?
if (Device1) {
parameter_name = $('#parameters_object').val();
var getParams=parameter_name.split(',');
paramLen=getParams.length;
alert(paramLen);
if (paramLen > 200){
}
//m is a selected mac address length count
for (var i = 0; i < m; i++) {
(function () {
var macAdd = values[i];
$.ajax({
method: "POST",
url: "get_object",
dataType: "json",
data: {
parameter: getParams,
mac: macAdd,
protocol: protocol,
serialnumber: serialnumber,
},
success: function (result) {
console.log(result);
}
},
statusCode: {
404: function () {
console.log("Call failed");
}
}
});
})();
}
You can split your array into chunks of 200 items, and then loop over the chunk array and do your AJAX call.
const chunkSize = 200
const chunkParams = getParams.reduce((resultArray, item, index) => {
const chunkIndex = Math.floor(index/chunkSize)
if(!resultArray[chunkIndex]) {
resultArray[chunkIndex] = [] // start a new chunk
}
resultArray[chunkIndex].push(item)
return resultArray
}, [])
values.forEach(macAddress =>
chunkParams.forEach(chunkParam =>
$.ajax({
method: "POST",
url: "get_object",
dataType: "json",
data: {
parameter: chunkParam,
mac: macAddress,
....
},
...
});
)
)
You can directly do your AJAX call in the reduce loop, more performant but less readable.
You need to split params to batches and make ajax call for each batch. Try following:
if (Device1) {
parameter_name = $('#parameters_object').val();
var getParams=parameter_name.split(',');
paramLen=getParams.length;
alert(paramLen)
var paramsBatches = [];
var batchSize = 200;
for (i = 0, j = getParams.length; i < j; i += batchSize) {
paramsBatches.push(getParams.slice(i, i + batchSize));
}
//m is a selected mac address length count
for (var i = 0; i < m; i++) {
paramsBatches.forEach((batch, index) => {
var macAdd = values[i];
$.ajax({
method: "POST",
url: "get_object",
dataType: "json",
data: {
parameter: batch,
mac: macAdd,
protocol: protocol,
serialnumber: serialnumber,
},
success: function (result) {
console.log(result);
}
},
statusCode: {
404: function () {
console.log("Call failed");
}
}
});
}
}
}

How to get data from ajax GET query

I'm doing a GET request using $.ajax():
jQuery(function ($) {
$('#acsess').on('click', function () {
$.ajax({
url: 'http://f4c0c1f3aa9a506c69b3b6642864b3590fb8f76f#504080.com/api/v1/services/categories',
method: 'GET',
beforeSend: function(req) {
req.setRequestHeader('Authorization', "f4c0c1f3aa9a506c69b3b6642864b3590fb8f76f");
},
success: function(data) {
console.log(data);
jQuery.each(data, function (index, value) {
// need to create divs with *icon and *title from data
})
},
error: function(error) {
alert("error");
}
})
});
});
I got this in my console:
And I can't retrieve icon link and title text. Please help.
You can access the data (which seems to be an array) by data[index].icon and data[index].title.
If you need to access all the items, I recommend a simple loop:
success: function(data) {
for (var i = 0; i++; i < data.length) {
data[i].icon // it's here, what to do is up to you
}
}
it helps me to resolve problem
success: function(data) {
var ololo = data.data;
for (let i = 0; i < ololo.length; i++) {console.log(ololo[i].title);}
}

function call another without waiting to finish

In my method feedContactCategorySelection, i would like to wait the assignContactCategoryToLocal call to be finished before continuing to run the rest of the code
feedContactCategorySelection();
function feedContactCategorySelection(){
assignContactCategoryToLocal();
var category = sessionStorage.getItem("category");
category = JSON.parse(category);
for (var i = 0; category["data"].length; i++) {
//....
}
}
function assignContactCategoryToLocal() {
var category = sessionStorage.getItem("category");
if (category == null) {
$.ajax({
url: 'http://localhost:8080/rest/contact/category',
type: 'GET',
success: function (json) {
sessionStorage.setItem("category", JSON.stringify(json));
}
});
}
You can pass a callback function to the assignContactCategoryToLocal() that way you can continue running the code only when the ajax is done. Something like this:
feedContactCategorySelection();
function feedContactCategorySelection() {
// Do anything here before running the ajax
// For instance, get category and pass it to the assignContact...
var category = sessionStorage.getItem("category");
...
assignContactCategoryToLocal(category, myCallbackFunction);
}
function myCallbackFunction(category) {
category = JSON.parse(category);
for (var i = 0; category["data"].length; i++) {
....
}
}
function assignContactCategoryToLocal(category, callback) {
if (category == null) {
$.ajax({
url: 'http://localhost:8080/rest/contact/category',
type: 'GET',
success: function (json) {
sessionStorage.setItem("category", JSON.stringify(json));
// Now that it is done and successful, run the rest...
callback(category);
}
});
}
}
For sake of example, you can get the category once and then pass it along the functions, maybe that helps understand how they are connected.
EDIT:
To address the issue with the category being null, here is a revised version.
feedContactCategorySelection();
function feedContactCategorySelection() {
// Do anything here before running the ajax
// For instance, get category and pass it to the assignContact...
var category = sessionStorage.getItem("category");
...
// Move the if statement here so it checks the condition earlier.
if (category === null) {
assignContactCategoryToLocal(category, myCallbackFunction);
} else {
myCallbackFunction(category);
}
}
function myCallbackFunction(category) {
category = JSON.parse(category);
for (var i = 0; category["data"].length; i++) {
....
}
}
function assignContactCategoryToLocal(category, callback) {
$.ajax({
url: 'http://localhost:8080/rest/contact/category',
type: 'GET',
success: function (json) {
sessionStorage.setItem("category", JSON.stringify(json));
// Now that it is done and successful, run the rest...
callback(category);
}
});
}
Consider using Promise in this case.
Pseudocode as below:
feedContactCategorySelection();
function feedContactCategorySelection(){
assignContactCategoryToLocal().then(function(){
var category = sessionStorage.getItem("category");
category = JSON.parse(category);
for (var i = 0; category["data"].length; i++) {
....
}
})
}
function assignContactCategoryToLocal() {
return new Promise(function(resolve, reject){
var category = sessionStorage.getItem("category");
if (category == null) {
$.ajax({
url: 'http://localhost:8080/rest/contact/category',
type: 'GET',
success: function (json) {
sessionStorage.setItem("category", JSON.stringify(json));
resolve()
}
failed:{reject(reason)}
});
})
}
Please check i have added async: false, to wait until get the ajax response.
feedContactCategorySelection();
function feedContactCategorySelection(){
assignContactCategoryToLocal();
var category = sessionStorage.getItem("category");
category = JSON.parse(category);
for (var i = 0; category["data"].length; i++) {
//....
}
}
function assignContactCategoryToLocal() {
var category = sessionStorage.getItem("category");
if (category == null) {
$.ajax({
url: 'http://localhost:8080/rest/contact/category',
type: 'GET',
async: false,
success: function (json) {
sessionStorage.setItem("category", JSON.stringify(json));
}
});
}
function feedContactCategorySelection() {
// `data` : `sessionStorage.getItem("category")` or response from `$.ajax()`
assignContactCategoryToLocal().then(function(data) {
// if `category` set , return `category` , else set `category`
var category = sessionStorage.getItem("category") != null
? sessionStorage.getItem("category")
: sessionStorage.setItem("category", JSON.stringify(data));
category = JSON.parse(category);
for (var i = 0; category["data"].length; i++) {
//....
}
// handle errors, if any, from `$.ajax()` call
}, function err(jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown)
})
}
function assignContactCategoryToLocal() {
var category = sessionStorage.getItem("category");
// if `category` is `null` , return `$.ajax()` response
return category == null
? $.ajax({
url: 'http://localhost:8080/rest/contact/category',
type: 'GET'
})
: $.when(category)
}

JQPlot, JSON and 'No data specified' Error

I am trying to use JQPlot within a VB.NET application under .NET 3.5. On a button click, using jquery, I am trying to populate the JQPlot Chart with JSON derived data using a ASP.NET Webservices Source file (which is part of the solution).
The JSON data is sent by the web service but when it is presented to JQPlot I get the javascript error 'No Data Specified' which is generated by JQPlot code.
My code listing is as follows:
Code to listen for the button to be clicked:
$(document).ready(function () {
$('#<%=btnASMX1.ClientID%>').click(function () {
getElectricDataJSON();
return false;
});
});
Javascript code outside the 'document.ready' function:
function ajaxDataRenderer() {
var ret = null;
$.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
async: false,
//url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: "AccountsService.asmx/GetJSONData",
data: "{AccountID: " + $('#<%= hiddenAccountID.ClientID%>').val() + " }",
dataType: "json",
success: function (response) {
var ret = response.d;
// The following two lines just display the JSON data for testing purposes
$('#<%=outputASMX.ClientID%>').empty();
$('#<%=outputASMX.ClientID%>').html("<div>" + ret + "</div>");
return ret;
},
error: function (request) {
$('#<%=outputASMX.ClientID%>').html("<div style='color:red;'>WEBSERVICE UNREACHABLE</div>");
}
});
return ret;
};
var jsonurl = "./jsondata.txt";
function getElectricDataJSON() {
var ret = ajaxDataRenderer();
var plot1 = $.jqplot('chart2', jsonurl, {
title: "AJAX JSON Data Renderer",
dataRenderer: ret, //$.jqplot.ciParser
dataRendererOptions: {
unusedOptionalUrl: jsonurl
}
});
}
The JSON data format is as follows:
[ { "todate": "2013-09-23T00:00:00", "Bill": 7095.65 }, { "todate": "2013-08-22T00:00:00", "Bill": 1137.96 }, { "todate": "2013-07-24T00:00:00", "Bill": 220429.41 }, ... ]
Any help or advice will be appreciated.
Thanks to #Fresh for their quick response. Here is the complete solution to my problem:
Code to listen for the button to be clicked:
$(document).ready(function () {
$('#<%=btnASMX1.ClientID%>').click(function () {
getElectricDataJSON();
return false;
});
});
JS function to get the data from a web service:
function ajaxDataRenderer() {
var ret = null;
$.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
async: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: "AccountsService.asmx/GetJSONData",
data: "{AccountID: " + $('#<%= hiddenAccountID.ClientID%>').val() + " }",
dataType: "json",
success: function (response) {
ret = response.d; // return response string object
},
error: function (request) {
$('#<%=outputASMX.ClientID%>').html("<div style='color:red;'>WEBSERVICE UNREACHABLE</div>");
}
});
return ret;
};
Data structure outputted by the web service is:
[ { "todate": "2013-09-23T00:00:00", "Bill": 7,095.65 }, { "todate": "2013-08-22T00:00:00", "Bill": 1,137.96 }, { "todate": "2013-07-24T00:00:00", "Bill": 220,429.41 }, ... ]
Data structure that is expected by JQPlot:
[ [ "2013-09-23T00:00:00", 7095.65 ] , [ "2013-08-22T00:00:00", 1137.96 ], [ "2013-07-24T00:00:00", 220429.41 ], ... ]
Note the removal of the comma's in the 'expected data' Bill field.
And finally, the function getElectricDataJSON() that is being called by btnASMX1 where 'chart2' is the ID of the div tags where the chart will be drawn.
function getElectricDataJSON() {
// Get JSON 'string' object
var ret = ajaxDataRenderer();
// If JSON string object is null, stop processing with friendly message
if (ret == null) {
$('#<%=outputASMX.ClientID%>').html("<div style='color:red;'>CHARTS ARE NOT AVAILABLE AT THIS TIME</div>");
return false;
}
// Now push required data into a JSON array object
var sampleData = [], item;
$.each(ret, function (key, value) {
sampleData.push([value.todate, parseFloat(value.Bill.replace(/,/g, ""))]);
});
var plot = $.jqplot('chart2', [sampleData], {
title: 'AJAX JSON Data Renderer',
dataRenderer: sampleData,
...
});
}
The method signature for your datarender (i.e. ajaxDataRender) is wrong. The signature should look like this:
function(userData, plotObject, options) { ... return data; }
(See the documentation here)
In your example you are passing the datarenderer "ret" which is not a function with the correct datarender signature. Also the jsonurl you are passing to getElectricDataJSON() is redundant as at no point in your code is the data from "AccountsService.asmx/GetJSONData" persisted to "./jsondata.txt".
Hence you should change your code to this:
$(document).ready(function(){
function ajaxDataRenderer(url, plot, options) {
var ret = null;
$.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
async: false,
url: url,
dataType: "json",
success: function (response) {
var ret = response;
// The following two lines just display the JSON data for testing purposes
$('#<%=outputASMX.ClientID%>').empty();
$('#<%=outputASMX.ClientID%>').html("<div>" + ret + "</div>");
},
error: function (request) {
$('#<%=outputASMX.ClientID%>').html("<div style='color:red;'>WEBSERVICE UNREACHABLE</div>");
}
});
return ret;
};
var url = "AccountsService.asmx/GetJSONData";
function getElectricDataJSON() {
var plot1 = $.jqplot('chart2', url, {
title: "AJAX JSON Data Renderer",
dataRenderer: ajaxDataRenderer,
});
}

Categories