Add array elements to list - javascript

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 */)

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

How to pass local storage item to MVC controller

I am trying to pass an array of strings from my local storage (key value) to MVC controller. Here's my code:
In cshtml View file:
<script>
function getFavouriteBooks() {
var ids = JSON.parse(localStorage.getItem("bookIds"));
// returns: ["1", "2", "3"]
$.ajax({
type: "POST",
traditional: true,
url: '#Url.Action("Favourites", "Home")',
data: { ids: ids },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
alert(result.Result);
}
}});
}
</script>
<button onClick="getFavouriteBooks()">Display Favourites</button>
My controller:
public async Task < ViewResult > Favourites(string ids) {
// code that fetches book data from API
if (data != null)
{
var bookList = JsonConvert.DeserializeObject < Book[] > (data);
foreach(var book in bookList) {
var matches = new List < bookList > ();
if (bookList.All(book => ids.Contains(book.Id))) {
matches.Add(book);
}
return View("Index", matches.ToArray());
}
}
return View("Index");
}
The controller action gets called successfully on the button click but the ids parameter is always null even though it isn't when in the console. Where am I going wrong?
from what you have described, I strongly feel this is the problem of expecting asynchronous function to behave synchronously,
await foreach(var book in bookList) {
var matches = new List < bookList > ();
if (bookList.All(book => ids.Contains(book.Id))) {
matches.Add(book);
}
return View("Index", matches.ToArray());
}
Try adding await before you call foreach loop. or better use for in loop
Thanks for your help everyone, the solution was actually to change this part of the ajax call to:
data: { ids: localStorage.getItem('videoIds') },
This code was tested in Visual Studio.
You have to create a viewModel:
public class IdsViewModel
{
public string[] Ids { get; set; }
}
Replace this:
var ids = JSON.parse(localStorage.getItem("bookIds"));
// returns: ["1", "2", "3"]
// or you can use
var ids = localStorage.getItem('videoIds'); //it still will be working
$.ajax({
type: "POST",
traditional: true,
url: '#Url.Action("Favourites", "Home")',
data: { ids: ids },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
with this
var ids= JSON.parse(localStorage.getItem("bookIds"));
$.ajax({
type: "POST",
url: '/Home/Favourites',
data: { ids:ids },
success: function (result) {
....
and the action
public async Task <ActionResult> Favourites(IdsViewModel viewModel) {
var ids=viewModel.Ids;
.....

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

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

Categories