Split html table values using java script - javascript

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

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

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

AJAX requests inside a loop

I am trying to call multiple ajax requests inside a loop to load multiple dropdown lists. I tried the sequential way and i can see that the last item in loop only is getting filled with values
var targetcontrols = [];
var targetcontrols_array = targetControl.split(',');
var targetsourcecontrols = [];
var targetsource_array = targetSource.split(',');
for(i=0; i < targetcontrols_array.length; i++)
{
var control_name=targetcontrols_array[i];
var source=targetsource_array[i];
$.ajax({
url: action_url,
type: 'POST',
traditional: true,
async: false,
data: JSON.stringify( { allselected: allselected_flag, selectedIds: selectedvalues,targetControl:control_name, targetSource: source, dependency: dependencyOptions } ),
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (response) {
//To clear existing items
var target= $("#"+response.targetControl);
target.multiselect('dataprovider', []);
var dropdown2OptionList = [];
for (i = 0; i < response.values.length; i++) {
dropdown2OptionList.push({
'label': response.values[i].text,
'value': response.values[i].value
})
}
console.log("--control"+control_name);
//re initialize the search plugin
target.multiselect('dataprovider', dropdown2OptionList);
target.multiselect('rebuild');
}
});
How can i ensure the first item in the loop also is getting filled with response values
You can try map to produce an array of Promise. After that use Promise.all() to execute this promises array.
var targetcontrols = [];
var targetcontrols_array = targetControl.split(',');
var targetsourcecontrols = [];
var targetsource_array = targetSource.split(',');
const arrOfPromises = targetcontrols_array.map(function(item, index) {
const control_name = item;
const source = targetsource_array[index];
return new Promise((resolve) => {
$.ajax({
url: action_url,
type: 'POST',
traditional: true,
async: false,
data: JSON.stringify( { allselected: allselected_flag, selectedIds: selectedvalues,targetControl:control_name, targetSource: source, dependency: dependencyOptions } ),
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (response) {
//To clear existing items
var target= $("#"+response.targetControl);
target.multiselect('dataprovider', []);
var dropdown2OptionList = [];
for (i = 0; i < response.values.length; i++) {
dropdown2OptionList.push({
'label': response.values[i].text,
'value': response.values[i].value
})
}
console.log("--control"+control_name);
//re initialize the search plugin
target.multiselect('dataprovider', dropdown2OptionList);
target.multiselect('rebuild');
resolve(`done for url ${control_name}`) // Show log for checking process
}
})
})
Promise.all(arrOfPromises)
These 2 declarations:
var control_name = targetcontrols_array[i];
var source = targetsource_array[i];
maybe cause the problem. Because var has function scope and for loop is a block scope, so when you use the loop, these control_name and source variables got replaced from the next one, before used in ajax request. That's why you always get the last. You should change var into const or let which support block scope
const control_name = targetcontrols_array[i];
const source = targetsource_array[i];
First of all if you use jquery, utilize it's full potential, instead of for loops, use
$.each:
var targetcontrols = [];
var targetcontrols_array = targetControl.split(',');
var targetsourcecontrols = [];
var targetsource_array = targetSource.split(',');
$.each(targetcontrols_array, function(i, item)
{
var control_name=targetcontrols_array[i];
var source=targetsource_array[i];
$.ajax({
url: action_url,
type: 'POST',
traditional: true,
async: false,
data: JSON.stringify( { allselected: allselected_flag, selectedIds: selectedvalues,targetControl:control_name, targetSource: source, dependency: dependencyOptions } ),
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (response) {
//To clear existing items
var target= $("#"+response.targetControl);
target.multiselect('dataprovider', []);
var dropdown2OptionList = [];
$.each(response.values, function(v, vItems) {
dropdown2OptionList.push({
'label': response.values[v].text,
'value': response.values[v].value
})
});
console.log("--control"+control_name);
//re initialize the search plugin
target.multiselect('dataprovider', dropdown2OptionList);
target.multiselect('rebuild');
}
});
});

How to use q.js to chain backbone model?

I have the following:
var q = new app.models.OverwriteLineItemsProcess();
q.set('id', $("#process_id").val());
q.saveSource($("#source_quote").val());
q.lockSource();
saveSource is sending data to the backend using ajax. So is lockSource.
I want to execute in this SEQUENTIAL manner: saveSource >> lockSource.
How do I write the q.js to make it work?
By q.js, I mean https://github.com/kriskowal/q
UPDATE: added saveSource and lockSource
saveSource: function (quotation_id) {;
var type = "PUT";
var verb = "Updated";
var headers = {
'X-HTTP-Method-Override': type
};
var url = app.base_url + "/overwrite_line_items/" + this.id;
this.set('source_quote', quotation_id);
var data = this.toFormData();
var result = false;
var currentModel = this;
var settings = {
headers: headers,
type: type,
url: url,
data: data,
success: function(json) {
response = JSON && JSON.parse(json) || $.parseJSON(json);
console.log(response);
currentModel.lockSource();
$("#facebox-source-quote-status").html('<font color="green">SELECTED</font>');
},
error: function(response) {
$("#facebox-source-quote-status").html('<font color="red">UNABLE TO SELECT</font>');
},
dataType: 'json'
};
$.ajax(settings).done(function() {
});
},
lockSource: function () {
var type = "PUT";
var verb = "Updated";
var headers = {
'X-HTTP-Method-Override': type
};
var url = app.base_url + "/quotations/is_editable/" + this.attributes.source_quote;
var data = this.toFormData();
var result = false;
var currentModel = this;
var settings = {
headers: headers,
type: type,
url: url,
data: data,
success: function(response) {
console.log(response);
},
error: function(response) {
$("#facebox-source-quote-status").html('<font color="red">UNABLE TO SELECT</font>');
},
dataType: 'json'
};
$.ajax(settings).done(function() {
});
},
The jQuery.ajax function which you're using already returns a promise for its result. You just need to return that from your functions:
saveSource: function (quotation_id) {;
…
var settings = {
headers: headers,
type: type,
dataType: 'json', // jQuery will automatically parse it for you
url: url,
data: data
};
return $.ajax(settings).done(function() {
// ^^^^^^
$("#facebox-source-quote-status").html('<font color="green">SELECTED</font>');
// notice I did remove the currentModel.lockSource(); call from the callback
}, function() {
$("#facebox-source-quote-status").html('<font color="red">UNABLE TO SELECT</font>');
});
},
lockSource: function () {
…
var settings = // analoguous, no callbacks here
return $.ajax(settings).fail(function(response) {
$("#facebox-source-quote-status").html('<font color="red">UNABLE TO SELECT</font>');
});
}
Now you can easily chain them:
var q = new app.models.OverwriteLineItemsProcess();
q.set('id', $("#process_id").val());
q.saveSource($("#source_quote").val()).then(function(saveResponse) {
console.log(saveResponse);
return q.lockSource();
}).done(function(lockResponse) {
console.log(lockResponse);
});
You don't even need Q for that. If you want to use it, wrap the $.ajax() calls in a Q() invocation, as explained in the Converting JQuery Promises to Q section of the docs.

Categories