How to send from JS to Python Django Server Backend - javascript

I have started learning about Javascript and I am trying to include it to my Django Project to calculate the time users are on the page so I found the answer to this question HERE but I am unable to implement it as it is the first time for me to link between JS and Django Python backend.
Here is what I understand:
Step 1 Add the following script for all HTML templates:
<script src="timeme.js"></script>
<script type="text/javascript">
TimeMe.setIdleDurationInSeconds(15);
TimeMe.setCurrentPageName("my-home-page");
TimeMe.initialize();
window.onload = function(){
setInterval(function(){
var timeSpentOnPage = TimeMe.getTimeOnCurrentPageInSeconds();
document.getElementById('timeInSeconds').textContent = timeSpentOnPage.toFixed(2);
}, 25);
}
</script>
Step 2 I am not sure exactly to place the below code to send the data to the backend to be read in Django Admin to know which user has been spending on each page
xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","ENTER_URL_HERE",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var timeSpentOnPage = TimeMe.getTimeOnCurrentPageInSeconds();
xmlhttp.send(timeSpentOnPage);
My questions are:
Where should I place the 2nd Code?
Should I start a new app in my django project to read the file sent from the JS?
What is the TimeMe.setCurrentPageName("my-home-page"); what variable should I add? is it the HTML name of the name in the URL?
Are there an easier way to track how long a user has been in a page?

Related

How might you create new subpages when api (json) changes?

I want to use data from the api from Mixcloud (audio hosting service like soundcloud) such that a new subpage(is it called deeplink?) is created when a new post is posted to Mixcloud.
My project is a website for a podcast. I am imagining the index.html featuring every podcast episode in a list, with subpages each dedicated to a single episode. mockup
I'm very new to web development so please bear with me. I would therefore love references/material to read.
I have figured out how to get data from the JSON api parse it into Javascript strings and change the innerHTML of elements in the index.html.
I'm having difficulty understanding how you might go about generating the new subpages whenever a new post is posted to Mixcloud.
I'm also having difficulty searching for the right material to read about this, probably because I don't know the right words and terms to search for.
Here's a snippet of my code so far. And the API / JSON file that I'm using.
<div class="episode">
<div class="episode-title">Loading episode...</div>
</div>
<div class="episode">
<div class="episode-title">Loading episode...</div>
</div>
<div class="episode">
<div class="episode-title">Loading episode...</div>
</div>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//parse JSON to javascript objects
var response = JSON.parse(xhttp.responseText);
//array of the first 3 podcast episodes
var episodes = document.getElementsByClassName("episode");
//array of the first 3 podcast episode titles
var episodeTitles = document.getElementsByClassName("episode-title");
//loop to update innerHTML
for(var i = 0; i < episodes.length; i++) {
var episodeTitle = response.data[i].name;
episodeTitles[i].innerHTML = episodeTitle;
}
}
};
xhttp.open("GET", "https://api.mixcloud.com/radiomodem/cloudcasts/", true);
xhttp.send();
It seems like you are expecting to be able to create a hierarchical structure of pages with client side code. I suggest starting some reading around client vs server. This link being the first google search result.
If you plan on doing this in javascript as client side code, the pages you create will not physically exist. You would be creating a Single Page Application that references resources that look like pages but are only stored in memory. Delivery of those pages would be made through a client side router, without a web request to a server resource being made. With a Single Page Application approach, you would not be able to present the same cached version of a Mixcloud post to multiple users; the in-memory pages you create would only exist in an individual users browser.
You need to split your code into separate server and client code bases for this to work properly.
Your server would make the requests to https://api.mixcloud.com/radiomodem/cloudcasts/ and create a new physical subpage file for each child page. Your home page could read the contents of the subpage directory and present these as navigateable choices.
On the client side all you have is html.
If you want to stick with only learning 1 language I suggest using Node with Express. This would allow you to run JavaScript on the server.

Creating API service to load processed data with html on an external website (require logic)

Need to figure out how chat providers like tawk.to or zopim works.
These site give you a small js code like this:
var Tawk_API = Tawk_API || {},
Tawk_LoadStart = new Date();
(function() {
var s1 = document.createElement("script"),
s0 = document.getElementsByTagName("script")[0];
s1.async = true;
s1.src = 'https://embed.tawk.to/5b1a548e10b99c7b36d4bf04/default';
s1.charset = 'UTF-8';
s1.setAttribute('crossorigin', '*');
s0.parentNode.insertBefore(s1, s0);
})();
And you are supposed to place the code on your website and the chat is loaded.
Suppose I have created a chatbot where when you send Hi it sends back Hello
And, I have created a Restful API like this:
domain.com/query?token=11223344&message=hi
I can definitely execute the URL with an ajax call on any of my page.
BUT, how can I create an Service API for this?
Best case scenario is where I provide a small js code with a token to anyone and they place the code on their website and the html is parsed.
It should also be able to perform the example functionality (say Hi get Hello)
Is there any framework which helps to achieve this functionality out of the box?
Note: Currently using Laravel as the Backend.

Request plain text file in javascript from URL?

I started a blog recently and coded it by hand. It is a static, CSS/HTML5 website. Upon sharing it with friends, I realized that when I would update it via FTP, it would be cached already by their browsers. I decided that I would keep all of my blog posts on new pages and then create a landing page that would somehow determine the newest post and forward users there after they clicked an enter button or something like that.
I was able to create a button that could forward them to a specific link, but I want to create a script that will always forward them to the newest page. So I created a file called 'getLatest.json' and uploaded it to an 'api' subfolder of my site. I then tried to use an XMLHttpRequest to load it:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
window.location = "http://latestBlogPost.com" +
xhttp.responseText.today;
//Today is a parent in the object returned.
}
};
xhttp.open("POST", "http://myWebsite.com/api/getLatest.json", true);
xhttp.send();
}
But that didn't work. The response was a null string. I tried using jquery to no avail.
I tried uploading a file called getLatest.html which contained the url in plaintext. That didn't work either.
tl;dr: Is there some way that I can get plaintext from a URL's html content?
edit: getLatest.json and getLatest.html contain a link to the newest blog post.
There are couple of ways to do this.
First your code is not working because you are using a "POST" it should be "GET", if you do that it will work.
Second easiest way is to create a java script file with variable declared and reference that file to your website
<script type="text/javascript" src="http://your javascript file"> </script>
This file contains your variable like this
var latestBlog = "http://....";
in your code use this variable. No more code required. but as i mentioned earlier if you change your HTTP Verb to get your code will work

marquee: fetch text from txt file hosted on cloud drive

I'm searching for an easy way to update a simple marquee on an HTML5 web page (e.g. displaying "we're on vacation from...") not via hard coding on the page itself but via an external txt file to be read. The thing is the text file should be hosted on a common cloud drive like Google drive or OneDrive. I make the file publicly available and include the public link to the txt file in the website code. Then I should be able to adapt the txt file in the cloud drive and see my edits in the marquee on the page.
Please support. Do you have other, better ideas? thx
<html>
<script type="text/javascript">
window.setInterval(function(){
ajaxCallFunction(); //calling every 5 seconds
}, 5000);
function ajaxCallFunction(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("textDisplay").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "YOUR TEXT DOCUMENT HERE", true);
xhttp.setRequestHeader("Pragma","no-cache");
xhttp.setRequestHeader("Cache-Control","no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
xhttp.setRequestHeader("Expires",0);
xhttp.setRequestHeader("Last-Modified", new Date(0));
xhttp.setRequestHeader("If-Modified-Since", new Date(0));
xhttp.send();
}
</script>
<marquee id="textDisplay"></marquee>
</html>
This will use ajax to pull the contents of your text file from wherever you have stored it, just use the share link from the cloud service you are using. It will update the text every 5 seconds.
EDIT
Ok, I've taken a look at your plunker and run the code in a browser. The error being returned in the console seems to indicate that the page you are requesting info from is redirecting you:
I'm not sure where to go from here, but I'll carry on looking none the less.

reading data from file and displaying on browser

I am new to javascript (mostly work on backend) but now I want to create a visualization and want to use javascript for it.
I have data saved in a file in format
id1 uid1 rating
id1 uid2 rating2
Just to get started, I want to read data from this file and display it on my browser?
Do I need to start server.. or can i do it just like that.
Any suggestions/directions will be appreciated.
THanks
you need to learn about ajax,and deal with browser differences. A way that would work on firefox and chrome would be :
<body>
<div id="log"></div>
<script type="text/javascript">
var request = new XMLHttpRequest();//depends on the browser , several ways to create the object
request.onreadystatechange = function(e){
if(request.readyState == 4 && request.status==200){
// do whatever you need with the data
document.getElementById("log").innerText = request.responseText;
}
}
// assuming the file is called data and is located on current-path-on-server/data
request.open("GET","data",true);
request.send();
</script>
</body>
more about it :
https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started

Categories

Resources