Using AJAX to create a datalist - javascript

I'm trying to add to a datalist using AJAX. The webpage I'm requesting just has names of cities each on their own line. I basically have:
(function() {
"use strict";
window.onload = function() {
fetch("cities");
};
function fetch(mode) {
var request = new XMLHttpRequest();
request.onload = getCities();
request.open("GET", "https://weather.com/weather/mode=" + mode, true);
request.send();
}
function getCities() {
//loop while there's data/string to grab {
var city = document.createElement("option");
city.innerHTML = this.responseText; //set the option as the name of the city from the request
document.getElementById("cities").appendChild(city);
}
}
}) ();
The webpage is just a filler for a webpage that I'm using on a server but I'm trying to create a new option tag for each string and append it to a datalist in my html but I'm having an issue catching anything. For some reason I'm just getting an undefined error. Sorry I'm kind of new to javascript and AJAX.
webpage layout of the page of requesting:
Abidjan
Accra
Adana
Addis Abeba
Ahmedabad
Aleppo
Alexandria
Alger
Almaty
Ankara
Anshan
Baghdad
Baku
Bandung
Bangalore
Bangkok

You're missing brackets () off your function calls
(function() {
"use strict";
window.onload = function() {
fetch("cities");
};
function fetch(mode) {
var request = new XMLHttpRequest();
request.onload = getCities(); // <- brackets missing here
request.open("GET", "https://weather.com/weather/mode=" + mode, true);
request.send(); // <- and here
}
function getCities() {
var city = document.createElement("option");
document.getElementById("cities").innerHTML = this.responseText;
}
}) ();
It's also very unclear to me how your getCities function is supposed to work. You're creating an option set, but not adding it to your DOM. I'm also not sure what this.responseText is supposed to be.

Related

How do I get around refreshing my videos?

I am making a messaging system and I recently added file uploads, and I refresh the messages every 1.5 seconds Here is my function :
function load_messages(){
var id = document.getElementById('group_id').value;
var fullurl = "loadmessages.php?id=" + id;
var request = new XMLHttpRequest();
request.open("GET",fullurl,false);
request.onload = function(){
if(request.status == 200){
document.getElementById("groupchat").innerHTML = this.responseText;
}
}
request.send();
};
setInterval(load_messages, 1500);
I think the problem is that it keeps refreshing it there for I can't view it. How do I get around that?

JavaScript Handlebars give no error but does not work

I am trying to replace text in my page using handlebars. But its not working and i am not getting any errors either.
The following code kicks in when the user presses the submit button
<button type="submit" id="add_lunch" class="button button-contactForm boxed-btn" onclick="addToCart()">Submit</button>
this then
function addtoCart() {
var request = new XMLHttpRequest();
var base_id = $("input[name='base_id']:checked").val();
var protein_id = $("input[name='protein_id']:checked").val();
var dessert_id = $("input[name='dessert_id']:checked").val();
var side_id = $("input[name='dessert_id']:checked").val();
request.open('POST', '/cart');
request.onload = () => {
// Extract JSON data from request
var template = Handlebars.compile(document.querySelector('#js_result').innerHTML);
var data_response = JSON.parse(request.responseText);
var content = template({'base_name': data_response.base.name});
console.log("****" + data_response.base.name)
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#add_lunch').onclick = () => {
document.querySelector('#media_js_body').innerHTML += content;
};
});
}
var data = new FormData();
data.append('base_id', base_id);
data.append('protein_id', protein_id);
data.append('side_id', side_id);
data.append('dessert_id', dessert_id);
// Send request
request.send(data);
return false;
}
plus the template
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.11/handlebars.min.js"></script>
<script id="js_result" type="text/x-handlebars-template">
{{ base_name }}
</script>
<script src="{{ url_for('static', filename='js/util.js') }}"></script>
What i have figured out so far is that it has something to do with DOM state? and onclick even.
Any suggestions and corrections?
i do not know if it was the coffee i drank, but after a few sips and few changes it seems to work partially now. i am getting the text being placed in the right place.
Now i only have to make sure that the values from data_response gets transferred in content as well
This is what i changed.
function addToCart() {
var request = new XMLHttpRequest();
var limit=2;
var base_id = $("input[name='base_id']:checked").val();
var protein_id = $("input[name='protein_id']:checked").val();
var dessert_id = $("input[name='dessert_id']:checked").val();
var side_id = [];
$.each($("input[name='side_id']:checked"), function(){
side_id.push($(this).val());
});
if(side_id.length==limit) {
request.open('POST', '/cart');
request.onload = () => {
// Extract JSON data from request
var data_response = JSON.parse(request.responseText);
var templateInfo=document.querySelector('#js_result').innerHTML
console.log("TempInfo:" + templateInfo)
var template = Handlebars.compile(templateInfo);
var content = template({'base_name': data_response.base.name});
console.log("DataResponse:" + data_response.base.name);
console.log("Content:" + data_response.base.name);
document.querySelector('#media_js_body').innerHTML += content;
}
var data = new FormData();
data.append('base_id', base_id);
data.append('protein_id', protein_id);
data.append('side_id', side_id);
data.append('dessert_id', dessert_id);
// Send request
request.send(data);
} else {
alert("Kindly select "+limit+" sides")
}
return false;
}

How to assign input id to variable for concat with url api call

I'm loading data from api into html table and would like to use user input field to change api call.
<input id="stockInput" value="AAPL"></input>
<br/>
<button id="submit">Submit</button>
const stocksBody = document.querySelector("#stocks-table > tbody
#data");
var input = $("#stockInput").val();
var url = "https://api.iextrading.com/1.0//stock";
var quote = "/quote";
function setup() {
var button = select("#submit");
button.mousePressed(loadData);
}
function loadData(){
const request = new XMLHttpRequest();
request.open("get", url + input.val() + quote);
request.onload = () => {
try {
var response = JSON.parse(request.responseText);
console.log(response);
populateData(response);x
} catch (e) {
console.warn("Could not load data!");
}
};
request.send();
I expect stock symbol entered by user to return stock data.
You are calling .val() twice.
Change this line:
request.open("get", url + input.val() + quote);
// ^^^^^^ - remove

AJAX and datalists

I'm trying to use XML to get a list of cities from a website, then go through and add each of the cities to a datalist so that when I put in an input it will filter the cities in the list.
example of city list:
Aleppo
Alexandria
Alger
Almaty
Ankara
Anshan
Baghdad
Baku
Bandung
Bangalore
Bangkok
Barcelona
*[Each city name is on a new line]
current html:
<div id="namearea">
<h2>City Name:</h2>
<div>
<input id="citiesinput" list="cities">
<datalist id="cities"></datalist>
<button id="search">
Search
</button>
<span class="loading" id="loadingnames">
Loading...
</span>
</div>
</div>
current JS code:
window.onload = function() {
var request = new XMLHttpRequest();
request.onload = processCities;
request.open("GET", "url", true);
request.send();
};
Inspecting the page with Firebug shows that nothing is being added to the datalist, so I'm wondering what I'm doing wrong. I also tried using .responseText rather than .responeXML but it didn't make any difference.
[Fixed]
I changed the processCities() function to:
function processCities() {
var response = this.responseText;
var city = response.split("\n");
var options = "";
for(var i = 0; i < response.length; i++) {
options += "<option value='"+city[i]+"'>\n";
}
document.getElementById("cities").innerHTML = options;
}
This code seems to work.
Here is an example of making the request. If you really are getting XML, you'll have to parse it. It's better if you could get json.
var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
var data = JSON.parse(request.responseText);
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();

settimeout not getting called?

I have a javascript which call a server and get a JSON data which contains some config to enable/disable redirecting to another link. I need to delay the redirection by a few seconds, but it seems that setTimeout() is not getting called in my method. Even if I change redirect() as an anonymous function and pass it in setTimeout it is still not getting called.
<script>
var xhr = new XMLHttpRequest();
var migrationConfig;
xhr.onreadystatechange = function() {
function redirect(){
alert("in redirect");
window.top.location=migrationConfig.REDIRECT_LINK;
}
if (xhr.readyState == 4 && xhr.status==200) {
var data = xhr.responseText;
migrationConfig = JSON.parse(data);
if(migrationConfig.SHOW_REDIRECT_MESSAGE == 'Y'){
if (window.confirm(migrationConfig.REDIRECT_MESSAGE)){
document.body.innerHTML = '';
document.write("<h1><font color='red'>You will now be redirected to the new URL at:</font></h1>");
document.write("<h1><font color='red'>"+ migrationConfig.REDIRECT_LINK +"</font></h1>");
setTimeout(redirect,3000);
}
}
}
}
xhr.open('GET', '/MyApp/migration-config?APP_NAME=MyApp', true);
xhr.send(null);
// set global object for using it inside the settimeout function
var redirect;
and then inside the xhr.onreadystatechange = function() {
redirect = function(){
alert("in redirect");
window.top.location=migrationConfig.REDIRECT_LINK;
}
setTimeout('redirect()',3000);
Thanks for all the suggestions. I have improved it as per suggestion by talsibony, and I further found out also that document.write() removes all my content, which makes it unable to find the redirect global variable. So I have instead changed it to add a div element and set the innerHTML. Here is the fixed code in case if someone encountered similar issue.
<script>
var xhr = new XMLHttpRequest();
var migrationConfig;
var redirect;
xhr.onreadystatechange = function() {
redirect = function(){
window.top.location=migrationConfig.REDIRECT_LINK;
}
if (xhr.readyState == 4 && xhr.status==200) {
var data = xhr.responseText;
migrationConfig = JSON.parse(data);
if(migrationConfig.SHOW_REDIRECT_MESSAGE == 'Y'){
if (window.confirm(migrationConfig.REDIRECT_MESSAGE)){
document.body.innerHTML = '';
var div = document.createElement("div");
document.body.insertBefore(div, document.body.firstChild);
div.innerHTML += "<h1><font color='red'>You will now be redirected to the new URL at:</font></h1>";
div.innerHTML += "<h1><font color='red'>"+ migrationConfig.REDIRECT_LINK +"</font></h1>";
div.innerHTML += "<h1><font color='red'>Remember to save the new URL to your favorites</font></h1>";
setTimeout(redirect,3000);
}
}
}
}
xhr.open('GET', '/MyApp/migration-config?APP_NAME=MyApp', true);
xhr.send(null);

Categories