I am trying to make an XMLHttpRequest, however, I am having issues. The page keeps refreshing automatically even when returning false or using e.preventDefault(). I'm trying to get cities to eventually pass through an options block. (I've started the option section and will complete it after I figure out the get request issue.) I'm trying to do this using pure Javascript because I've already done it using Angular and Node. Any help would be appreciated.
HTML:
<form id="citySearchForm" method="get" onSubmit="return searchFormFunc();">
<div>
<p>Choose a city:</p>
<input type="text" placeholder="Enter a city" id="getCitiesInput" name="city">
<input type="submit" value="submit">
</div>
<div id="weather"></div
<p><span id="temp"></span></p
<p><span id="wind"></span></p>
</form>
Javascript:
var citySearch = document.getElementById("citySearchForm");
// citySearch.addEventListener("submit", searchFormFunc);
function searchFormFunc(e){
cityName = document.getElementById('getCitiesInput').value;
var searchCityLink = "http://autocomplete.wunderground.com/aq?query=";
var search = searchCityLink.concat(cityName);
console.log("link : " + search);
var xhr = XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
var r = JSON.parse(xhr.response || xhr.responseText); // IE9 has no property response, so you have to use responseText
console.log(r);
} else {
console.log('error');
}
};
xhr.open("GET", link, true);
xhr.send(null);
var r = JSON.parse(xhr.response);
return false;
// e.preventDefault();
}
You are specifying that you want this to be an async request. So you need to parse your response inside of the onreadystatechange or onload.
function ajax(url, callback) {
var xhr;
if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
else {
var versions = ["MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"]
for(var i = 0, len = versions.length; i < len; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
}
catch(e){}
} // end for
}
/** Here you can specify what should be done **/
xhr.onreadystatechange = function() {
if(xhr.readyState < 4) {
return;
}
if(xhr.status !== 200) {
return;
}
// all is well
if(xhr.readyState === 4) {
callback(xhr);
}
}
xhr.open('GET', url, true);
xhr.send('');
}
Answer from documentation by user6123921
You have to use var xhr = new XMLHttpRequest();
you have to define an onreadystatechange event listener
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
var r = JSON.parse(xhr.response || xhr.responseText); // IE9 has no property response, so you have to use responseText
console.log(r);
/* do stuff with response */
}
};
Related
I know this question has been asked before, but I tried to apply the answers with no results.
I'm trying to do multiple requests on the same domain with a for loop but it's working for the entire record of my array.
Here is the code I use:
function showDesc(str) {
var prod = document.getElementsByName("prod_item[]");
var xhr = [], i;
for (i = 0; i < prod.length; i++) {
var txtHint = 'txtHint10' + i;
(function(i) {
var xhr = new XMLHttpRequest();
var url = "getDesc.php?q=" + str;
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById(txtHint).innerHTML = xhr.responseText;
}
};
xhr.open("GET", url, false);
xhr.send();
})(i);
}
}
PHP
<select name="prod_item[]" id="prod_item.1" onchange="showDesc(this.options[this.selectedIndex].value)"></select>
<div id="txtHint100"></div>
and then I will use dynamic table for the prod_item field and div_id.
Is there any mistake in my code?
The issue I'm having is that I have a dynamic API call whose url changes everytime. So In order to get the proper URL I have to get the text on the page and parse it so it only the first part of the text, then concatenate that to the first part of the URL. When I try to pass the string to the async script it keeps coming up as undefined. How can I get the string into the async script?
Specifically get the string to this line of code:
xhr.open("GET", APIcall, true);
var ID = element(by.css(".sometext")).getText().then(function(getFirstPartOfText) {
//console.log(ID);
var thing = getFirstPartOfText
var thing2 = getFirstPartOfText.toString().split(" ");
var thing3 = thing2[0];
var API = "https://someAPIcall/read/";
APIcall = API + thing3;
return APIcall;
}).then(function(APIcall){
console.log(APIcall);
browser.executeAsyncScript(function(ApiCall) {
var callback = arguments[arguments.length - 1];
var xhr = new XMLHttpRequest();
xhr.open("GET", APIcall, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
callback(xhr.responseText);
}
};
xhr.send('');
}).then(function(str) {
console.log(str);
//var whatINeed = JSON.parse(str);
var ID = element(by.css(".sometext")).getText().then(function(getFirstPartOfText) {
// this is synchronous, so there's no need to chain it using .then()
var thing = getFirstPartOfText
var thing2 = getFirstPartOfText.toString().split(" ");
var thing3 = thing2[0];
var API = "https://someAPIcall/read/";
APIcall = API + thing3;
return APIcall;
});
call_something(ID); // ID should be set at this point.
function call_something (APIcall) {
console.log(APIcall);
browser.executeAsyncScript(function(ApiCall) {
var callback = arguments[arguments.length - 1];
var xhr = new XMLHttpRequest();
xhr.open("GET", APIcall, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
callback(xhr.responseText);
}
};
xhr.send('');
}).then(function(str) {
console.log(str);
}
}
There are multiple things going on here, first of all the callback in call_something is not required, you are still within webdriver's promise manager. So all you need to do is return the data for the next call chain. Also quote in xhr.send(''); inside the method are not required. All you need to do is call send() and JSON parse the response and return, the next then block should have the JSON result. If you are getting pure HTML, then make sure the URL is correct.
function call_something (APIcall) {
console.log(APIcall);
browser.executeAsyncScript(function(ApiCall) {
var xhr = new XMLHttpRequest();
xhr.open("GET", APIcall, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
return JSON.parse(xhr.responseText);
}
};
xhr.send();
}).then(function(str) {
console.log(str);
}
}
I was missing an extra parameter mentioned here
The first argument is a function which will be called
The second+ arguments will be passed as arguments to the function in the first argument.
var ID = element(by.css(".sometext")).getText().then(function(getFirstPartOfText) {
//console.log(ID);
var thing = getFirstPartOfText
var thing2 = getFirstPartOfText.toString().split(" ");
var thing3 = thing2[0];
var API = "https://someAPIcall/read/";
APIcall = API + thing3;
return APIcall;
}).then(function(APIcall){
console.log(APIcall);
browser.executeAsyncScript(function(ApiCall) {
var callback = arguments[arguments.length - 1];
var xhr = new XMLHttpRequest();
xhr.open("GET", APIcall, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
callback(xhr.responseText);
}
};
xhr.send('');
}, APIcall).then(function(str) {
console.log(str);
//var whatINeed = JSON.parse(str);
I want to show a random quote when a button is clicked. The project is here https://skidle.github.io/projects/random-quote. If you open a console, you can see that this onclick=newQuote() function is working because it generates an JSON object into a console. But the quote stays the same, so should I change the URL somehow?
JS:
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1");
xhr.send();
xhr.onreadystatechange = function () {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
var json = JSON.parse(xhr.responseText);
var elQuote = document.getElementById("quote");
elQuote.innerHTML = json[0]["content"];
var elAuthor = document.getElementById("author");
elAuthor.innerHTML = json[0]["title"];
console.log(json[0]);
} else {
console.log("Error: " + xhr.status); // An error occurred during the request.
}
};
}
var newQuote = function() {
//the script below is the same as above just inserted inside newQuote()
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1");
xhr.send();
xhr.onreadystatechange = function () {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
var json = JSON.parse(xhr.responseText);
var elQuote = document.getElementById("quote");
elQuote.innerHTML = json[0]["content"];
var elAuthor = document.getElementById("author");
elAuthor.innerHTML = json[0]["title"];
console.log(json[0]);
} else {
console.log("Error: " + xhr.status); // An error occurred during the request.
}
};
}
}
HTML:
<main>
<div class="container">
<div class="wrapper">
<section id="quote">
</section>
<div class="button-wrapper">
<button>Tweet this</button>
<div id="author"></div>
<button onclick="newQuote()">New quote</button>
</div>
</div>
</div>
</main>
Thank you in advance!
I think that the ajax request is beeing cached. Try adding a timestamp to the url, like this:
xhr.open("GET", "https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1×tamp="+new Date());
I need to simulate an authenticated user to pull a JSON file. I am using Last.fm's API, but there is currently no method to pull the specific data I want. If I just pull it as plain text in browser, it shows up. However, I want data that is specific to an authenticated user. So, if I login to Last.fm as me, then pull the data, the data is different than if I just pull the data from anywhere.
Basically, the data contained in this file is specific to the user, and as there is no function specifically set to access this file, I don't know how I'd do that....
My function that pulls the current data is listed below:
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
function getRadio() {
var trackUrls = new Array();
var resValue;
var station;
var radioStation;
var url;
var data;
var neatDisplay;
var resultsDisplay = document.getElementById('result');
var radioTypeInput = document.getElementsByName('radioType');
var queryInput = document.getElementById('query');
var query = queryInput.value;
for (var i = 0, length = radioTypeInput.length; i < length; i++) {
if (radioTypeInput[i].checked) {
station = radioTypeInput[i].value;
break;
}
}
if (station == 1) {
radioStation = "recommended";
} else if (station == 2) {
radioStation = "library";
} else if (station == 3) {
radioStation = "mix";
} else {
radioStation = "music";
};
if (radioStation != "music") {
url = "https://crossorigin.me/" + "http://www.last.fm/player/station/user/" + query + "/" + radioStation;
} else {
url = "https://crossorigin.me/" + "http://www.last.fm/player/station/music/" + query;
};
console.log(url);
request = createCORSRequest("get", url);
if (request) {
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
data = JSON.parse(request.responseText);
for (i = 0; i < data.playlist.length; i++) {
trackUrls[i] = data.playlist[i].playlinks[0].url;
}
neatDisplay = trackUrls.join("\n ");
resultsDisplay.innerHTML = neatDisplay;
console.log(neatDisplay.toString());
neatDisplay = neatDisplay.toString();
return neatDisplay.toString();
} else if (request.status == 503) {
resultsDisplay.innerHTML = "Connection Error. The application may be overloaded."
} else {}
};
request.onerror = function() {
document.getElementById("result").innerHTML = "Connection Error. The application may be overloaded. Try again later"
};
request.send();
}
}
Ultimately, this used to pull Spotify links in the resulting data, but now it pulls YouTube. So, the problem only occurs if just pulling the file, without authentication.
I recently got a website aired and am having trouble getting the chat to work without having to have the user refresh the page (hence, the ajax). But the person on the other end still has to refresh in order to see the latest message. We're in the same room, so I can see if the chat refreshes or not; it doesn't, and here's the code
<script type="text/javascript">
var scroller = function(){
posts = document.getElementById("posts");
posts.scrollTop = posts.scrollHeight;
}
var menu = 3;
var checksum = function(){
if (menu == 3){
document.getElementById('smileys').style.display="block";
document.bob.smileyhider.innerHTML="−";
menu=1;
}
else {
document.getElementById('smileys').style.display="none";
document.bob.smileyhider.innerHTML="+";
menu=3;
}
}
//Chat ajax loader
var updater = 10;
function update(){
var xhr;
if(updater < 200){ updater = 200 }
if (window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }
else { xhr = new ActiveXObject('Microsoft.XMLHTTP'); }
xhr.onreadystatechange = function(){
if (xhr.readyState==4 && xhr.status == 200){
document.getElementById('posts').innerHTML = xhr.responseText;
}
}
setTimeout(update, (++updater)*10);
xhr.open("GET","chatlog<?php echo date("d");?>.log",true);
xhr.send(null);
}
</script>
You are never actually calling update to kick off the ajax requests. I wouldn't nest it either
You want to use setInterval instead. setTimeout will only run once.
I would just use a static value for updater, like 3 seconds
/
var updater = 3000;
function update(){
var xhr;
if(updater < 200){ updater = 200 }
if (window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }
else { xhr = new ActiveXObject('Microsoft.XMLHTTP'); }
xhr.onreadystatechange = function(){
if (xhr.readyState==4 && xhr.status == 200){
document.getElementById('posts').innerHTML = xhr.responseText;
}
}
xhr.open("GET","chatlog<?php echo date("d");?>.log",true);
xhr.send(null);
}
setInterval(update, updater);