load more button in nodejs - javascript

I have json file in series.pug page. When I click load more button want to make a request JSON file and add new element in the page. How can I make load more with using NodeJS or AJAX in pug page ?
extends layout
block content
.content(style='padding-bottom: 100px;')
#titles
.container
.row
.col-md-12
.form-group.text-center
label.col-md-2.text-right Quick Filter
input.search.col-md-6.text-center(type="text",placeholder='Search series quickly')
.row.list
-var count = 0
each value in data.entries
-if(value.programType =='series')
if(count!=18)
.col-md-3.col-sm-6.col-lg-2.series(data-item-id=++count)
figure.figure
a(href='/details/'+value.title)
img.figure-img.img-fluid.rounded(src=value.images['Poster Art'].url, alt=value.title)
.name.figure-caption.text-center.text-dark=value.title
.col-lg-12
a.btn.btn-primary.text-light.load Load More
script.
$('.load').click(function(){
var lastchild = $('.series').last().data('item-id');
$.ajax({
url: '/request',
method: 'POST',
data:{'lastchild':lastchild},
success: function(response){
}
});
});

You need to create a new route that you can make an API call to that returns only partial HTML. So something like this:
$.ajax('/loadmore?data=jsonFileName&template=pugTemplateName&startIndex=10&load=20');
Then in node, you'd have logic listening for this route, and when it comes in, you have node build out your html using your pug template.
So you're query params in this example would be:
data = .json file to pull data from
template = .pug file to use as template, should not `extend layout`
startingIndex = starting index for getting data from .json file
load = number items to render html for
Finally, you need to use a pug template that does not extend layout, so you only get a <div> back, and not an entire <html> document. In the pug template, pull in the json file, loop through the number of items you want (specified by startingIndex, and load), and then send the result of the pug file back to the browser.
The result of the AJAX call will be partial html, like a <div> or <ul>, but not an entire <html> document. You can then just append it to your webpage where it should be displayed.
Obviously, this is just a rough guide on how to do it, but if you set up the logic like this, you can use this call for any load-more functionality you might need on your site. If you post your source code to github, I might be able to give more specifics.

Related

HTML form submission(POST req) to the server should return a dynamic HTML

How do I get the server-side(in NodeJS and Express) to return a new HTML page after receiving a post request?
Let's say the HTML page a several fields and each needs to be checked (which could be done using Javascript) in the HTML page itself.
But after submitting the form, the server-side does some heavy calculation (let's say it take 5 seconds on complete it, maybe more).
And then the server-side returns a new HTML page which highlights results of all the input fields individually.
I can't use a static HTML page to be returned since there can be many outcomes and I want the HTML page (send by the server) to dynamically adjust based on the calculation done by the server.
q1. How can I create this dynamic HTML page on the server-side?
q2. How do I show the user a loading screen when server-side is performing the calculations?
Correct me if I am wrong
a1. I believe I can create some sort of static HTML template with EJS/JADE/PUG/HANDLEBARS and then pass the result of the calculations and let JS Script(in HTML) handle how it is displayed.
a2. I do no have an idea about it now.
You can make an ajax call to your server & return success / error data / calculations in json format
Then use this json to add dynamic html content on your page using client side javascript
$.ajax({
url: '/admin/login',
method: 'POST',
data: {'key':'value'},
beforeSend: function(){
// show loader
},
success: function(response) {
// hide loader
// add dynamic html to dom from here
});
Hope this helps

How to save a dynamic html page which displays results of tests written in javascript

I have a dynamic html page index.html.
When I hit that page in the browser it runs some tests which is written in JS and generates dynamic results on the page. On every reload it writes fresh data on index.html page.
Now I want to save this html page into another html page so that I can save the results and view later.
One method of doing it would be to write the dynamic results to an element on the page, and then save the contents of that via an ajax call.
For example create an element with an ID results on your index.html page:
<div id="results"></div>
Write the dynamic results to this element. I'm going to write the js in jquery syntax for brevity; but you can adapt this to vanilla js:
$('#results').html(data); // data is the dynamic content
Now you can grab the data inside #results and make an ajax call to a script which could write it to a HTML file:
$(function() {
$.ajax({
url: '/save-data.php', // script to save your data
method: 'POST',
cache: false,
data: {
results: $('#results').val() // the html inside #results
}
});
});
Your save-data.php script would read the contents in the POST variable ($_POST['results']) and then write it to a file, e.g.
<?php
$fp = fopen('data.html', 'w');
fwrite($fp, $_POST['results']);
?>
This is merely to illustrate the concepts required. You need to take care of security, particularly sanitising the POST data.
The js to make the ajax call will execute on page load of index.html. You could adapt this to work when the user presses a button or takes some other action. You may also want to look at the .done() method in jquery because this is where you could perform checks to see if save-data.php has actually saved the data and display an appropriate message.
For example save-data.php might return a JSON response on successfully saving the data:
echo json_encode(['result' => 'success']);
You could then use the .done() callback to display an appropriate message to the user when the data has been saved:
// previous ajax code
// ...
.done(function(response) {
if (response.result == 'success') {
// write message to the page to say it's been done successfully
// You will need an element with the class .status to hold the message, e.g. <span class="status"></span>
$('.status').html('Successfully saved your page').
}
});

How to handle multiple AJAX behaviors in one HTTP request?

I am using jQuery. I have implemented a multipart web page where a list of links* are rendered and each link is periodically updated through AJAX HTTP requests. That is, on the page there are many links of which each one is "timer-triggered" through JavaScript so to perform a HTTP request to the URL pointed by the link itself and, on response success, to replace those links with the retrieved data (the updated links).
This implementation works but it is "performance less" in cases when the page contains many links: one AJAX request is executed per link resulting in many hits to the server. In order to solve that performance issue I thought to make the JavaScript code to execute a unique AJAX request that retrieves the whole set of links and then to replace DOM data.
However I do not know how to implement the "unique request" mostly due to the practice/technique that I have to use and since it is the first time I notice this kind of problem. What can I do? Should I implement a JavaScript handler for event-registration or what?
* In my case link elements are used (<a></a> HTML tags) but those can be anything associated with a URL.
Update after the jfriend00 answer
If the solution is to build a JSON array as jfriend00 describes in his answer then I should implement the page behavior so to update the JSON array dynamically. Since my HTML links are even rendered dynamically along with some JavaScript code then that JavaScript code could update the JSON array dynamically by "registering"/"unregistering" links. If this is a solution in my case, how can I implement it?
I render links as "partial templates" along with the JavaScript code which JavaScript makes those links to execute AJAX requests. HTML-JS code per each link (the mentioned "partial templates") looks like the following:
<script type="text/javascript">
(function() {
var link = $('#link_1')
...
}());
</script>
It seems like you can just send some JSON that is your array of links to request and then receive JSON back that is an object where each key is the requested link and the data is the server response for that particular link.
If the links you want to process look something like this:
<a class="myLink" href="xxx"></a>
It could look something like this:
function processLinks()
// assuming you can specify some CSS selector to select the links in your page that
// you want to target
// create an array of URLs for the ajax call
// and an index of arrays --> DOM objects so we know which DOM object goes
// with a given URL when processing the ajax results
var urlArray = [];
var urlIndex = {};
var urlArray = $(".templateLink").each(function() {
urlArray.push(this.href);
urlIndex[this.href] = this;
});
$.ajax({
url: "your ajax url here",
data: JSON.stringify(urlArray),
dataType: "json"
}).done(function(data) {
// assumes you get data back as {"url1": data1, "url2": data2, ...}
$.each(data, function(url, urlData) {
// get DOM object that goes with this URL
var domObj = urlIndex[url];
// apply urlData to domObj here
})
});
}
Updating my answer now that you've disclosed your "partial templates".
To process them all at once, change this type of structure which processes them one at a time:
<script>
(function() {
var link = $('#link_1')
...
}());
</script>
<a href="yyy" id="link_2></a>
<script>
(function() {
var link = $('#link_2')
...
}());
</script>
to this which finds them all in the DOM and process them all at once:
<script>
// process all the template links
$(document).ready(processLinks);
</script>

Refresh Part of Page (div)

I have a basic html file which is attached to a java program. This java program updates the contents of part of the HTML file whenever the page is refreshed. I want to refresh only that part of the page after each interval of time. I can place the part I would like to refresh in a div, but I am not sure how to refresh only the contents of the div. Any help would be appreciated. Thank you.
Use Ajax for this.
Build a function that will fetch the current page via ajax, but not the whole page, just the div in question from the server. The data will then (again via jQuery) be put inside the same div in question and replace old content with new one.
Relevant function:
http://api.jquery.com/load/
e.g.
$('#thisdiv').load(document.URL + ' #thisdiv');
Note, load automatically replaces content. Be sure to include a space before the id selector.
Let's assume that you have 2 divs inside of your html file.
<div id="div1">some text</div>
<div id="div2">some other text</div>
The java program itself can't update the content of the html file because the html is related to the client, meanwhile java is related to the back-end.
You can, however, communicate between the server (the back-end) and the client.
What we're talking about is AJAX, which you achieve using JavaScript, I recommend using jQuery which is a common JavaScript library.
Let's assume you want to refresh the page every constant interval, then you can use the interval function to repeat the same action every x time.
setInterval(function()
{
alert("hi");
}, 30000);
You could also do it like this:
setTimeout(foo, 30000);
Whereea foo is a function.
Instead of the alert("hi") you can perform the AJAX request, which sends a request to the server and receives some information (for example the new text) which you can use to load into the div.
A classic AJAX looks like this:
var fetch = true;
var url = 'someurl.java';
$.ajax(
{
// Post the variable fetch to url.
type : 'post',
url : url,
dataType : 'json', // expected returned data format.
data :
{
'fetch' : fetch // You might want to indicate what you're requesting.
},
success : function(data)
{
// This happens AFTER the backend has returned an JSON array (or other object type)
var res1, res2;
for(var i = 0; i < data.length; i++)
{
// Parse through the JSON array which was returned.
// A proper error handling should be added here (check if
// everything went successful or not)
res1 = data[i].res1;
res2 = data[i].res2;
// Do something with the returned data
$('#div1').html(res1);
}
},
complete : function(data)
{
// do something, not critical.
}
});
Wherea the backend is able to receive POST'ed data and is able to return a data object of information, for example (and very preferrable) JSON, there are many tutorials out there with how to do so, GSON from Google is something that I used a while back, you could take a look into it.
I'm not professional with Java POST receiving and JSON returning of that sort so I'm not going to give you an example with that but I hope this is a decent start.
You need to do that on the client side for instance with jQuery.
Let's say you want to retrieve HTML into div with ID mydiv:
<h1>My page</h1>
<div id="mydiv">
<h2>This div is updated</h2>
</div>
You can update this part of the page with jQuery as follows:
$.get('/api/mydiv', function(data) {
$('#mydiv').html(data);
});
In the server-side you need to implement handler for requests coming to /api/mydiv and return the fragment of HTML that goes inside mydiv.
See this Fiddle I made for you for a fun example using jQuery get with JSON response data: http://jsfiddle.net/t35F9/1/
Usefetch and innerHTML to load div content
let url="https://server.test-cors.org/server?id=2934825&enable=true&status=200&credentials=false&methods=GET"
async function refresh() {
btn.disabled = true;
dynamicPart.innerHTML = "Loading..."
dynamicPart.innerHTML = await(await fetch(url)).text();
setTimeout(refresh,2000);
}
<div id="staticPart">
Here is static part of page
<button id="btn" onclick="refresh()">
Click here to start refreshing every 2s
</button>
</div>
<div id="dynamicPart">Dynamic part</div>
$.ajax(), $.get(), $.post(), $.load() functions of jQuery internally send XML HTTP request.
among these the load() is only dedicated for a particular DOM Element. See jQuery Ajax Doc. A details Q.A. on these are Here .
I use the following to update data from include files in my divs, this requires jQuery, but is by far the best way I have seen and does not mess with focus. Full working code:
Include jQuery in your code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Create the following function:
<script type="text/javascript">
function loadcontent() {
$("#test").load("test.html");
//add more lines / divs
}
</script>
Load the function after the page has loaded; and refresh:
<script type="text/javascript">
$( document ).ready(function() {
loadcontent();
});
setInterval("loadcontent();",120000);
</script>
The interval is in ms, 120000 = 2 minutes.
Use the ID you set in the function in your divs, these must be unique:
<div id="test"></div><br>

How can one incorporate JSON data with the returned HTML on the first request to the home page?

My scenario is this - the user asks for the home page and then the javascript code of the page executes an ajax GET request to the same server to get some object.
The server keeps the home page as a jade template.
So, right now it takes two roundtrips to load the home page:
GET the home page
GET the JSON object
I am OK with it, but just out of curiosity - what are my options to incorporate the object requested later into the initial GET request of the home page?
I see one way is to have a hidden html element, which inner HTML would be the string representation of the object. A bit awkward, but pretty simple on the server side, given that the home page jade template is preprocessed anyway.
What are my other options?
Please, note that I am perfectly aware that sparing this one roundtrip does not really matter. I am just curious about the techniques.
Another option is to always return a JSON object, then the HTML for your home page would be the value of some property on this object. This would probably require some changes on your client-side logic, though.
One more option: instead of a hidden HTML input/textarea containing a JSON string, the home page code could contain a script block where an object literal is declared as a variable. Something like this:
<script>
var myObj = ... // Your JSON string here.
// myObj will be an object literal, and you won't need
// to parse the JSON.
</script>
The initial GET request will retrieve just that document. You can have additional documents loaded defined as scripts at the bottom of your page, so you don't need to do a XHR, for the initial load.
For instance:
GET /index.html
//At the bottom you have a <script src="/somedata.js"></script>
GET /somedata.js
//here you define you var myObj = {}.... as suggested by bfavertto
Depending on which server side technology are you using, this could be for instance in MVC3
public partial class SomeDataController : BaseController
{
public virtual ContentResult SomeData()
{
var someObject = //GET the JSON
return Content("var myObj = " + someObject, "application/javascript");
}
}
You can embed the Json data inside a hidden tag in your HTML. At runtime, your javascript reads the data from this hidden tag instead of making a Json call (or make the call if this data is not available).
<!--the contents of this div will be filled at server side with a Json string-->
<div id="my-json-data" style="display:hidden">[...json data...]</div>
on document ready:
var jsonStr = document.getElementById( "my-json-data" ).innerHTML;

Categories

Resources