use Ajax and JavaScript to create dynamic links from the results - javascript

HTML contains two div make different ajax calls to both the divs,where div1 is the result of html form and div2 should be the result of onclick on div1
html
<html lang="en">
<head>
<title>Display Movie Information</title>
<meta charset="utf-8"/>
<script type="text/javascript" src="movies.js"></script>
</head>
<body onload="initialize();">
<tr><td>
<form>
<label>Movie title: <input type="text" id="form-input"/></label>
<input type="button" onclick="sendRequest();" value="Display Info"/>
</form>
<div id="output"> </div></td>
<td><div id="right_panel">Display Dynamic results here</div></td>
</body>
</html>
I have a movies.js file which using ajax gets the result
function initialize () {
}
function sendRequest () {
var xhr = new XMLHttpRequest();
var query = encodeURI(document.getElementById("form-input").value);
xhr.open("GET", "proxy.php?method=/3/search/movie&query=" + query);
xhr.setRequestHeader("Accept","application/json");
xhr.onreadystatechange = function () {
if (this.readyState == 4) {
var json = JSON.parse(this.responseText);
var str = JSON.stringify(json,undefined,2);
//customized code
console.log(json.results.length);
var i=0;
var movie_title,release_date;
var movies = new Array();
while(i<json.results.length)
{
movie_title = json.results[i].title;
release_date = json.results[i].release_date;
movies[i] = "<li>"+movie_title+"<br/>"+release_date+"<br/></li>";
i++;
}
document.getElementById("output").innerHTML = "<ul>" + movies + " </ul>";
}
};
var movie_detail = new XMLHttpRequest();
var movie_credit = new XMLHttpRequest();
xhr.send(null);
}
This code displays the title and the release date of the movies(result of onclick on the button)
Q: I want to make the movie title an hyperlink that could make a call like www.imdb.com/(movie_title) and display the result in the second div tag named "right_panel" using only ajax and javascript and no jquery.

Related

Updating a variable using Ajax

I'm not familiar with Ajax so I'm learning fast. I'd appreciate some help on displaying a variable
rdm = urandom.randint(10,100) //comes from a loop in micropython.
Here's what I've so far. The part of turning ON/OFF a LED is working. I just cannot get the variable to update every 2 seconds.
TIA
<html>
<head>
<title>ESP32-OLED
</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.js" type="text/javascript">
</script>
</head>
<body>
<div>
<h4>The ESP32 Update web page without refresh
</h4>
<br>
<p>LED State:
<strong>%s
</strong>
</p>
<p>RDM number:
<span id="rdm">0
</span>
</p>
<p>
<button onclick="window.location.href = '/?led=on'">ON
</button>
</p>
<p>
<button onclick="window.location.href = '/?led=off'">OFF
</button>
</p>
<br>
<a href="http://www.google.com">www.google.com
</a>
</div>
<script>
var txt = "jQuery Works";
var _rdm = rdm;
//wait for the page to fully load
//$(document).ready(function(){
// var txt = "jQuery Works";
// alert(txt)
//}
//);
setInterval(function() {
// Call a function repetatively with 2 Second interval
getData();
}, 2000);
//2000mSeconds update rate
function getData() {
var xhttp = new XMLHttpRequest();
var rdm = document.getElementById("rdm").value;
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//returns 4 when the server finishes streaming the response
document.getElementById("rdm").innerHTML = _rdm;
//return object whose id property matches the specified string
}
};
xhttp.send();
}
</script>
</body>
</html>```
<!DOCTYPE html>
<html>
<head>
<title>ESP32-OLED
</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.js" type="text/javascript">
</script>
</head>
<body>
<div>
<h4>The ESP32 Update web page without refresh
</h4>
<br>
<p>LED State:
<strong>OFF
</strong>
</p>
<p>RDM number:
<span id="rdm">0
</span>
</p>
<p>
<button onclick="window.location.href = '/?led=on'">ON
</button>
</p>
<p>
<button onclick="window.location.href = '/?led=off'">OFF
</button>
</p>
<br>
<a href="http://www.google.com">www.google.com
</a>
</div>
<script>
var asyncGetData = new Promise(getData)
asyncGetData.then(() => {
setTimeout(asyncGetData, 2000)
})
function getData(resolve) {
var xhttp = new XMLHttpRequest();
var rdm = document.getElementById("rdm").value;
alert("Test 123!!");
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//returns 4 when the server finishes streaming the response
document.getElementById("rdm").innerHTML = rdm;
resolve();
//return object whose id property matches the specified string
}
};
xhttp.send();
}
</script>
</body>
</html>
You should resolve xhr before calling interval/timeout, also you need to call method open
var asyncGetData = new Promise(getData)
function run () {
asyncGetData.then(d => {
console.log(d)
setTimeout(run, 2000)
})
}
run()
function getData(resolve) {
var xhttp = new XMLHttpRequest();
// var rdm = document.getElementById("rdm").value;
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//returns 4 when the server finishes streaming the response
document.getElementById("rdm").innerHTML = JSON.stringify(JSON.parse(this.responseText), false, 2);
resolve(this.responseText);
//return object whose id property matches the specified string
}
};
// you need to call open with the method an the api url
xhttp.open('GET', 'https://api.github.com/users/octocat')
xhttp.send();
}
<pre id="rdm"></pre>

Detecting a click after a new element is loaded after the DOM

I am trying to create a simple Chrome Plugin - however I have come to an issue.
I am trying to detect a click on a div using a simple getElementById - however as the api call happens after the DOM is loaded the JS cannot 'find' any div's and gives an error and doesn't do anything after I click on the element.
How do I detect the click, after the data from the API has loaded? I have included some of my code below:
Thanks
document.addEventListener('DOMContentLoaded', function () {
var checkPageButton = document.getElementById('checkPage');
checkPageButton.addEventListener('click', function () {
inputBox = document.getElementById("postcodeInput").value
console.log(inputBox)
let xml = new XMLHttpRequest();
xml.open('get', "https://api.getaddress.io/find/" + inputBox + "/?api-key=SECRET&expand=true", false);
xml.send(null);
var data = xml
var arr = xml.responseText
var data = JSON.parse(arr)
var postcode = data.postcode
var addresses = data.addresses
console.log(addresses)
document.getElementById("postcode").innerHTML = postcode;
var text = "";
var i;
for (i = 0; i < addresses.length; i++) {
text += "<div id='addressClick' name=" + i + ">" + addresses[i].line_1 + "</div>" + "<br>";
}
document.getElementById("data").innerHTML = text;
clickFunc()
}, false);
}, false);
function clickFunc() {
var rowBox = document.getElementById("addressClick");
rowBox.addEventListener('click', function () {
console.log('asd');
}, true);
}
HTML
<!doctype html>
<html>
<head>
<title>Address Search</title>
<script src="popup.js"></script>
</head>
<body>
<h3>Address Search</h3>
<input type="text" id='postcodeInput' name="postcodeInput" value="KW1 4YT">
<button id="checkPage">Search</button>
<div class='results'>
<h3>Results - <span id='postcode'></span></h3>
<p id='data'></p>
</div>
</body>
</html>
<style>
body {
width: 200px
}
#addressClick:hover {
color: blue;
cursor: pointer
}
</style>
You can attach an EventListener to all the body and, at every click, detect if the clicked element is the desired one:
document.body.addEventListener('click', event => window.alert(event.target.innerText));
This can sound like an aggressive solution, but it's way less invasive than a MutationObserver

I am able to load text data into a javascript array in .js file but not inside html

I need to load the text file data into a javascript array and define a dynamic form using html.
I tried below code for extracting data from text file and to store in a javascript array and it works as long as it is in .js file
var fs = require('fs');
var textByLine = fs.readFileSync('123.txt').toString().split("\n");
console.log(textByLine);
but when I embed it inside my html file this doesn't work.
below is my html code. for now I am just forming an array with months but i need to replace it with array taken from the text file.
<html>
<head>
<title></title>
<META NAME="DESCRIPTION" CONTENT="">
<META NAME="KEYWORDS" CONTENT="">
<script language="javascript">
var dt=new Date();
var dt_month=dt.getMonth() +1;
//alert(dt_month);
function addOption(selectbox,text,value )
{
var optn = document.createElement("OPTION");
optn.text = text;
optn.value = value;
selectbox.options.add(optn);
}
function addOption_list(){
var month = new Array("January","February","March","April","May","June","July","August",
"September","October","November","December");
for (var i=0; i < month.length;++i){
addOption(document.drop_list.Month_list, month[i], month[i]);
document.drop_list.Month_list.options[i].selected=true;
}
}
</script>
</head>
<body onLoad="addOption_list()";>
You can see the view-> Source of this page.
<br><br>
<FORM name="drop_list" action="yourpage.php" method="POST" >
<SELECT NAME="Month_list">
<Option value="" >Month list</option>
</SELECT>
</form>
</body>
</html>
I gave the 3 line code which is working independently as a .js file inside addOption_list function in above code and it doesn't work. Appreciate help on this.
Thanks in advance
The FileSytem (fs) module is for NodeJS applications so needs to be in .js file. If you want to load the file into your html you can use Ajax instead. This may work:
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this.responseText);
}
};
xhttp.open("GET", "123.txt", true);
xhttp.send();
}
function myFunction(data) {
var textByLine = data.split("\n");
console.log(textByLine);
}
loadDoc();
</script>

Switch Images Based on external text file content

I'm trying read a text file and based on the contents of that text file, change the image on a webpage. I tried using the console log to get error messages back, however I'm not getting errors. The contents of the txt file is literally the name of the images I want to show. Below is my javascript and html code.
<!DOCTYPE html>
<html>
<meta charset="utf-8"/>
<script type="text/javascript">
window.onload = function(){
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "../HTML/Images/Bowl.txt", true);
console.log(txtFile);
txtFile.onreadystatechange = function() {
allText = txtFile.responseText;
lines = txtFile.responseText.split("\n"); // Will separate each line into an array
if (lines === 'GDogbowl.png'){
document.getElementById('myImage').src='../HTML/Images/GDogbowl.png'
}
else if (lines === 'YDogbowl.png') {
document.getElementById('myImage').src='../HTML/Images/YDogbowl.png'
}
else {
document.getElementById('myImage').src='../HTML/Images/RDogbowl.png'
}
}
}
</script>
<body>
<table class="centerTable" >
<tr>
<td>
<div class="imgContainer">
<div>
<img id="fullsize" />
<ul id="thumbs">
<img id="myImage" src= "../HTML/Images/RDogbowl.png" style="width:100px">
</ul>
</div>
<div class="imgButton">
<button id="Bowl" >Toggle Color</button>
</div>
</div>
</td>
</table>
</body>
You can't magicly pull data out of an array as if it were a string. To solve the issue, you'll have to loop through the array after you've split the lines. Something like this:
var xhr = new XMLHttpRequest();
var data = null;
xhr.open("GET", "../HTML/Images/Bowl.txt", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
data = xhr.responseText.split('\n');
for(var i=0; i<data.length; i++){
document.getElementById('myImage').src='../HTML/Images/'+data;
}
}
};
xhr.send();
You need to check for txtFile.readyState == 4 and txtFile.status == 200 in your readystatechange handler, and you also need to do txtFile.send().
You also need to reference each URL in the lines array separately. Here's an example with two ways to show the images:
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "../HTML/Images/Bowl.txt", true);
console.log(txtFile);
txtFile.onreadystatechange = function() {
if (txtFile.readyState == 4 && txtFile.status == 200) {
allText = txtFile.responseText;
lines = txtFile.responseText.split("\n"); // Will separate each line into an array
if (lines[0] === 'GDogbowl.png'){
document.getElementById('myImage').src='../HTML/Images/GDogbowl.png'
}
else if (lines[0] === 'YDogbowl.png') {
document.getElementById('myImage').src='../HTML/Images/YDogbowl.png'
}
else {
document.getElementById('myImage').src='../HTML/Images/RDogbowl.png'
}
// if you have several images, you need several image elements:
lines.forEach(function(imgUrl, i) {
var image = document.createElement("img");
img.src = imgUrl;
img.id = "myImage_" + i;
document.body.appendChild(img);
});
}
}
txtFile.send();
split returns an array, where each element contains a line. So use, lines[0] to access the first element, lines[1] to access the second and so on.
If you don't care about handling state changes of your xmlHTTPRequest, then you can use the onload event, rather than onstatechange. ( I think all modern browsers should support this by now)
And as others have alluded in their answers, if you only care about the first line item, and you are sure that the name in the file is always valid, then you can concatenate the strings to achieve your goal without all the if/else cases.
<!DOCTYPE html>
<html>
<meta charset="utf-8"/>
<script type="text/javascript">
window.onload = function(){
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "../HTML/Images/Bowl.txt", true);
console.log(txtFile);
txtFile.onload = function() {
allText = txtFile.responseText;
lines = txtFile.responseText.split("\n"); // Will separate each line into an array
document.getElementById('myImage').src="../HTML/Images/"+lines[0];
</script>
<body>
<table class="centerTable" >
<tr>
<td>
<div class="imgContainer">
<div>
<img id="fullsize" />
<ul id="thumbs">
<img id="myImage" src="../HTML/Images/RDogbowl.png" style="width:100px">
</ul>
</div>
<div class="imgButton">
<button id="Bowl" >Toggle Color</button>
</div>
</div>
</td>
</table>
</body>

Javascript does not work upon AJAX call

I have a page which does an AJAX call and loads an entire page. The page that gets loaded has some Javascript. The javascript works on page by itself when loaded, but when its gets loaded by AJAX, the Javascript does not work. I dont know what I am missing.
The code of the loaded page
<html>
<script type="text/javascript">
function showfield(name){
if(name=='lstbox')document.getElementById('div1').style.display="block";
else document.getElementById('div1').style.display="none";
}
function hidefield() {
document.getElementById('div1').style.display='none';
}
</script>
<head>
</head>
<body onload="hidefield()">
<form action = "test2.php" method = "post">
Please enter a name for the App <input type = "text" name = "name">
<table border = "1"><tr><th>Choose a Label</th><th>Choose an element</th></tr>
<tr><td><input type = "text" name = "label1" /></td> <td>
<select name = "elementtype1" id="elementtype1" onchange="showfield(this.options[this.selectedIndex].value)">
<option value = 'select'> Select </option>
<option value='txtbox'>Text Box</option>
<option value='lstbox'>List Box</option>
<option value='chkbox'>Check Box</option>
<option value='radio'>Radio Button</option>
</select></td><td><div id="div1">Enter Listbox options: <input type="text" name="whatever1" /></div></td></tr>
</table>
<input type = "submit" value = "Submit">
</form>
</body>
</html>
The code of the loading(AJAX) page is
<html>
<head>
</head>
<body>
<script src="ajax.js" type="text/javascript"></script>
<script src="responseHTML.js" type="text/javascript"></script>
<div id="storage" style="display:none;">
</div>
<div id="displayed">
<FORM name="ajax" method="POST" action="">
<p>
<INPUT type="BUTTON" value="Get the Panel" ONCLICK="loadWholePage('appcreator.php')">
</p>
</FORM>
</div>
</body>
</html>
The ajax.js code
function createXHR()
{
var request = false;
try {
request = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (err2) {
try {
request = new ActiveXObject('Microsoft.XMLHTTP');
}
catch (err3) {
try {
request = new XMLHttpRequest();
}
catch (err1)
{
request = false;
}
}
}
return request;
}
The responseHTML.js code
function getBody(content)
{
test = content.toLowerCase(); // to eliminate case sensitivity
var x = test.indexOf("<body");
if(x == -1) return "";
x = test.indexOf(">", x);
if(x == -1) return "";
var y = test.lastIndexOf("</body>");
if(y == -1) y = test.lastIndexOf("</html>");
if(y == -1) y = content.length; // If no HTML then just grab everything till end
return content.slice(x + 1, y);
}
/**
Loads a HTML page
Put the content of the body tag into the current page.
Arguments:
url of the other HTML page to load
id of the tag that has to hold the content
*/
function loadHTML(url, fun, storage, param)
{
var xhr = createXHR();
xhr.onreadystatechange=function()
{
if(xhr.readyState == 4)
{
//if(xhr.status == 200)
{
storage.innerHTML = getBody(xhr.responseText);
fun(storage, param);
}
}
};
xhr.open("GET", url , true);
xhr.send(null);
}
/**
Callback
Assign directly a tag
*/
function processHTML(temp, target)
{
target.innerHTML = temp.innerHTML;
}
function loadWholePage(url)
{
var y = document.getElementById("storage");
var x = document.getElementById("displayed");
loadHTML(url, processHTML, x, y);
}
/**
Create responseHTML
for acces by DOM's methods
*/
function processByDOM(responseHTML, target)
{
target.innerHTML = "Extracted by id:<br />";
// does not work with Chrome/Safari
//var message = responseHTML.getElementsByTagName("div").namedItem("two").innerHTML;
var message = responseHTML.getElementsByTagName("div").item(1).innerHTML;
target.innerHTML += message;
target.innerHTML += "<br />Extracted by name:<br />";
message = responseHTML.getElementsByTagName("form").item(0);
target.innerHTML += message.dyn.value;
}
function accessByDOM(url)
{
//var responseHTML = document.createElement("body"); // Bad for opera
var responseHTML = document.getElementById("storage");
var y = document.getElementById("displayed");
loadHTML(url, processByDOM, responseHTML, y);
}
Javascript loaded in HTML through AJAX will not be executed.
If you want to include scripts dynamically, append <script> tags to the existing loaded page's <head> element.
execute the script with jquery rather than with innerHTML
//this is not working!
document.getElementById("chart-content").innerHTML = this.responseText;
//try this
$("#chart-content").html(this.responseText);
The script is outside the body tag, and the loader picks out only the code inside the body tag, so the script is not even part of what you add to the page.
Loading you Js within the <head> should work. use this.
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', loadJs);
} else {
loadJs();
}
function loadJs() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '/assets/script/editor-controlls.js';
script.defer = true
document.getElementsByTagName('head')[0].appendChild(script);
}

Categories