HTML page doesn't show that city does not exist - javascript

I am trying to make a website that shows the weather forecast. It already shows the weather forecast. If I want to enter a city that doesn't exist I want a message to appear. I already tried something with 404 but it doesn't show up in the console log. I hope someone can help me. Thank you in advance!
function getData() {
let apikey = 'private';
var city = document.querySelector('#city').value;
let requestURL = 'https://api.openweathermap.org/data/2.5/forecast?q='+city+'&appid='+apikey+'&units=metric';
let request = new XMLHttpRequest();
request.open('GET', requestURL, true);
request.responseType = 'json';
request.send();
request.onload = function () {
let data = request.response;
addData(data);
var body = document.querySelector('body');
var div = document.createElement('div');
for (var i = 0; i < data.list.length; i += 8) {
// console.log(data.list[i].dt_txt);
div.appendChild( createEL('p',
'<b>Date en time: ' + data.list[i].dt_txt+'<br></b>'+
'City: ' + city+'<br>'+
'Country: ' + data.city.country + '<br>'+
'Temperature: ' +data.list[i].main.temp+'<br>'+
'Weather: ' +data.list[i].weather[0].main));
}
if (XMLHttpRequest == '404'){
console.log("Doesn't exist")
}
var body = document.querySelector('body');
body.appendChild(div);
function createEL(tag, content){
var el = document.createElement(tag);
el.innerHTML = content;
return el;
}
}
}
var button = document.querySelector('#show');
button.addEventListener("click", function (ev) {
ev.preventDefault();
getData();
},false);
function addData(jsonData) {
var city = document.querySelector('#city').value;
var input = document.querySelector('#city');
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Weather</title>
</head>
<body>
<h1>Weather</h1>
City: <input type="text" id="city" name="city" placeholder="city">
<button id="show" name="show">Show</button>
<script src="js/weather.js"></script>
</body>
</html>

XMLHttpRequest will never be equal to 404. It is the constructor function you used to created the object that made the HTTP request!
You need to examine request.status.

You need to check request.status if you are sending status code from API.
let request = new XMLHttpRequest()
console.log(request.status);
To display does not exist you can check the response data length like
if(data.list.length==0)
{
console.log("Does not exists.");
}

Related

Django-channels:chatSocket.onmessage or chatSocket.send does not work

I'm trying to implement a django channels chat app. when the submit button of the room view is clicked, the message does not appear in the chat log. which make me think that somethings wrong with chat.onmessage command, it does not seem to fire. can someone help me fix the issue. here is the code for room view:
<!-- chat/templates/room.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Chat Room</title>
</head>
<body>
<textarea id="chat-log" cols="100" rows="20"></textarea><br/>
<input id="chat-message-input" type="text" size="100"/><br/>
<button id="chat-message-submit" type="submit" value="Send">Send</button>
</body>z
<script>
var roomName = {{ room_name_json }};
var chatSocket = new WebSocket(
'ws://' + window.location.host +
'/ws/chat/' + roomName + '/');
chatSocket.onmessage = function(e) {
console.log("got to onmessage");
var data = JSON.parse(e.data);
var message = data['message'];
document.getElementById('chat-log').value += (message + '\n');
};
chatSocket.onclose = function(e) {
console.error('Chat socket closed unexpectedly');
};
document.querySelector('#chat-message-input').focus();
document.querySelector('#chat-message-input').onkeyup = function(e) {
if (e.keyCode === 13) { // enter, return
document.getElementById('chat-message-submit').click();
}
};
document.getElementById('chat-message-submit').onclick = function(e) {
var messageInputDom = document.getElementById('chat-message-input');
var message = messageInputDom.value;
console.log("got message : " + message);
chatSocket.send(JSON.stringify({
'message': message
}));
console.log("This was done?");
messageInputDom.value = '';
};
</script>
</html>
Here is my consumer view :
from channels.generic.websocket import WebsocketConsumer
import json
class ChatConsumer(WebsocketConsumer):
def connect(self):
self.accept()
def disconnect(self, close_code):
pass
def recieve(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
self.send(text_data = json.dumps({
'message' : message
}))
I'm so stupid I literally made a typo, used function name "received" instead of "recieved". Thanks I'll go cry in the corner now.

AJAX return undefined in html document

I have the following xml document
<?xml version="1.0" ?>
<result searchKeyword="Mathematics">
<video>
<title>Chaos Game</title>
<channel>Numberphile</channel>
<view>428K</view>
<link>http://www.youtube.com/watch?v=kbKtFN71Lfs</link>
<image>http://i.ytimg.com/vi/kbKtFN71Lfs/0.jpg</image>
<length>8:38</length>
</video>
<video>
<title>Australian Story: Meet Eddie Woo, the maths teacher you wish you&apos;d had in high school</title>
<channel>ABC News (Australia)</channel>
<view>223K</view>
<link>http://www.youtube.com/watch?v=SjIHB8WzJek</link>
<image>http://i.ytimg.com/vi/SjIHB8WzJek/0.jpg</image>
<length>28:08</length>
</video>
<video>
<title>Ham Sandwich Problem</title>
<channel>Numberphile</channel>
<view>557K</view>
<link>http://www.youtube.com/watch?v=YCXmUi56rao</link>
<image>http://i.ytimg.com/vi/YCXmUi56rao/0.jpg</image>
<length>5:53</length>
</video>
<video>
<title>Magic Square Party Trick</title>
<channel>Numberphile</channel>
<view>312K</view>
<link>http://www.youtube.com/watch?v=aQxCnmhqZko</link>
<image>http://i.ytimg.com/vi/aQxCnmhqZko/0.jpg</image>
<length>3:57</length>
</video>
<video>
<title>The 8 Queen Problem</title>
<channel>Numberphile</channel>
<view>909K</view>
<link>http://www.youtube.com/watch?v=jPcBU0Z2Hj8</link>
<image>http://i.ytimg.com/vi/jPcBU0Z2Hj8/0.jpg</image>
<length>7:03</length>
</video>
</result>
I have created this html file which has an AJAX call to get the xml file but it return all the values as "undefined"
<html>
<head>
<title>A7-Question2</title>
<script>
function getSearch()
{
// create an XMLHttpRequest
var xhttp = new XMLHttpRequest();
//create a handler for the readyState change
xhttp.onreadystatechange = function() {
readyStateChangeHandler(xhttp);
};
//get XML file by making async call
xhttp.open("GET", "A7.xml", true);
xhttp.send();
}
// handler for the readyState change
function readyStateChangeHandler(xhttp){
if (xhttp.readyState == 4){
// readyState = 4 means DONE
if(xhttp.status == 200){
// status = 200 means OK
handleStatusSuccess(xhttp);
}else{
// status is NOT OK
handleStatusFailure(xhttp);
}
}
}
// XMLHttpRequest failed
function handleStatusFailure(xhttp){
// display error message
var displayDiv = document.getElementById("display");
displayDiv.innerHTML = "XMLHttpRequest failed: status " + xhttp.status;
}
// XMLHttpRequest success
function handleStatusSuccess(xhttp){
var xml = xhttp.responseXML;
// print XML on the console
console.log(xml);
// parse the XML into an object
var searchResult = parseXML(xml);
// print object on the console
console.log(searchResult);
// display the object on the page
display(searchResult);
}
// parse the XML into an object
function parseXML(xml){
var resultElement = xml.getElementsByTagName("result")[0];
//create a receipt object to hold the information in the xml file
var searchResult = {};
searchResult.searchKeyword= resultElement.getAttribute("searchKeyword");
var videoElements = xml.getElementsByTagName("video");
//create an array to hold the items
searchResult.videoArray = [];
for(var i=0; i< videoElements.length; i++){
var video = {};
video.title = videoElements[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
video.channel = Number(videoElements[i].getElementsByTagName("channel")[0].childNodes[0].nodeValue);
video.view = Number(videoElements[i].getElementsByTagName("view")[0].childNodes[0].nodeValue);
video.link = Number(videoElements[i].getElementsByTagName("link")[0].childNodes[0].nodeValue);
video.image = Number(videoElements[i].getElementsByTagName("image")[0].childNodes[0].nodeValue);
searchResult.videoArray.push(video);
};
return searchResult;
}
// display the searcg result object on the page
function display(searchResult){
var html = "<p>searchKeyword: Mathematics</p>";
for(var i=0; i<searchResult.videoArray.length; i++){
var video = searchResult.videoArray[i];
html += "title: " + searchResult.title + "<br/>";
html += "channel: " + searchResult.channel + "<br/>";
html += "view: " + searchResult.view + "<br/>";
html += "link: " + searchResult.link + "<br/>";
html += "image: " + searchResult.image + "<br/>";
html += "length: " + searchResult.length + "<br/>";
}
var displayDiv = document.getElementById("display");
displayDiv.innerHTML = html;
}
</script>
</head>
<body>
<button onclick="getSearch()">Get Search Result</button>
<div id="display"></div>
</body>
</html>
Is the problem with my success function? Is it returning null because it hasn't returned all the values or something due to how AJAX runs?
Thanks heaps for any help
There's a lot of code to go over and a working snippet can't be produced because we can't put the XML file here.
This answer is making an assumption that your response from the XMLHttpRequest is null and the problem does not lie in any of your parsing functions.
It also seems that you're over complicating the request process by passing it around to many functions when it's quite simple itself.
Here is an example I made locally that correctly logged the XML to the console:
<!doctype html>
<html>
<head>
<title>A7-Questions2</title>
</head>
<body>
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var xml = xhttp.responseXML;
// Logs just fine for me. You can do your parsing here.
console.log(xml);
}
};
xhttp.onerror = function() {
// Display error message.
var displayDiv = document.getElementById('display');
displayDiv.textContent = 'XMLHttpRequest failed status: ' + xhttp.status;
};
xhttp.open('GET', './path/to/xml.xml');
xhttp.send();
</script>
</body>
</html>

Response.write() or .toString() (bug?) on NodeJS server

I am a trying to make a small web server for testing. I made it with NodeJS. But something unexpected happened. The webpage passed by the NodeJS server couldn't be displayed properly. But the webpage worked perfectly when I used php+Apache. When I opened the source code received at my client side, there are no observable difference. Here is my code:
Server.js
var http = require('http');
var fs = require('fs');
var url = require('url');
var Max = 30;
var port = process.argv[2];
var server = http.createServer( function (request, response) {
var pathname = url.parse(request.url).pathname; if (pathname == "") pathname = "index.html";
console.log("Request for " + pathname + " received.");
fs.readFile(pathname.substr(1), function (err, data) {
if (err) {
console.log(err);
response.writeHead(404, {'Content-Type': 'text/html'});
} else {
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data.toString());
}
response.end();
});
}).listen(port);
console.log('Server running at http://127.0.0.1:8081/');
var sockets = {}, nextSocketId = 0;
server.on('connection', function (socket) {
var socketId = nextSocketId++;
sockets[socketId] = socket;
console.log('socket', socketId, 'opened');
socket.on('close', function () {
console.log('socket', socketId, 'closed');
delete sockets[socketId];
});
socket.setTimeout(4000);
});
function anyOpen(array) {
for (var ele in array) {
if (ele) return true;
}
return false;
}
(function countDown (counter) {
console.log(counter);
if (anyOpen(sockets)) {
return setTimeout(countDown, 1000, Max);
} else if (counter > 0 ) {
return setTimeout(countDown, 1000, counter - 1);
};
server.close(function () { console.log('Server closed!'); });
for (var socketId in sockets) {
console.log('socket', socketId, 'destroyed');
sockets[socketId].destroy();
}
})(Max);
Chatroom2-0.php
<!DOCTYPE html>
<html>
<head>
<style>
textarea {
width:95%;
rows:50;
height:80%;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
<script type="text/javascript">
var str = "";
function enter(e){
if (e.keyCode == 13 && document.getElementById("Input").value) {
//alert("Enter!!!!");
sendInput();
document.getElementById("Input").value = "";
}
};
function updateBoard() {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if ( xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("MsgBoard").innerHTML = xmlhttp.responseText;
}
var textarea = document.getElementById('Output');
textarea.scrollTop = textarea.scrollHeight;
};
xmlhttp.open("POST","Server.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("Type=Username&Content="+document.getElementById("Username").value);
};
function sendInput() {
username = document.getElementById("Username").value; if (!username) username = "Gotemptyname";
msg = document.getElementById("Input").value; if (!msg) msg = "GotNothing";
if (msg) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","Server.php",true);
//xmlhttp.open("POST","test.txt",true);
//xmlhttp.send();
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("Type=Message&Username="+username+"&Content="+msg);
//alert(xmlhttp.responseText);
}
};
</script>
</head>
<body onload="setInterval('updateBoard()',1000)">
<div id="MsgBoard"></div>
<form name="UsrInput">
<?php
if (isset($_POST["Username"]))
echo '<input type="text" id ="Username" value="'.$_POST["Username"].'" disable>';
else {
header("Location: /login/index.html");
die();
}
?>
<input type="text" id="Input" onkeypress="enter(event)" value="" >
</form>
</body>
</html>
Users should be able to access the Chatroom2-0.php after login. The login functionality is also ok. But when I entered the Chatroom2-0.php, I got a String, next to my textbox.
'; else { header("Location: /login/index.html"); die(); } ?>
I noticed that the string is part of my php code in the file. I don't know what's happening. I think this might have something to do with the response.write() or the data.toString() function. Maybe the function changed something in my coding? How could I solve this problem.
Anyway, I appreciate for any help given.
The problem is that you are trying to run php code on a nodejs server. There is no solution to this, as node is not a php interpreter, so it sees everything as html text; thus your php code appearing on the page. You need to create an entirely different html for the node project.

JSON error request is not defined

When I do console.log(req.responsetext) i get [11:38:04.967] ReferenceError: req is not defined. But i define req as a new xml request on window load so I am kind of stumped. Is there a way that I should be passing a reference?
the console output is as follows
[12:29:06.839] GET getterms.php?query=DFA [HTTP/1.1 200 OK 99ms]
[12:29:06.888] SyntaxError: JSON.parse: unexpected character # search.php:21
[12:33:24.316] console.log(req.responsetext)
[12:33:24.318] ReferenceError: req is not defined
Any and all help would be most gratefully appreciated. Thank you to anyone who takes the time to read and/or answer even if you cannot help!
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>Auto Complete</title>
</head>
<body>
<script>
window.onload = function () {
var req = new XMLHttpRequest(); //the HTTP request which will invoke the query
var input = document.getElementById('search'); //where to grab the search from
var output = document.getElementById('results'); //where to display the sugestions
input.oninput = getSuggestions;
function getSuggestions() {
req.onreadystatechange = function () {
output.innerHTML = ""; //CLEAR the previous results!! only once the server can process new ones though
if (this.readyState == 4 && input.value != "") {
var response = JSON.parse(req.responseText);
for (var i = 0; i < response.length; i++)
addSuggestion(response[i].terms);
}
}
req.open('GET', 'getterms.php?query=' + input.value, true); //GET request to getterms.php?=
req.send(null);
}
addSuggestion = function (suggestion) {
var div = document.createElement('div');
var p = document.createElement('p');
div.classList.add('suggestion'); //suggestion[x]...
p.textContent = suggestion;
div.appendChild(p);
output.appendChild(div);
div.onclick = function() {
input.value = p.innerHTML; //set the search box
getSuggestions(); //GET new suggesions
}
}
}
</script>
<input type='text' id='search' name='search' autofocus='autofocus'>
<div id='results'></div>
</body>
</html>
edit this is my php page that echos the json.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
if (!isset($_GET['query']) || empty($_GET['query']))
header('HTTP/1.0 400 Bad Request', true, 400);
else {
$db = new PDO(
my database
);
$search_query = $db->prepare("
SELECT * FROM `words` WHERE `word` LIKE :keywords LIMIT 5
");
$params = array(
':keywords' => $_GET['query'] . '%',
);
$search_query->execute($params);
$results = $search_query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($results);
}
?>
Scope problem! Remove var in front of req to make it global and it should work

JSON error when trying to parse request length in loop

So I am trying to make a simple autocomplete form but keep getting a error when I try to test the program.
When I try to test the program my console spits out [11:25:26.267] SyntaxError: JSON.parse: unexpected character # /search.php:22 which is this line. I am pretty sure my syntax is fine but I could be mistaken. Any and all help would be most gratefully appreciated. Thank you to anyone who takes the time to read and/or answer even if you cannot help!
for (var i = 0; i < response.length; i++)
My Full code is as follows.
Edit: Now with page that echos the json. When I do console.log(req.responsetext) i get [11:38:04.967] ReferenceError: req is not defined. But i define req as a new xml request on window load so I am kind of stumped.
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>Auto Complete</title>
</head>
<body>
<script>
window.onload = function () {
var req = new XMLHttpRequest(); //the HTTP request which will invoke the query
var input = document.getElementById('search'); //where to grab the search from
var output = document.getElementById('results'); //where to display the sugestions
input.oninput = getSuggestions;
function getSuggestions() {
req.onreadystatechange = function () {
output.innerHTML = ""; //CLEAR the previous results!! only once the server can process new ones though
if (this.readyState == 4 && input.value != "") {
var response = JSON.parse('(' + req.responseText + ')');
for (var i = 0; i < response.length; i++)
addSuggestion(response[i].terms);
}
}
req.open('GET', 'getterms.php?query=' + input.value, true); //GET request to getterms.php?=
req.send(null);
}
addSuggestion = function (suggestion) {
var div = document.createElement('div');
var p = document.createElement('p');
div.classList.add('suggestion'); //suggestion[x]...
p.textContent = suggestion;
div.appendChild(p);
output.appendChild(div);
div.onclick = function() {
input.value = p.innerHTML; //set the search box
getSuggestions(); //GET new suggesions
}
}
}
</script>
<input type='text' id='search' name='search' autofocus='autofocus'>
<div id='results'></div>
</body>
</html>
edit this is my php page that echos the json.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
if (!isset($_GET['query']) || empty($_GET['query']))
header('HTTP/1.0 400 Bad Request', true, 400);
else {
$db = new PDO(
my database
);
$search_query = $db->prepare("
SELECT * FROM `words` WHERE `word` LIKE :keywords LIMIT 5
");
$params = array(
':keywords' => $_GET['query'] . '%',
);
$search_query->execute($params);
$results = $search_query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($results);
}
?>
Get rid of the ( and ) in the JSON.parse!
JSON.parse('(' + req.responseText + ')')
should be
JSON.parse( req.responseText );
hopefully the responseText is valid JSON

Categories

Resources