I am using the following script to read the information from an html request.
function runSearch(searchid, fullMovie) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
var fullMovie = JSON.parse(xhr.responseText);
var movie = { title: fullMovie.Title, runtime: fullMovie.Runtime, plot: fullMovie.Plot };
document.getElementById('Title').innerText = movie.title;
document.getElementById('Runtime').innerText = movie.runtime;
document.getElementById('Plot').innerText = movie.plot
}
};
xhr.open('GET', 'http://www.omdbapi.com/?i=' +searchid+ '&plot=short&r=json', true);
xhr.send(null);
}
How can I do to change the searchid from the xhr.open to use the id="searchid" from a div tag?
<div>
<div id="tt0110912">
<h1 id="Title">Title from tt00110912</h1>
<p id="Runtime">Runtime from id</p>
<p id="Plot">Plot from id</p>
</div>
</div>
<br>
<div>
<div id="tt3322364">
<h1 id="Title">Title from tt3322364</h1>
<p id="Runtime">Runtime from id</p>
<p id="Plot">Plot from id`enter code here`</p>
</div>
</div>
Is it possible to run this script several times with different xhr requests? How can i do this if possible?
EDIT: cant make the code work! Theoricaly i need the code to make an xhr request depending on the div id class and fill the information inside that div with the xhr response from that id. Think of a movie database that will show specific movie information from a movie list.
Wrap your code into function and then call it in loop or manually several times with different searchid values.
function runSearch(searchid, fullMovie) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
var fullMovie = JSON.parse(xhr.responseText);
var movie = { title: fullMovie.Title, runtime: fullMovie.Runtime, plot: fullMovie.Plot };
document.getElementById('Title').innerText = movie.title;
document.getElementById('Runtime').innerText = movie.runtime;
document.getElementById('Plot').innerText = movie.plot
}
};
xhr.open('GET', 'http://www.omdbapi.com/?i=' + searchid + '&plot=short&r=json', true);
xhr.send(null);
}
Then call it like this:
runSearch('your search id', fullMovie);
<div id="runSearch('tt0110912', fullMovie)">
JavaScript needs to go in a script element (or an intrinsic event attribute, but they are terrible and should be avoided).
The id attribute is where you put an identifier for an element. It isn't JavaScript and it makes no sense to put JavaScript there.
<script>
runSearch('tt0110912', fullMovie)
</script>
Your HTML is invalid. An id must be unique in a document. You can't reuse the if Title (etc) within the same document. Look at using classes instead.
Related
I am using Js xmlHttpRequest to display the same menu on different pages of my site. Lately I found out that some functions are not executed when the site is online, like a quiz I made.
I had also tried to use fetch, or put the scripts in different files, but the same thing kept happening.
(The quiz does work when checking locally, where the xml request cannot be satisfied.)
//load the menu
onload = function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementsByTagName('body')[0].innerHTML +=
this.responseText;
}
};
xhttp.open("GET", "mnu.html", true);
xhttp.send();
}
//check the quiz
const checkBtn = document.getElementById('checkBtn')
checkBtn.onclick = function quizCheck() {
//right answers
var score = 0;
if (q1a1.checked) {
score = score + 1;
}
if (q2a1.checked) {
score = score + 1;
}
alert("your score: " + score);
}
<li>
Check the right answer:
<br>
<input type="checkbox" id="q1a1">Right
<br>
<input type="checkbox">Wrong
</li>
<li>
Check the right answer:
<br>
<input type="checkbox" id="q2a1">Right
<br>
<input type="checkbox">Wrong
</li>
<button id="checkBtn">Check</button>
Anybody knows why and/or has some solutions?
The problem is this line which is wrong and that's why js is not working.
document.getElementsByTagName('body')[0].innerHTML += this.responseText;
You can't just add to innerHtml like that.
Instead you should create an html element and add it to body like this:
if (this.readyState == 4 && this.status == 200) {
var p = document.createElement("p");
p.innerText = this.responseText;
document.body.appendChild(p);
}
edit: of course you want to add an html menu instead of just a text inside a <p>, so you will have to add it like this:
var nav = document.createElement('nav');
nav.innerHTML = this.responseText;
document.body.prepend(nav); // always at the top
I have a function that is responsible for updating the values in some <div>, the code looks like this:
file.js
window.onload = function makeRequest() {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
calcPreco(xmlHttp.responseText);
}
xmlHttp.open("GET", "_config/buscar_valor.php?id="+document.getElementsByName("cloud")[0].getAttribute("cloudid")+"&periodicidade=monthly", true); // true para asynchronous
xmlHttp.send(null);
}
function calcPreco(preco) {
console.log(preco);
preco = preco.replace(",", ".");
preco -= document.getElementsByName("cloud")[0].getAttribute("desconto");
document.getElementsByClassName("mostrar_valor").textContent = preco;
}
index.php
<div name="cloud" cloudid="1" desconto="5">
<span class="mostrar_valor"></span>
</div>
<div name="cloud" cloudid="2" desconto="10">
<span class="mostrar_valor"></span>
</div>
<div name="cloud" cloudid="3" desconto="15">
<span class="mostrar_valor"></span>
</div>
Note that only the cloudid anddesconto attributes are changed in each <div>, the remainder remains the same.
The script will only do a calculation by searching for the value in "buscar_valor.php", through the cloudid attribute, which is the ID of each plan.
The desconto attribute is the amount it will subtract from the account.
The problem is that it is doing this only for the first <div>, how can I make it work for all <div>?
You have to loop over all cloud elements as:
for(const cloud of Array.from(document.getElementsByName("cloud"))) {
To then retrieve the related preco from the API I would use the new fetch method as that is way more easy to handle:
fetch("_config/buscar_valor.php?id=" + cloud.getAttribute("cloudid")+ "&periodicidade=monthly")
.then(res => res.text())
.then(preco => {
Now the desconto can be applied to preco:
preco -= cloud.getAttribute("desconto");
To get the mostrar_valor insode that cloud, just use querySelector:
const valor = cloud.querySelector(".mostrar_valor");
then you can change the textContent of that element.
I am attempting to build a web feature that allows the user to select a window of time to see local Earthquake information, using information found here.
https://earthquake.usgs.gov/earthquakes/feed/v1.0/geojson.php
As you can see here, (https://codepen.io/JoshTheGray/pen/yPmJeR) I am having success parsing the information when I statically assign the url variable for whatever timeframe I want, however I am running into trouble trying to make that url variable change, based on a user button click.
My HTML
<div>Please select a window of time to see Earthquake information.</div>
<br>
<button id="1HourButton">Past Hour</button>
<button id="1DayButton">Past 24 Hours</button>
<br>
<br>
<div id="output1">Earthquakes Around the State<br><br></div>
<br>
My JavaScript / JQuery
;(function($){
$( document ).ready(function() {
// testing document load state
console.log( "document loaded" );
var output1 =document.getElementById('output1');
var hr = new XMLHttpRequest();
// Asigns url based on button choice from user.
var url = '';
$('#1HourButton').click(function () {
url = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson';
console.log(url);
});
$('#1DayButton').click(function () {
url = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson';
console.log(url);
});
hr.onreadystatechange = function() {
if(this.readyState === 4 && this.status === 200){
var myObj = JSON.parse(hr.response);
for(i=0; i < myObj.features.length; i++) {
if (myObj.features[i].properties.title.includes("Alaska")) {
output1.innerHTML += myObj.features[i].properties.title + '<br>';
}
}
}
}
hr.open("GET", url, true);
hr.send();
});
})(jQuery);
=========================
Currently I am seeing the correct URL information passed to the console upon button click, but the json information is no longer coming through.
What am I missing?
Using Ajax, I want to display the response text of a certain file when clicking its corresponding tab; for example, when clicking the "Box 1" tab, it must display the response text of box1.html, "Box 2" for box2.html, and "Box 3" for box3.html - (the box files are located inside the ajax folder). The issue is, all the three tabs displays only the response text of box3.html. When I open the console to look for errors, there was none.
HTML
<section>
<!-- TABS -->
<div>
<button>Box 1</button>
<button>Box 2</button>
<button>Box 3</button>
</div>
<!-- ResponseText container -->
<div id="response-text"></div>
</section>
JavaScript
function query(selector) {
return Array.prototype.slice.call(document.querySelectorAll(selector));
}
query('button').forEach(function(btn) {
btn.onclick = function() {
var xhr = new XMLHttpRequest();
var files = ['box1', 'box2', 'box3'];
for(var f=0; f<files.length; f++) {
var result = files[f];
xhr.open('POST', 'ajax/'+result+'.html', true);
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
document.querySelector('#response-text').textContent = xhr.responseText;
}
}
xhr.send();
}
}
});
Is my style of pushing elements into arrays improper?
I would appreciate so much the corrections, improvements, and tips that you would suggest.
You are probably overwriting the div, with command
document.querySelector( '# response-text') textContent = xhr.responseText.;
switch to append and see if it works correctly.
document.querySelector( '# response-text') append( xhr.responseText);
This is the markup
<div class="header">
Competitive Exams
</div>
<div class="Content login">
<form action="authenticate.php" method="get" id="login">
<ul>
<li id="b9">Login</li>
<li id="b10"><input type="text" name="username" placeholder="Username" ></li>
<li id="b12"><input type="password" name="password" placeholder="Password"></li>
<li id="b11"><input type="submit" value="MoveIn"></li>
</ul>
</form>
</div>
<div id="show"></div>
<div class="foot">
Copyright © 2013.All Rights Reserved.Created by :HACKSHAK & I-GOOGLEPLAY.
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type= "text/javascript" src="debug.js"></script>
/This is the javascript code for ajax call/
window.onload = function(){
var form = document.getElementById('login');
var output = document.getElementById('show');
form.onsubmit = function(e){
e.preventDefault();
var action = form.action;
var method = form.method;
var data = {};
var names = document.querySelectorAll('#login [name]');
for(var i=0;i<2;i++){
var name = names[i].name;
var value = names[i].value;
data[name] = value;
}
var transmit = new Transmit(method,action,data,output).bind(transmit);
}
function Transmit(method,action,data,output){
this.method = method;
this.action = action;
this.data = data;
this.output = output;
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
alert(xhr);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
this.output.innerHTML = xhr.responseText;
this.output.style.display = "inline-block";
}
}
xhr.open(this.method,this.action?this.data,true);
xhr.send();
}
}
when I run the code even after the default behaviour of the form is prevented it redirects to authenticate.php instead of making ajax call.
From the JS error console:
Uncaught SyntaxError: Unexpected token ,
You start a ternary operator here, but never finish it:
xhr.open(this.method,this.action?this.data,true);
Consequently, the function you assign to onload never gets properly parsed, so it never gets assigned, so you never assign your submit event.
It looks like you are trying to construct a query string, but getting it entirely wrong.
You need to loop over the object, encodeURIComponent all the keys and values, and then concatenate them (via +) using = and & characters before concatenating (again with +) to the action and the string "?".
Authentication should generally be done with a POST request rather than a GET request though.