Refresh MEN stack webpage without refreshing the entire page - javascript

I am creating a data analytics dashboard using the MEN stack. (express,node,ejs) However, I would like to display the real-time data that refreshes every 5 seconds WITHOUT refreshing the HTML page which I am doing so currently using the following scripts.
Everything works. But, it's kind of an eyesore to see the page refreshing all the time. Is there a way to use AJAX or something to refresh a particular DIV or PAGE?? I've tried different AJAX functions on different places but it doesn't work. Maybe am doing it the wrong way. Any advice?
async showTasksMain(req, res) {
const queryWeather = "SELECT * FROM c ORDER BY c.EventProcessedUtcTime desc"
const items = await this.taskDao.findweather(queryWeather); //Return variables
const tempdata = await this.taskDao.findtempdata(queryWeather);
res.render("index",{items:items, tempdata:tempdata});
}
async findweather(queryWeather) {
debug("Querying for items from the database");
if (!this.container) {
throw new Error("Collection is not initialized.");
}
const { result: results } = await this.container.items
.query(queryWeather)
.toArray();
var obj = results[0];
return obj;
}
app.get("/", (req, res, next) => taskList.showTasksMain(req, res).catch(next));
<script type = "text/JavaScript">
function AutoRefresh( t ) {
setTimeout("location.reload(true);", t);
}
</script>
<body onload="JavaScript:AutoRefresh(30000)">;

Here is a sample javascript code to refresh partial page like some div
Suppose , you have menu like beloe:
ul id="menu">
<li>About Us
<li>Services
<li>Products
</ul>
and you have content div like below:
<div id="content"></div>
you can then write a code something like:
$("#menu li a").click(function(e) {
// prevent from going to the page
e.preventDefault();
// get the href
var href = $(this).attr("href");
$("#content").load(href, function() {
// do something after content has been loaded
});
});
You can refer Load
Load data from the server and place the returned HTML into the matched element.
Hope it helps.

Related

How to access the arrays of strings inside <script> which is inside handlebar page inline rendering from nodejs?

Here is the route nodejs code from where I am sending data by rendering this handlebar page to script code:
router.route('/profile/view/:id').get(function(req, res, next) {
var element = "Buyers, Sellers, Investors";
var separatedStringArray = element.split(',');
res.render('viewTask',
{
hiding:false,
separatedStringArray :separatedStringArray
});
})
And this is the handlebar page where inside I am having script code as follows:
<script>
var hide = {{hiding}};
if(hide)
{
$('.imag-close').show();
$('.commonText2').hide();
}
else {
$('.imag-close').hide();
$('.commonText2').show();
}
alert({{separatedStringArray}});
$.each({{separatedStringArray}}, function(index, objValue) {
alert(objValue);
})
</script>
Although I am getting the {{hiding}} value inside script tag but I am unable to access the array elements inside the same script tag. I am not getting any alerts of array elements. How to access the array of elements here then? Any idea please help!!

How to pass data for partial view using Jquery

I have next code:
#foreach (var offer in Model.Packages)
{
#Html.Partial("Search/PackageOffer", new Primera.Site.WebUI.Models.ViewModels.Search.PackageOfferViewModel
{
Package = offer,
DisplayPricePerPerson = Model.DisplayPricePerPerson,
RoomsCount = Model.RoomsCount
})
}
I need to implement infinite scroll using js. How can I call render partial view on js and pass parameters on it?
As a very basic demo, you want to have a Partial View that is returning some sort of html to you. In my case this is just the next 10 numbers based on the the number submitted:
public IActionResult _InfiniteNumbers(int lastId)
{
var Ids = Enumerable.Range(lastId, 10);
return PartialView(Ids);
}
In a real world scenario this would be the next n entities of whatever - blogs, orderitems, comments.
The view for this is fairly straight forward as well:
#model IEnumerable<int>
#foreach (var number in Model)
{
<li data-number="#number">#number</li>
}
it just renders every number as a list item.
My main view then looks like this:
<h1>InfiniteNumbers</h1>
<ul id="partial-view-container">
</ul>
<input id="btnLoadMore" type="button" name="loadMore" value="Load More numbers" />
#section scripts {
<script>
$(document).ready(() => {
$("#btnLoadMore").click(() => { //the trigger
var ul = $("#partial-view-container"); //our container for all partial views
let lastId = 0; //the lastId displayed
let lastLi = $("#partial-view-container li:last-child"); //find the last number
if (lastLi.length !== 0) {
lastId = lastLi.attr("data-number"); //if we found something set the value
//lastId = +lastLi.data("number");
}
$.get(`/Home/_InfiniteNumbers?lastId=${lastId}`) //call our action method
.then((res) => {
ul.append(res); //append the html to the container
});
});
});
</script>
}
We have a <ul></ul> element that serves as our container for infinite loading. Since I am lazy, I am using a button as the trigger. In a more complex scenario, this would be an event waiting for the scrollbar to reach the bottom of the page or something similar. I'll leave this up to you.
We then query the list for its last <li> item and get its data-number attribute.
After this, we query our action method and get the next 10 items based on that number and finally just inject them into our view.

Using part of Text to control redirect using Protractor

In our project, there are different urls assigned to different categories of product. If the product category is Cat1, click on edit button should take the user to the Cat1 page, and Cat2 should take the user to Cat2 page. However these categories are in a dynamic table so we can not use a fix reference for the edit buttons, and I am trying to make it dynamic. Below is my code snippet:
it('should take the user to appropriate page', function () {
expect(globalVariables.Edit_Button_1.isDisplayed());
// get rows
var row_1 = globalVariables.tableData_Dashboard.all(by.tagName("tr")).get(1);
// get cell values
var cells = row_1.all(by.tagName("td"));
var Cetegory = cells.get(3).getText().then(function (GL) {
// console.log(GL)
return GL;
});
globalVariables.Edit_Button_1.click();
browser.wait(EC.invisibilityOf(globalVariables.Edit_Button_1), 25000, 'Edit button is not disappearing yet');
if (Cetegory.endsWith('Cat1')){
expect(browser.getCurrentUrl()).toEndWith("Cat1");
}
else {
expect(browser.getCurrentUrl()).toEndWith("Cat2")
}
The tests fails with the log " Failed: Cetegories.endsWith is not a function ..
How can this be fixed?
Cetegory is a promise, not a string. Thus it does has function endsWith. You need to consume the promise eventual value in then() as following.
Cetegory.then(function(_Cetegory){
if (_Cetegory.endsWith('Cat1')){
expect(browser.getCurrentUrl()).toEndWith("Cat1");
}
else {
expect(browser.getCurrentUrl()).toEndWith("Cat2")
}
})

Listview populates on first load, but not if you visit page by clicking a link

I'm just learning Adobe Air with JQuery, and I'm using some sample code from a Sitepoint tutorial. I've encountered a rather unusual problem. If I view the page with the list view by using the "Preview in Adobe Air" option in Dreamweaver, it populates fine. If I navigate away from the page and come back to it, the listview doesn't populate, and the rest of the javascript on the page stops working.
This is the code for populating the listview:
function ListNotes() {
var notes = GetNotes();
$("#notes").empty();
var numRecords = notes.data.length;
for (i=0;i<numRecords;i++) {
$('#student-list').append("<li><a href=\"#\">"+unescape(notes.data[i].name)+" "+unescape(notes.data[i].lastseen)+"<br \/>"+unescape(notes.data[i].belt)+"<br \/>Last Session: <\/a><\/li>");
}
$('#student-list').listview('refresh');
$(".note_time a").click(function(){
var currHash = $(this).attr("href").split('/');
var id = currHash[1];
var dbQuery = new air.SQLStatement();
dbQuery.sqlConnection = db;
dbQuery.text = "DELETE FROM students WHERE id=" + id;
try {
dbQuery.execute();
} catch (error) {
air.trace("Error deleting note from DB:", error);
air.trace(error.message);
return;
}
ListNotes();
});
}
The listview goes inside a div:
<div data-role="content" data-theme="a"><ul data-role="listview" data-inset="true" id="student-list" data-filter="true"></ul></div>
There's a snippet in notes.js that populates the listview:
$(document).ready(function(){
BindEvents();
CreateMenus();
SetupDB();
ListNotes();
});
The page works fine on first loading via "Preview in Adobe Air", but doesn't work at all if you navigate to it via clicking a button inside the app. I suspect I'm missing something really obvious but would appreciate any tips.
Thanks
I would try this:
$(".note_time a").on('click', function(){
//your code here
});

Detect change in hash value of URL using JavaScript

I'm working on a simple application which is single page based (due to project restrictions) and has dynamic content. I understand the dynamic content alright but what I don't understand is how to set-up a script that changes the html of a div when the hash value in the URL changes.
I need a JavaScript script to work as such:
Url: http://foo.com/foo.html div contents: <h1>Hello World</h1>
Url: http://foo.com/foo.html#foo div contents: <h1>Foo</h1>
How would this work?
Please help! Thanks.
You can listen to the hashchange event:
$(window).on('hashchange',function(){
$('h1').text(location.hash.slice(1));
});
personally, I'd use sammy which gives you the flexibility to template the hashtag (add placeholders and be able to read them back). e.g.
<script src="/path/to/jquery.js"></script>
<script src="/path/to/sammy.js"></script>
<script>
$(function(){
// Use sammy to detect hash changes
$.sammy(function(){
// bind to #:page where :page can be some value
// we're expecting and can be retrieved with this.params
this.get('#:page',function(){
// load some page using ajax in to an simple container
$('#container').load('/partial/'+this.params['page']+'.html');
});
}).run();
});
</script>
Load foo.html
Load bar.html
An example can be found here: http://jsfiddle.net/KZknm/1/
Suppose we have list of items, each items has a hash tag as #id
const markup = `
<li>
<a class="results__link" href="#${recipe.recipe_id}">
<figure class="results__fig">
<img src="${recipe.image_url}" alt="${limitRecipeTitle(recipe.title)}">
</figure>
<div class="results__data">
<h4 class="results__name">${recipe.title}</h4>
<p class="results__author">${recipe.publisher}</p>
</div>
</a>
</li>
`;
Now when a user click on any of those list item or reload (http://localhost:8080/#47746) an item with hash tag, hash event will be fired. To recive the fired hash event we must register hash event listener in our app.js
//jquery:
['hashchange', 'load'].forEach(event => $(window).on(event, controlRecipe));
//js:
['hashchange', 'load'].forEach(event => window.addEventListener(event, controlRecipe));
catch the id in your controlRecipe function
const controlRecipe = async ()=>{
//jq
const id = $(window)..location.hash.replace('#','');
//js
const id = window.location.hash.replace('#','');
if(id){
//console.log(id);
state.recipe = new Recipe(id);
try {
await state.recipe.getRecipe();
state.recipe.calcTime();
state.recipe.calcServings();
console.log(state.recipe);
} catch (error) {
alert(error);
}
}
}

Categories