Pagination with JQuery on HTML Page - html

I'm using Go to write the backend with MongoDB. I am using JQuery AJAX to send requests to the API.
I have an API that accepts parameters (page, limit, offset) and returns all records as a response. I want to perform pagination and send these parameters on page Number button click. I have approx 4,50,000 records in the collection.
I have searched some examples using pagination plugin but from what I understood it will first load all records from DB then perform pagination but I do not want to load all records because I am already sending (page, limit, offset parameters to limit records. How we can do that using HTML and JQuery?
<a href='#' onclick='getRecords(page,limit,offset)'>1</a>
I am using using Find().skip().limit().All(&result) in golang. And My HTML code is like first table show first 10 rows from db and then
<a herf='' onclick='getRecords(1,10,0)'>1</a>
<a herf='' onclick='getRecords(2,10,10)'>2</a>
<a herf='' onclick='getRecords(3,10,20)'>3</a>
...
function getRecords(page,limit,offset)
{
$.ajax(){}
}
I want to do it dynamic with next and prev like pagination

This is the most straightforward example I could come up with.
Initially you would populate the results server side with an html template. Or you could have a script do it and populate them similar to how I am doing it in the button click callback.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JQuery Pagination</title>
</head>
<body>
<ul>
<li>1</li>
<li>1</li>
<li>1</li>
</ul>
prev
<span>
</span>
next
</body>
<script
src="https://code.jquery.com/jquery-3.5.1.js"
integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
crossorigin="anonymous"></script>
<script>
let currentPage = 1
let $searchList = $("body > ul")
let $prevButton = $("#prev")
let $nextButton = $("#next")
let maxPages = 23
let maxPageButtons = 5
let pageButtonClick = function() {
currentPage = parseInt($(this).text())
update(currentPage)
console.log(currentPage)
}
let update = function(currentPage) {
$searchList.children().each(function() {
$(this).text(currentPage)
})
let basePage = currentPage
if (basePage + maxPageButtons > maxPages) {
basePage = maxPages - maxPageButtons + 1
}
let basePageOffset = 0
let $newPageButtons = $()
while (basePageOffset < maxPageButtons) {
$newPageButtons = $newPageButtons.add(`${basePage + basePageOffset}`)
basePageOffset++
}
$("span").children().remove()
$("span").append($newPageButtons)
$("span > a").on("click", pageButtonClick)
// Get results and display them.
}
update(currentPage)
$prevButton.on("click", function() {
if (currentPage > 1) {
currentPage--
update(currentPage)
}
})
$nextButton.on("click", function () {
if (currentPage < maxPages) {
currentPage++
update(currentPage)
}
})
</script>
</html>
JSFiddle
If you want to put html in the list item then use the html() method.

It looks like the pagination plug-ins you are using are frontend facing. I would suggest to rewrite the querying of data in your backend in a way such that only the required data is sent to the frontend instead of all the records. You can use the limit(), for limit, and skip(), for offset, mongodb methods interfaces that your driver offers.
Check out this answer to understand how to do this for mongo-go-driver. If you are using any other driver, you can use an equivalent of what's being used in the mongo-go-driver.

Related

Parsing Html Page with Dart

I m trying to parse the following entry in an HTTP get request.
In the body, you see a script tag with a function call where I need to have access to the JSON inside the HTML tag.
<!DOCTYPE html>
<html translate="no">
<head></head>
<body>
<script>
$(function() {
intranet.list.frontend.init({
gridDataAndConfiguration: {
"Here is a big Json - WANTED"
},
},
});
</script>
</body>
</html>
Up to now, I don't parse the HTML with any Dart specific parsing method like
"parse" from package:html/parser.dart. That attempt was successful in searching for all the "script" tags inside the HTML DOM, but unfortunately, I did not find or showed the JSON or function call inside the referred script Tag!
The question is, how to access the JSON in the given HTML Page using Dart?
Solution :
RegExp re = RegExp(r'\[\{.*?\}\]');
var parsedHtml = parse(htmlText);
var allScripts = parsedHtml.getElementsByTagName('script');
for (int i = 0; i < allScripts.length; i++) {
if (allScripts[i].innerHtml.contains(startString)) {
Iterable<String> result =
re.allMatches(allScripts[i].innerHtml).map((m) => m[0]);
List<dynamic> jsonParsed = [];
for (var match in result) jsonParsed.add(jsonDecode(match));
Thanks for your answer & help.

jQuery function preventing nested <body> elements from being read

My assignment is to create a Twitter clone with HTML, CSS, and jQuery. I have been provided a jQuery function that generates 10 tweets, but when I call it in <scripts>, I am only able to get it to run in the <body> tag, and all of my changes to HTML and CSS are canceled out. Basically it just spits out 10 tweets on top of my singular background.
<script>
$(document).ready(function(){
var $body = $('body');
$body.html('Twitter-Clone');
var $tweets = $("tweets-container");
var index = streams.home.length - 1;
while(index >= 0){
var tweet = streams.home[index];
var $tweet = $('<div></div>');
$tweet.text('#' + tweet.user + ': ' + tweet.message);
$tweet.appendTo($body);
index -= 1;
}
});
</script>
And if I write something like
$tweet.appendTo($tweets) <!--or-->
$tweet.appentTo("#tweets-container");
Tweets do not show up at all, AND my page ignores all the HTML and CSS I've written aside from what's at the top of <body>
I really want to know, how can I apply this function to my <div>"tweets-container", and why does the code seem to skip over all of my elements nested in <body> after execution?
I think once I figure this out, it'll be a huge step in the right direction. Any help is very much appreciated! Can supply additional code if needed.

Wixcode "static" html iframe

Apologies if this is not the correct place to post this. I'm completely new to HTML and such, but I wanted to put a button on my website which would remember how many times it been pressed and each time someone presses it it give you a number, say for example the next prime number. With enough googleing I managed to put together some (what I expect is really bad code) which I thought could do this. This is what I have (sorry if its not formatted correctly, I had trouble with copy pasting).
<head>
<title>Space Clicker</title>
</head>
<body>
<script type="text/javascript">
function isPrime(_n)
{
var _isPrime=true;
var _sqrt=Math.sqrt(_n);
for(var _i=2;_i<=_sqrt;_i++)
if((_n%_i)==0) _isPrime=false;
return _isPrime;
}
function nextPrime(_s,_n)
{
while(_n>0)if(isPrime(_s++))_n--;
return --_s;
}
var clicks = 0;
function hello() {
clicks += 1;
v = nextPrime(2,clicks);
document.getElementById("clicks1").innerHTML = clicks ;
document.getElementById("v").innerHTML = v ;
};
</script>
<button type="button" onclick="hello()">Get your prime</button>
<p>How many primes have been claimed: <a id="clicks1">0</a></p>
<p>Your prime: <a id="v">0</a></p>
</body>
The problem is that when I put this code in a iframe on my wixsite it seems to reload the code each time you look at the site, so it starts the counter again. What I would like it say the button has been pressed 5 times, it will stay at 5 until the next visitor comes along and presses it. Is such a thing possible?
You don't actually need an iframe for that, You can use wixCode to do that. WixCode let's you have a DB collection. and all you need to do is update the collection values on every click.
Let's say you add an Events collection can have the fields:
id, eventName, clicksCount
add to it a single row with eventName = 'someButtonClickEvent' and clicksCount = 0
Then add the following code to your page:
import wixData from 'wix-data';
$w.onReady(function () {});
export function button1_click(event) {
wixData.get("Events", "the_event_id")
.then( (results) => {
let item = results;
let toSave = {
"_id": "the_event_id",
"clicksCount": item.clicksCount++
};
wixData.update("Events", toSave)
})
}
now you need to add button1_click as the onClick handler of your button (in the wixCode properties panel).

Mustache.js iterate over all arrays

I'm still busy trying to setup a JSON file to a HTML website. So if the json changes the changes are dynamically loaded in the HTML. Till this far i'm able to retreive the content and even request some content. But not everything that i want because the markup from the JSON is a bit weird.
Because of the cross-site protection I was not able to do a JSOP request directly, so i solved that with a little trick i saw somewhere. I've created a test.php that simply does:
That way I circumvent the cross-site protection, and everything works well. Only problem is that I can't iterate over all the arrays that i want. Currently i'm using the following script to do a JSOP call and get the data. And the output is a nice description between the <li></li>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
</head>
<body>
<ul id="episodes">
</ul>
<script src="http://cdnjs.cloudflare.com/ajax/libs/mustache.js/0.7.0/mustache.min.js"></script>
<script src="http://ps3scenefiles.com/json/handlebars.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script id="episodes-template" type="text/template">
<li>{{description}}</li>
</script>
<script>
$(function() {
$.getJSON('http://ps3scenefiles.com/json/test.php', function(data) {
var template = $('#episodes-template').html();
var info = Mustache.to_html(template, data);
$('#episodes').html(info);
});
});
</script>
</body>
</html>
But when you open the link to the JSON (http://ps3scenefiles.com/json/test.php), you see that the Episodes array has another array with just numbers. How can i create a list like
Episode: 1
Id:13605 Active:true Lang:en Link: url
Id:16525 Active:true Lang:ru Link: url
Episode: 2
Id:14854 Active:true Lang:en Link: url
Id:19445 Active:true Lang:ru Link: url
So to be clear, how can i do a mustache (or handlebars) templating to make it look like the example?
You can use Handlebars helper as mentioned in this answer
Here is a fiddle without styling, that prints out the data you expect (sort of, not all fields).
Here is the helper function -
Handlebars.registerHelper('eachkeys', function(context, options) {
var fn = options.fn, inverse = options.inverse;
var ret = "";
var empty = true;
for (key in context) { empty = false; break; }
if (!empty) {
for (key in context) {
ret = ret + fn({ 'key': key, 'value': context[key]});
}
} else {
ret = inverse(this);
}
return ret;
});

stagger loading of ajax responses

I have a page that displays the status of all objects in a given set of database schemas. Schema objects are shown as a hierarchical tree (schema > object type > object name). There are a lot (thousands) of objects. The status is source-control related (is the object modified/deleted/added/unchanged in comparison to the source controlled version?).
I use a bit of ajax to load an icon representing the status of each object with the intention being that the status can be displayed whenever the asynchronous check completes. What actually happens, is that the loading icons freeze and after all statii requests have resolved, all icons display at the same time. This is unintended and gives the page load an undesirable and distinctly synchronous feel. I envisaged the loading icons changing individually to the correct status icon in some sort of staggered order.
How can I modify my javascript to give a better experience (icons transforming from loading gif to status png individually, rather than all at the same time)?
Here's some code:
$(window).load(function () {
#foreach (var schema in Model) {
foreach (var o in schema.Objects) {
#:$.getJSON('#Url.Action("ObjectStatus")', {service:'#schema.Service', schema:'#schema.Name', objectName:'#o.Name', objectType:'#o.Type'}, function (data) {
#:$('##string.Format("{0}-{1}", schema.Name, o.Name)').attr('src', '/Content/images/' + data + '.png');
#:});
}
}
});
...
<ul id="treeview">
#foreach (var schema in Model)
{
<li>#schema.Name<br />
<ul>
#foreach (var t in schema.Objects.Select(x=>x.Type).Distinct())
{
var objectType = t;
<li>#string.Format("{0}{1}", objectType, objectType.EndsWith("x") ? "es" : "s")<br />
<ul>
#foreach (var o in schema.Objects.Where(x => x.Type == objectType))
{
<li>
<img src="#Url.Content("~/Content/images/loading.gif")" alt="checking status..." id="#string.Format("{0}-{1}", schema.Name, o.Name)"/>
#Html.ActionLink(o.Name, "Diff", "Browse", new { service = schema.Service, schema = schema.Name, objectName = o.Name, objectType }, null)
</li>
}
</ul>
</li>
}
</ul>
</li>
}
</ul>
and here's what the finished tree looks like:
You're not going to get a true 'multi threaded' look and feel with javascript; it's simply not available.
What you can do is push all of your requests into an array, and then shift the first element off of the list for your next ajax request.
function getResponse()
{
if(myRequestArray.length == 0)
return;
var elementToRequest = myRequestArray.shift();
$.ajax({
url: '/some/url/',
data: { someData: elementToRequest.someData },
success: getResponse
});
}
Your callback will be the method invoked so you start the next request. This way, your UI can remain 'responsive' while the ajax requests complete. It's going to appear synchronous only so far as the ordering of the elements in the array get updated in order.
May not be best solution out there, but try this..
set
async : false
on your jquery call..