script not loading after navigate from one page to another page nunjucks - javascript

i am creating website using nunjucks and express, its king of blog website and content coming from prismic. i want to load one script file for active campane form when user navigate from blog list page to any blog detail page, after navigate to detail page. will get script URL from prismic and I want to execute that script in HTML file.
its working while refresh the detail page but its not working when navigate from one page to another pages.
here is some sample code of my website
---
layout: _layout.njk
permalink: "/{{ post.blogType }}/{{ post.uid }}/"
pagination:
alias: post
data: posts
size: 1
addAllPagesToCollections: true
---
{% set params = item.primary.sumo_form_id.split("=") %}
<div class="_form_{{params[1]}}">
</div>
<script src="{{item.primary.sumo_form_id}}" type="text/javascript" charset="utf-8" defer>
</script>

After spent so much time i have found the solution. it is not proper solution but it is working right now.
Page where you are using recapcha. (njk file)
<div
id="recaptcha"
data-callback="recaptchaOnload"
data-sitekey="SITE_KEY"
data-size="invisible"
class="g-recaptcha">
</div>
index.njk
<head>
<script>
setInterval(()=>{
recaptchaOnload(); // function calls every 20 Seconds.
}, 20000)
function recaptchaOnload() {
try {
if (document.getElementsByClassName("g-recaptcha").length > 0) {
// Whenever route changes this function is going to check for id="g-recaptcha".
// if its found recapcha code renders
grecaptcha.render("recaptcha", {
sitekey: "SITE_KEY",
callback: function () {
console.log("recaptcha callback");
},
});
}
} catch (e) {
return;
}
}
</script>
<script src='https://www.google.com/recaptcha/api.js?onload=recaptchaOnload&render=explicit' async defer>
</head>
Q - Why i have to use this functionality ?
A - nunjucks are server side templates. so once they are initialised in front-end and if we have added scripts in other than parent route it is not going to initialised, if we changed to new page without redirect(page refresh). So in such conditions this is going to useful

Related

Javascript - ajax refreshing a div with an old version of an updated file

I am making a web dashboard and for this I have a javascript function that loops infinitely, updating a particular div at frequent intervals. (it uses ajax/jquery to do this).
I have used a loop with setTimeout:
<!doctype html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
function updateMain() {
setTimeout(function() {
console.log("updating");
$('#main').load('new-content.php #main', function() {});
updateMain();
}, 3000)
}
updateMain();
</script>
</head>
<body>
<div id="main">
<p>hi there</p>
</div>
</body>
</html>
'new-content.php' is a file that is constantly updated by another part of my program, to show the new content for the dashboard.
it looks something like this:
<div id="main">
<p>Hello i am updated content</p>
</div>
I am sure the loop is working as the "updating" messages appear at regular intervals in the console.
When the program starts, the div is showing "hello there", and in the new-content.php file it has "hello am updated content".
The first time the loop runs, it updates the div to show "hello i am updated content".
But if I further update the new-content.php file, for example to say "hello I am further updated content", it just won't show on my webpage. However I am sure that the loop is still running as the messages appear in console.
It's like ajax has some cached version of the new-content.php file that it loads at the start then keeps using forever.
I am very confused, if you could help me I would be very grateful
Thank you
PS: if it is of relevance, the website is running through flask but I don't think this is the problem.
EDIT: I believe it is actually a flask caching issue
You can try adding a cache buster to see if that helps. Change your code as follows:
function updateMain() {
setTimeout(function() {
console.log("updating");
const cb = new Date().getTime();
$('#main').load('new-content.php?cb=' + cb + '#main',function() {
updateMain();
});
}, 3000)
}
updateMain();
Wasn't able to solve the issue but for anyone who is trying to make a similar project, I decided to use flask-socketio instead which allows me to send data to javascript to be shown on the page, instead of javascript loading the data itself from a file. (the answer by vladtn on this SO post was useful as an introduction to socketio)

Loading a html script from a typescript file

Im am currenlty working on a integration of a nps widget within a Chatbot. I cannot show you all the code, but i imported the html file inside the chat.ts file. I want to call the entire html file after a button press from the chatbot. I have tried a lot, but nothing seems to help.
this is the chat.ts code (small part of it)
private showAskNicely() {
// #ts-ignore
window.location.assign('npshtml.html');
}
private askNicelyButton() {
const el = document.getElementById('detractbut');
el.addEventListener('click', this.showAskNicely);
}
this is the npshtml file
<html>
<body id="try">
<p>
AskNicely Web Survey Popup Example for traditional websites.<br>
Running in 'force' mode.<br>
Responses will be recorded.
</p>
<script type="text/javascript" src="https://static.asknice.ly/dist/standalone/asknicely-in-app-conversation.js"></script>
<link href="https://static.asknice.ly/dist/standalone/asknicely-in-app-conversation.css" rel="stylesheet" type="text/css" charset="utf-8">
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
askNicelyConversation({
config: {
--- cannot show this part ---
},
customData: {
a_custom_property: 'business', // Optional - Send extra data about this customer for reporting and leaderboards
another_custom_property: 'New York' // Optional - Send extra data about this customer for reporting and leaderboards
}
});
});
</script>
</body>
</html>
I also have the button rendered inside another html file with css, but that all works fine.
I have it currently on windows.location.assign, so that it opens a new page. It would be ideal if the script could be triggered without opening a new page.
Using jquery.load does not work and does not give me a error of some sort.

Refresh using Page.js gives 404 Not Found

I have just started using page.js, a routing library that I intend to use to make a single page application with handlebars. I will use the routes to call different handlebar templates. So far, this functionality is working and is as quick as I had hoped.
I am currently encountering an issue where refreshing the page (pressing F5) or copying the URL, and pasting it into a new tab gives me a 404 not found error. It is not calling the not found page that I created in my app.
The code below is a copy of: https://github.com/visionmedia/page.js/tree/master/examples/notfound
<!DOCTYPE html>
<html>
<head>
<title>Not Found</title>
<script src="/page.js"></script>
</head>
<body>
<h1>Not Found</h1>
<p></p>
<ul>
<li>/</li>
<li>/about</li>
<li>/contact</li>
<li>/not-found</li>
</ul>
<script>
page.base('/notfound');
page('/', index);
page('/about', about);
page('/contact', contact);
page('*', notfound);
page();
function index() {
document.querySelector('p')
.textContent = 'viewing index';
}
function about() {
document.querySelector('p')
.textContent = 'viewing about';
}
function contact() {
document.querySelector('p')
.textContent = 'viewing contact';
}
function notfound() {
document.querySelector('p')
.textContent = 'not found';
}
</script>
</body>
When I refresh this page, I am presented with my localhost's 404 page. I get the same result when I use the link http://127.0.0.1/notfound/about.
My question is this: does page.js support refreshing the browser, or using links to access specific portions of my application?
It seems that the question I should really be asking is this: Would it be possible for the web server to redirect all navigation to the page that loads the application? The answer is Yes.
It seems that refreshing the browser would be a common case. An acceptable solution to this would also be to catch any refresh attempts, and redirect them to the main page. Using links to access specific portions of my application is not as crucial, but would be a nice touch.

Loading content only

I am using a $_GET function to load content into the website,
what I want to do is add a Loading image into all that mess.
Right now it looks like it opens a whole new page.
Code:
<?php
if (isset($_GET['page']) || isset($_POST['page'])) {
$page = trim(isset($_POST['page']) ? $_POST['page'] : $_GET['page']);
if (preg_match("/a-z/", $page)) {
}
} else {
$page = "index";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example</title>
</head>
<body>
<div id="navigation">
<ul class="nav-items">
<li>Home</li>
<li>Test</li>
<li>Beta</li>
</ul>
</div>
<div id="content">
<?
if ($page != '')
include('pages/'.$page . '.php');
else
{
include('pages/error.php');
}
?>
</div>
</body>
</html>
Now, it works perfectly but I'd want it to show a Loading... image while loading the content , and instead of reloading whole page would be great to load the content div ONLY.
I did not try javascript solution since I didn't find anything that would work correctly and would keep the links working (for example http://example.com/index.php?page=test with already loaded the text.php file from pages folder). Plus I'm a real newbie in javascript so I have no idea what to start with.
The only solution to this problem is with JavaScript because PHP will only execute on the server and will only present HTML on the client side.
If you understand the HTTP request/response system, you will know that a request is sent to the server and then the server responds back with the page content, which will be the HTML (and CSS and any client-side scripts such as JavaScript). This method normally means having to reload the page but if you use AJAX (Asynchronous JavaScript and XML), this acts as a layer between the client and the server, allowing the user to request content without having to reload the page.
The most simple way of doing this is with jQuery. Be sure to include the jQuery library and put your code inside the $(document).ready(); function so that it executes when the page has finished loading.
Fortunately, this particular task is fairly simple, although it will require restructuring your website/application slightly. You will need to have the content echoed or printed onto a different page with PHP.
On your main page that will be used and seen by the users, you would simply write $("#container").load("page.html"); where container is the id of the container you want to load the content into.
If you want different content to be loaded with different buttons, you could do this (as long as you give your links the correct ids:
$(document).ready(function() {
$("#alpha").onclick(function() {
$("#container").load('page.html?page=alpha');
});
$("#beta").onclick(function() {
$("#container").load('page.html?page=beta');
});
});
Edit: I'm so sorry, I missed out the important part about the loading image, but the other answer demonstrates this well, so there is no point in repeating it.
It looks like it is opening a whole new page because it is. Your only option would be javascript. If I were wanting to do this, I would always only load the index page with nothing in your content div except the loading icon. Then once the page is loaded have jquery read the get variable and make an ajax request for the content of the page and load it into the div.
<div id="content">
<div id='page'></div>
</div>
Then, to make it easier on you since you are unfamiliar with javascript I would include the following jquery plugin: https://github.com/allmarkedup/purl
then in .js file:
$( document ).ready(function() {
var loading_annimation = "<div class='loading'></div>";
var page = $.url().param("page");
if(page){
$('#page').load(loading_annimation ).load('/special_php_file_that_includes_JUST_content.php?page='+page);
} else {
$('#page').load(loading_annimation ).load('/special_php_file_that_includes_JUST_content.php?page=index');
}
$(document).on('click','.link', function(e){
e.preventDefault();
var page = $(this).attr("data-link");
$('#page').load(loading_annimation ).load('/special_php_file_that_includes_JUST_content.php?page='+page);
});
});
Then you will need to change your links to do something like this:
<a class='link' data-link='beta' href="/index.php?page=beta">Beta</a>

Perform a function based on the hash with director.js

I am trying to use director.js for the routing on my single page application. The issue is when you go to a page by typing it into the address bar the application does not perform the function that the hash in the routing table is pointed to.
Here is the example on github - If I refresh the page with a hash or direct to a page with a hash nothing shows up in the console. But if I click on one of the links console output is shown. How can I change this code so that if a user directly goes to a link the routing table checks the hash and performs it's matching function from the routing table? Please answer with a methodology that utilizes director.js
<html>
<head>
<meta charset="utf-8">
<title>A Gentle Introduction</title>
<script src="https://raw.github.com/flatiron/director/master/build/director.min.js"></script>
<script>
var author = function () { console.log("author"); },
books = function () { console.log("books"); },
viewBook = function(bookId) { console.log("viewBook: bookId is populated: " + bookId); };
var routes = {
'/author': author,
'/books': [books, function() { console.log("An inline route handler."); }],
'/books/view/:bookId': viewBook
};
var router = Router(routes);
router.init();
</script>
</head>
<body>
<ul>
<li>#/author</li>
<li>#/books</li>
<li>#/books/view/1</li>
</ul>
</body>
</html>
I have not used Director but your issue may be the fact that GitHub serves the "raw" files with a mime type of "text/plain". So the Director js code might not be processed as javascript, causing your test page not to work. Try downloading your own copy of Director and link to the local version instead of the one on GitHub.

Categories