JavaScript - Issue with using ReST API - javascript

Not sure what I am doing wrong here.
HTML
<form id="inp" onsubmit="process()">
<input id="link" type="text" name="link" placeholder="Enter your link">
<input id="submit" type="submit" name="submit" value="→">
</form>
JavaScript
function createRequest() {
let result = null;
if (window.XMLHttpRequest) {
result = new XMLHttpRequest();
result.overrideMimeType('application/json');
}
else {
window.alert("Abort!");
}
return result;
}
let c=0;
function process() {
let l = document.getElementById("inp").link.value;
let resp;
let req = createRequest();
let payload = {
link: l,
ignoreException: true
};
req.open("POST", url, true);
req.setRequestHeader("Content-Type", "application/json");
req.send(payload);
req.onreadystatechange = function () {
if (req.readyState === 4 && req.status === 200) {
resp = req.responseText;
console.log("response text - " + resp);
}
console.log(req.readyState + " " + req.status + " " + c);
};
}
I want it to log the readyState and status for every state change and also log the response text for the final state.
It logs " 4 0 1 " which means it's changing the state just once and is changing it straight to the final state.
It should change the states as .open(), .setRequestHeader(), and .send() functions are executed.
How can I make this work?
Note- "url" parameter is the api url.

If you want the onreadystatechange event to be called for .open() and .setRequestHeader() you will need to register the onreadystatechange event handler before you call the open() and setRequestHeader() functions.
So if you move the onreadystatechange definition up a few lines, it should be good.
So something like this:
function process() {
let l = document.getElementById("inp").link.value;
let resp;
let req = createRequest();
let payload = {
link: l,
ignoreException: true
};
req.onreadystatechange = function () {
if (req.readyState === 4 && req.status === 200) {
resp = req.responseText;
console.log("response text - " + resp);
}
console.log(req.readyState + " " + req.status + " " + c);
};
req.open("POST", url, true);
req.setRequestHeader("Content-Type", "application/json");
req.send(payload);
}

Related

Ajax doesn't fire onreadystatechange

I know the URL is working as intended as i logged that to the console and it is fine. However I can't get "Good News" to log to the console when readyState == 4 and status == 200. I tried removing readState and it still wouldn't log. I tried logging the status and It would only fire once with a value of 0. This is the first time I am working with Ajax so any help is appreciated.
function setupRequest(){
var bttn = document.querySelector('#send');
bttn.addEventListener('click', sendData)
}
setupRequest();
function sendData () {
console.log('ran')
var url = 'localhost/bev/drinks.php';
var data = document.getElementById('input').value;
url += '?' + 'alcohol=' + data;
console.log(url)
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log('good news')
console.log(this.responseText)
} else {
console.log(this.status)
}
}
request.open('GET', url, true);
request.send;
console.log('sent')
}
You need to actually call send(). You aren't doing anything whenever you say request.send;
function setupRequest() {
var bttn = document.querySelector('#send');
bttn.addEventListener('click', sendData)
}
setupRequest();
function sendData() {
console.log('ran')
var url = 'https://jsonplaceholder.typicode.com/posts';
var data = document.getElementById('input').value;
//url += '?' + 'alcohol=' + data;
console.log(url)
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log('good news')
console.log(this.responseText)
} else {
console.log(this.status)
}
}
request.open('GET', url, true);
// You wrote (without parentheses):
///////////////////
// request.send; //
///////////////////
// You need to write
request.send();
console.log('sent')
}
<button type="button" id="send">Btn</button>
<input type="text" id="input">

Query Parameters twitch API

This query works, but i want to add some optionnals parameters.
Alert.prototype.getUserFollowedChannels = async function (user) {
return new Promise((resolve, reject) =>{
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.twitch.tv/kraken/users/' + user+ '/follows/channels?client_id=' + this.clientId, true);
//xhr.open('GET', 'https://api.twitch.tv/kraken/users/' + user+ '/follows/channels?client_id=' + this.clientId+'?limit=100', true); // try with what i want
xhr.onreadystatechange = function () {
if (xhr.readyState != 4 || xhr.status != 200) return;
var follows = JSON.parse(xhr.responseText);
if (follows) resolve(follows);
else resolve("none");
}
xhr.send();
})
}
There is the doc of my query : https://dev.twitch.tv/docs/v5/reference/users/#get-user-follows
You can use something like query-string

Update DOM object in time intervals using JavaScript Worker

I'm trying to do some DOM objects updates in background.
What I mean is update tab title, and some elements regardless if user has tab active or not ( to show that there are new notifications )
I already found out, that Worker has to be used as it runs in background ( but don't have access to DOM). Tried as follows:
Main HTML:
...some html
<script>
$(document).ready(function ($) {
if (window.Worker) {
console.log('[DEBUG] Worker is supported')
var eventsWorker = new Worker("<c:url value="/resources/js/eventTimer.js" />");
setInterval(eventsWorker.postMessage([appUrl]), 20 * 1000);
//setEventsNonWorker()
eventsWorker.onmessage = function (e) {
console.log('Message received from worker' + e.data);
setEventsCount(e.data, appName, eventsTxt);
}
} else {
console.log('[DEBUG] Worker is NOT supported')
setEventsNonWorker()
}
});
function setEventsNonWorker(){
//regular update with setTimout and stuff
}
worker javascript file
function setEventsCount(count, appName, eventsTxt) {
var bell, text, countPar;
if (count > 0) {
bell = '<i class="fa fa-bell"></i> ';
countPar = '(' + count + ') ';
text = bell + eventsTxt + countPar;
$(".event-menu-li").html(text);
$("#event-menu-icon").html(bell + count)
document.title = countPar + appName;
} else {
bell = '<i class="fa fa-bell-o"></i> ';
text = bell + eventsTxt;
$(".event-menu-li").html(text);
$("#event-menu-icon").html(bell)
document.title = appName;
}
}
onmessage = function (e) {
var appUrl = e.data[0];
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === XMLHttpRequest.DONE && xmlhttp.status === 200) {
postMessage(xmlhttp.responseText);
}
};
xmlhttp.open("GET", appUrl, true);
xmlhttp.send();
}
The first call is working ( the event count is properly set ) but there are no more calls in 20 sec
Ok it turns out I was putting timeout in wrong place
html should be
//...
eventsWorker.postMessage([appUrl]);
eventsWorker.onmessage = function (e) {
console.log('Message received from worker' + e.data);
setEventsCount(e.data, appName, eventsTxt);
//...
which will just init worker , while worker.js should have the timeout
//...
onmessage = function (e) {
var appUrl = e.data[0];
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === XMLHttpRequest.DONE && xmlhttp.status === 200) {
postMessage(xmlhttp.responseText);
}
};
xmlhttp.open("GET", appUrl, true);
xmlhttp.send();
setInterval(function () {
xmlhttp.open("GET", appUrl, true);
xmlhttp.send();
}, 20*1000);
}

Can't get weather asynchronously using openweathermap API

I'm trying to retrieve data using the openweathermap API. I can get it to work, but I can't seem to do it asynchronously. This causes the following error:
Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
Form:
<label>Zipcode: </label>
<form>
<input type="text" id="locationField" name="locationField">
<input type="submit" id="weatherSubmit" value="Get Weather">
</form>
<div>
<br>
<label>Location:</label>
<div id="location"></div>
<br>
<label>Temperature:</label>
<div id="temperature"></div>
<br>
<label>Humidity</label>
<div id="humidity"></div>
</div>
Script:
document.getElementById('weatherSubmit').addEventListener('click', function(event) {
var zipcode = document.getElementById('locationField').value;
var req = new XMLHttpRequest();
var payload = {location: null, temperature:null, humidity:null};
req.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=" + zipcode + ",us&appid=fa7d80c48643dfadde2cced1b1be6ca1", true);
req.setRequestHeader('Content-Type', 'application/json');
req.addEventListener('load',function(){
if(req.status >= 200 && req.status < 400){
var response = JSON.parse(req.responseText);
document.getElementById('location').textContent = response.name;
document.getElementById('temperature').textContent = response.main.temp;
document.getElementById('humidity').textContent = response.main.humidity;
} else {
console.log("Error in network request: " + request.statusText);
}});
req.send(JSON.stringify(payload));
event.preventDefault();
});
I can get this to work if I don't use AJAX, but that's not the way I want to do it. The following code works if foo() is called onclick from the submit button and passes in the zip code value.
function foo(value) {
var req = new XMLHttpRequest();
req.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=" + value + ",us&appid=fa7d80c48643dfadde2cced1b1be6ca1", false);
req.send(null);
var response = JSON.parse(req.responseText);
document.getElementById('location').textContent = response.name;
var f = ((response.main.temp - 273.15) * 9 / 5) + 32;
document.getElementById('temperature').textContent = f + "f";
document.getElementById('humidity').textContent = response.main.humidity + "%";
}
Get rid of the setRequestHeader
var req = new XMLHttpRequest();
var payload = {location: null, temperature:null, humidity:null};
req.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=02143,us&appid=fa7d80c48643dfadde2cced1b1be6ca1", true);
//req.setRequestHeader('Content-Type', 'application/json');
req.addEventListener('load',function(){
if(req.status >= 200 && req.status < 400){
var response = JSON.parse(req.responseText);
console.log(response);
//document.getElementById('location').textContent = response.name;
//document.getElementById('temperature').textContent = response.main.temp;
//document.getElementById('humidity').textContent = response.main.humidity;
} else {
console.log("Error in network request: " + request.statusText);
}});
req.send(null);
Works great!
BTW. Change your API key :(
It's a problem with CORS. The workaround is to use JSONP. It seems to be supported by OpenWeatherMap's API.
function foo(value) {
window.weatherCallback = function(response) {
document.getElementById('location').textContent = response.name;
var f = ((response.main.temp - 273.15) * 9 / 5) + 32;
document.getElementById('temperature').textContent = f + "f";
document.getElementById('humidity').textContent = response.main.humidity
delete window.weatherCallback; // delete the property
};
var script = document.createElement('script');
script.src = '//api.openweathermap.org/data/2.5/weather?q=" + value + ",us&appid=fa7d80c48643dfadde2cced1b1be6ca1&callback=weatherCallback';
document.head.appendChild(script);
}
Can't test it though, as I don't have the key for API.

jquery to javascript converted but not working

my initial code was in jquery + ajax and i tried to write it in javascript but its not working now. Can anyone tell me where's the mistake and why its not showing anything when i run through the server? i checked in the console and there is no error either
my code in JQ
$(document).ready(function(){
findteacher = function() {
var file = "course.php?course="+ $("#course").val();
$.ajax({
type : "GET",
url : file,
datatype : "text",
success : function(response) {
var file2 = response.split(",");
$("#courseInfo").html("The course: " + file2[0] + " Taught by: " + file2[1]);
}
});
}
clear = function() {
$("#courseInfo").html("");
};
$("#course").click(clear);
$("#go").click(findteacher);
});
My code in JS
function findteacher () {
var file = "course.php" + document.getElementById('course');
function callAjax(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById('courseInfo').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", file, true);
xmlhttp.send(null);
var file2 = callAjax.split(",");
document.getElementById('courseInfo').text("The course: " + file2[0] + " Taught by: " + file2[1]);
}
document.getElementById('go').onclick(findteacher)
}
window.onload = findteacher;
You're missing ?course= in file. You're not getting .value of the course element. callAjax.split(",") makes no sense -- callAjax is a function, not a string -- you should be using xmlhttp.responseText.split(",") in the onreadystatechange function. onclick is a property you assign to, not a method, so .onclick(findteacher) should be onclick = findteacher; and you shouldn't do this inside the function, it should be done just once when the page is loaded.
function findteacher () {
var file = "course.php?course=" + document.getElementById('course').value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
var file2 = xmlhttp.responseText.split(",");
document.getElementById('courseInfo').innerHTML = "The course: " + file2[0] + " Taught by: " + file2[1];
}
}
xmlhttp.open("GET", file, true);
xmlhttp.send(null);
}
function clear () {
document.getElementById('courseInfo').innerHTML = '';
}
window.onload = function() {
document.getElementById('go').onclick = findteacher;
document.getElementById('course').onclick = clear;
}

Categories

Resources