Infinite loop to output all values from an array - javascript

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

Related

Add array elements to list

I am trying to append array elements to the list using below code:
function GetList() {
let list = [];
$.ajax({
url: '../Lookup/GetList',
type: 'GET',
cache: true,
dataType: "json",
success: function (response) {
debugger;
list = response;
//for (var data in response) {
// list = { value: data, rest: list };
//}
//for (let i = response.length - 1; i >= 0; i--) {
// list = { value: array[i], rest: list };
//}
//for (let i = response.length - 1; i >= 0; i--) {
// list.push(response[i]);
//}
}
});
return list;
}
I have attached the screenshot of array data format.
I need in the below list format:
var list= [
{
"id": "1",
"LookupMasterName": " Source1",
"Description": "xxx",
"Enabled Flag":"Y"
},
{
"id": "2",
"LookupMasterName": " Source2",
"Description": "yyy",
"Enabled Flag": "Y"
}
];
Above code doesn't work. It returns empty list. Can you help?
It's returning an empty list because this line return list; is executed before Ajax is completed. A solution to fix it is wrapping your Ajax request into a Promise:
Example:
function GetList() {
let list = [];
return new Promise((resolve) => {
$.ajax({
url: "../Lookup/GetList",
type: "GET",
cache: true,
dataType: "json",
success: function (response) {
list = response;
resolve(list);
},
});
});
}
Then calling GetList:
GetList().then(list => /* do whatever you need */)

How to parse json value (Javascript Ajax)

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

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 speed up ajax calls to fetch record from php file

i'm trying to send ajax call to php file which return 1000 record at a time in json encoded format which i am appending in table. everything working fine but it takes alot for time which result in hanging of page. below is my js code.
$(window).load(function() {
for (i = 0; i < 31; i++)
{
$.ajax({
type: "GET",
url: "filters.php",
data: {limit: 1000, start_from: (i * 1000)},
success: function(response) {
var array = JSON.parse(response);
Object.keys(array).forEach(function(key) {
oTable.fnAddData([
array[key][1],
array[key][2],
array[key][3],
array[key][4],
array[key][5],
array[key][6],
array[key][7],
array[key][8],
array[key][9],
array[key][10],
array[key][11],
array[key][12],
array[key][13],
array[key][14],
array[key]['link']
]);
});
},
datatype: 'json'
});
}
});
Try this:
$(window).load(function() {
for (i = 0; i < 31; i++)
{
setTimeout(500,function(){
$.ajax({
type: "GET",
url: "filters.php",
data: {limit: 1000, start_from: (i * 1000)},
success: function(response) {
var array = JSON.parse(response);
Object.keys(array).forEach(function(key) {
oTable.fnAddData([
array[key][1],
array[key][2],
array[key][3],
array[key][4],
array[key][5],
array[key][6],
array[key][7],
array[key][8],
array[key][9],
array[key][10],
array[key][11],
array[key][12],
array[key][13],
array[key][14],
array[key]['link']
]);
});
},
datatype: 'json'
});
});
}
});

jQuery ajax loop and iteration scope

I'm wondering why in the code below the i variable still shows "5" instead of showing "1" then "2" then "3" and so on ? Must be a scope issue but I don't really get it as I changed the scope of i variable in global and dom scope and still getting the same problem.
When I alert i outside the ajax function, it works well.
for (var i = 0; i < 5; i++) {
$.ajax({
url: '/echo/html/',
method:'post',
data: {
html: 'Ajax data'
},
success: function (resp) {
$('#success').append(i) // always 5
}
})
$('#outsideAjax').append(i); // is okay
}
Here is the fiddle
EDIT :
I went for #Tushar Gupta solution as it best suits my needs but I get another issue, the iteration won't work if I set this option : processData: false
See the fiddle
Why is this not working ?
This is due to Closures in JavaScript. Here's the fix -
for (var i = 0; i < 5; i++) {
(function(i){
$.ajax({
url: '/echo/html/',
method:'post',
data: {
html: 'Ajax data'
},
success: function (resp) {
$('#success').append(i)
}
})
})(i);
$('#outsideAjax').append(i);
}
you can fix this using closures, wrapping the value of i:
for (var i = 0; i < 5; i++) {
(function(val){
$.ajax({
url: '/echo/html/',
method:'post',
data: {
html: 'Ajax data'
},
success: function (resp) {
$('#success').append(val);
}
})
$('#outsideAjax').append(val); // is okay
})(i);
}
fiddle Demo
var i = 0;
function ajax_call() {
$.ajax({
url: '/echo/html/',
method: 'post',
data: {
html: 'Ajax data'
},
success: function (resp) {
$('#success').append(i++);
if (i < 5) {
ajax_call();
}
}
});
$('#outsideAjax').append(i);
};
ajax_call();
Solution using Function#bind():
http://jsfiddle.net/RQncd/1/
for (var i = 0; i < 5; i++) {
$.ajax({
url: '/echo/html/',
method:'post',
data: {
html: 'Ajax data'
},
success: (function (i, resp) {
$('#success').append(i);
}).bind(null, i)
});
$('#outsideAjax').append(i);
}

Categories