Limit items in ajax request - javascript

I am requesting data from a json to fill a table. I want to limit to 5 the request.
jQuery.getJSON("data/data.json", function(data) {
var table = $("table");
$.each(data, function(id, elem) {
table.append("<tr class='text-center'><td>" + elem.dato1 + "</td><td>" + elem.dato2 + "</td></tr>");
});
})
Or another option is to add boolean key "active" to the data and that it brings me the data items with the value = true. How do i do this?

You can use .slice() to filter the returned array down to just the first 5 elements.
data = data.slice(0, 5);

Just use a simple for loop.
var json_arr, limit;
limit = 5; // set limit to whatever you like
json_arr = JSON.parse(json_data);
for(var i = 0; i < limit; i++;) {
var this_item = json_arr[i];
table.append(this_item); // do your thing
}

The best limit you can implement is on your own controller (where you get your data from)
But if you don't have access/don't want to change, you can simple achive this by JavaScript:
var limit = 5; //your Limit
for(var i in data){
if(i > limit) break;
var elem = data[i];
table.append("<tr class='text-center'><td>" + elem.dato1 + "</td><td>" + elem.dato2 + "</td></tr>");
}

Related

how to list all local storage on page properly in javascript?

I am trying to show all my localstorage items value on my index page but for some reason it is not showing. can anyone see what I am doing wrong in my code below. In my index page script I am looping thorough the length of local storage and trying to display them on screen, only thing that display is one item. Please help. thanks for your help.
here is my code (index page script):
document.addEventListener("DOMContentLoaded", function (event) {
var dataFromLocalStorage = "";
for (var i = 0; i < localStorage.length; i++) {
dataFromLocalStorage =
dataFromLocalStorage + " " + localStorage.getItem(`key${i}`);
}
document.querySelector("#content").innerHTML = dataFromLocalStorage; // Updating same thing
})
The other script where I load it to localStorage:
var addToTheContent = document.getElementById("canvas");
var scheduleEvent = document.getElementById("scheduleStartTime");
var candidateId = document.getElementById('candsId');
var getCandId = document.getElementById("candsId");
var displayCandId = candidateId.options[candidateId.selectedIndex].value;
var id = 1;
function addTheEvent() {
var showText = addToTheContent.innerHTML = displayCandId + " ( " + scheduleEvent.value + " ) ";
localStorage.setItem(`key${id}`, JSON.stringify(showText))
id += 1
localStorage.getItem(`key${id}`);
window.location = "/";
}
"key${id}" is a template string, you need to use backticks `` instead of quotation marks "".
You could also loop through localStorage as you normally would for most JavaScript objects:
for(var key in localStorage) {
if(localStorage.hasOwnProperty(key)) { // ignore the prototype methods
// Do whatever you want with key and value found here
console.log(key + ": " + localStorage[key]);
}
}
Typo: Use i instead id
var dataFromLocalStorage = localStorage.getItem(`key${id}`);
correct:
var dataFromLocalStorage = `localStorage.getItem("key${i}");
Another thing, You are updating same innerHTML
var dataFromLocalStorage = "";
for (var i = 0; i < localStorage.length; i++) {
dataFromLocalStorage =
dataFromLocalStorage + " " + localStorage.getItem(`key${i}`);
}
document.querySelector("#content").innerHTML = dataFromLocalStorage; // Updating same thing
// do something with localStorage.getItem(localStorage.key(i));
// missing template string 'key${id}'
var id = 1;
function addTheEvent() {
var showText = displayCandId + " ( " + scheduleEvent.value + " ) ";
localStorage.setItem(`key${id}`, JSON.stringify(showText));
id += 1;
window.location = "/";
}

How can I print values of nested objects of JSON string?

I have the following JSON response after an XMLHttpRequest:
{
"success":true,
"result":{"1":{"id":"1","question":"What is one + two","answer":"three"},
"2":{"id":"2","question":"two + four","answer":"six"},
"3":{"id":"3","question":"one + three","answer":"for"}
}
}
I want to display all the questions in a bulleted list and all the answers in a bulleted list side-by-side. Right now I have the following (I included this code to add the JSON.parse functionality, should work):
<script type="text/javascript" src="json2.js"></script>
// ...
var response = JSON.parse(xhr.requestText);
var list = document.getElementById('listQuestions');
for (var i = 0 ; i < response.length; i++){
list.innerHTML += '<li>' + response[i].question + '</li>'; // I'm certain this is wrong--I also tried the following but it's not what I'm looking for:
// for (var key in response) {
// console.log("Key: "+key+" value: "+response[key]);
// }
}
// ...
</script>
The result property in your JSON response is an object and not an array. Also, the response variable does not point to the result object but rather the parent, container object so you'll have to access the result object by calling response.result.
var jsonText = '{"success":true,"result":{"1":{"id":"1","question":"What is one + two","answer":"three"},"2":{"id":"2","question":"two + four","answer":"six"},"3":{"id":"3","question":"one + three","answer":"for"}}}';
var response = JSON.parse(jsonText);
var list = document.getElementById('listQuestions');
var results = Object.keys(response.result);
for (var i = 1 ; i <= results.length; i++) {
list.innerHTML += '<li>' + response.result[i].question + ' - ' + response.result[i].answer + '</li>';
}
<div id="listQuestions">
</div>
https://jsfiddle.net/djqrt8z9/
Based on your description I wasn't sure if you wanted two lists because you say you wanted a bulleted list of questions and bulleted list of answers.
var response = {
"success":true,
"result":{
"1":{"id":"1","question":"What is one + two","answer":"three"},
"2":{"id":"2","question":"two + four","answer":"six"},
"3":{"id":"3","question":"one + three","answer":"for"}
}
}
var questions = document.getElementById('listQuestions');
var answers = document.getElementById('listAnswers');
var result = response.result
Object.keys(result).forEach(function(key){
var question = document.createElement('li');
questions.appendChild(question);
question.innerHTML = result[key].question;
var answer = document.createElement('li');
answers.appendChild(answer);
answer.innerHTML = result[key].answer;
})
<ul id="listQuestions"></ul>
<ul id="listAnswers"></ul>
let response = JSON.parse(xhr.requestText);
let qs = [];
for (let obj of response.result) qs.push("<li>"+obj.question+"<\/li>");
document.getElementById('listQuestions').innerHTML = qs.join('');
The above uses the for ... of construct to loop through the values of an object.

Datatables row reorder event issue

var table =$("#exampleList").DataTable({
paging:false,
rowReorder:false
}
});
table.on('row-reorder',function(e, diff,edit){
for(var i=0, ien = diff.length ; i<ien ; i++){
var rowData = table.row(diff[i].node).data();
sequence = sequence + "_" + rowData[0];
}
var data = table.rows().data();
data.each(function (value, index) {
alert('Data in index: ' + index + ' is: ' + value);
});
});
Hi,
I am new to datatables. Issue I am having right now is I cant get the latest value in my table after the user reorder the row. The code above only shows the value before the reorder occurs. I need to get the latest reorder sequence so I can update the database.
What you need to do is wait a few milliseconds before trying to read the data.
table.on('row-reorder',function(e, diff, edit){
for(var i=0, ien = diff.length ; i<ien ; i++){
var rowData = table.row(diff[i].node).data();
sequence = sequence + "_" + rowData[0];
}
setTimeout(()=> { lookAtData() }, 10);
});
function lookAtData() {
var data = table.rows().data();
data.each(function (value, index) {
alert('Data in index: ' + index + ' is: ' + value);
});
}
You should use column-reorder not row-reorder.
Please try :
var rdata = table .columns().order().data();
console.log(rdata);
It will get the data after columns ordering.

How do you generate a previous and next button for an array?

I have a function with this specific array in it.
var elementsArray = xmlDocument.documentElement.getElementsByTagName('track');
// console.log(elementsArray);
var arrayLength = elementsArray.length;
var output = "<table>";
for (var i=0; i < arrayLength; i++)
{
var title = elementsArray[i].getElementsByTagName('title')[0].firstChild.nodeValue;
var artist = elementsArray[i].getElementsByTagName('artist')[0].firstChild.nodeValue;
var length = elementsArray[i].getElementsByTagName('length')[0].firstChild.nodeValue;
var filename = elementsArray[i].getElementsByTagName('filename')[0].firstChild.nodeValue;
console.log(title + ' ' + artist + ' ' + length + ' ' + filename);
output += "<tr>";
output += ("<td onclick='songSelect(\"" + filename + "\")'>" + title + "</td><td>" + artist + "</td>");
output += "</tr>";
}
With this array how would i generate a previous and next button to move.
http://jsfiddle.net/xbesjknL/
Once could use a linked list or even the notion of C-like pointers that point at the prev/curr/next tracks. But alas this is Javascript and the client side is too processing burdened.
So you could just build your own simplified idea of pointers in a cursor like object that is constantly pointing at the current track's index, the previous track's index and the next. And you'd call the refresh method everytime the user clicks the prev or next buttons to update the cursor's pointers accordingly.
var cursor = {
prev:(elementsArray.length-1),
curr:0,
next:(1 % (elementsArray.length-1)),
refresh: function(button){ //button is either the btnPrev or btnNext elements
if (button.getAttribute("id") === "btnPrev") {
old_curr = this.curr;
this.curr = this.prev;
if ((this.curr-1) < 0)
this.prev = elementsArray.length-1;
else
this.prev = this.curr - 1;
this.next = old_curr;
} else {
old_curr = this.curr;
this.curr = this.next;
if ((this.curr+1) > (elementsArray.length-1))
this.next= 0;
else
if (elementsArray.length === 1)
this.next = 0;
else
this.next = this.curr+1;
this.prev = old_curr;
}
}
};
// example usage:
cursor.refresh(btnPrev);
elementsArray[cursor.curr]; // gives the previous track, which is now the current track
You can even simplify this even more by just keeping track of only the current track. Note

jqGrid gridComplete:- getRowData - get row cell value from array

Please - need syntax for setting variables from jqGrid getRowData
property
Looping thru rows - just need to pull the ID and Phrase column values into variables
gridComplete: function () {
var allRowsInGrid = $('#list').jqGrid('getRowData');
for (i = 0; i < allRowsInGrid.length; i++) {
pid = allRowsInGrid[i].ID;
vPhrase = allRowsInGrid[i].Phrase;
vHref = "<a href='#' onclick='openForm(" + pid + ", " + vPhrase + ")'>View</a>";
}
},
Was able to get ID easy enough with getDataIDs :-)
Need help with getting specific column values for pid and vPhrase for i
Cheers
Try this:
var ids = jQuery("#list").jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++)
{
var rowId = ids[i];
var rowData = jQuery('#list').jqGrid ('getRowData', rowId);
console.log(rowData.Phrase);
console.log(rowId);
}
Please Note: If your goal is to add a link to cell which calls a javascript method you can achieve this by using formatter like given below, formatter should be added to colModel like you add other column properties like name,index,width,align etc, so you can avoid the iteration over row data
formatter: function(cellvalue, options, rowObject) {
return "<a href='#' onclick='openForm("
+ rowObject.ID + ", "
+ rowObject.Phrase
+ ")'>View</a>";
}
This is what I use when I want to get Data by RowID for specific Cell.
var selRow = jQuery("#list10").jqGrid('getGridParam','selarrrow'); //get selected rows
for(var i=0;i<selRow.length;i++) //iterate through array of selected rows
{
var ret = jQuery("#list10").jqGrid('getRowData',selRow[i]); //get the selected row
name = ret.NAME; //get the data from selected row by column name
add = ret.ADDRESS;
cno = ret.CONTACTNUMBER
alert(selRow[i] +' : ' + name +' : ' + add +' : ' + cno);
}

Categories