Ajax doesn't fire onreadystatechange - javascript

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">

Related

How to pass a string in url in Javascript?

I'm trying to make an application that accesses different sites inside of an iframe from a private JSON dns server.
I have completed the main code, but now I am trying to make it able to be accessed through the url. (Ex. https://thissite.info?url='test.json'&dnsserver='https://thissite.info')
I also want it to default to a value if the variable is not defined in the url. For this, I'm using the following code:
function setup(){
var dns = document.getElementById("dns");
var urlbar = document.getElementById("urlbar");
var frame = document.getElementById("viewport");
if (typeof url === "undefined") {
url = 'Welcome Page URL Here';
} else {
urlbar.value = url;
}
if (typeof dnsserver === "undefined") {
dnsserver = 'Default Server Here';
} else {
dns.value = dnsserver;
}
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
console.log(this.status)
if(this.readyState == 4 && this.status == 200){
var response = JSON.parse(this.responseText);
frame.src=response;
console.log("Request Completed with 200");
};
if(this.readyState == 4 && this.status == 404){
console.log("Website Not Found");
frame.src='404.html'
};
}
xmlhttp.open("GET",dnsserver + url + '.json', true);
xmlhttp.send();
console.log("Request Sent");
}
But even if I pass the vars in the URL, it doesn't accept it.
<script type="text/javascript"> $(function () { $("#btnQueryString").bind("click", function () { var url = "Page2.htm?name=" + encodeURIComponent($("#txtName").val()) + "&technology=" + encodeURIComponent($("#ddlTechnolgy").val()); window.location.href = url; }); }); </script> <input type="button" id="btnQueryString

API not responding

The app that I'm working on does not respond with the API address. I only get the ajax responding, but not the weather api that I'm trying to call.
I've tried everything that I could think of with my current knowledge.
let search = document.getElementById("search-bar");
let temp = document.getElementById("temperature");
let input = document.getElementById("input");
let city = document.getElementById("city");
const key = "";
input.addEventListener("keyup", enter);
function enter(event) {
if (event.key==="Enter") {
details();
}
}
function details() {
if (searchInput.value === ""){
} else {
let searchLink = "https://api.openweathermap.org/data/2.5/weather?q={}" + searchInput.value + "&appid=" + key;
httpRequestAsync(searchLink, talk)
}
}
function talk(talking){
let jsonObject = JSON.parse(talking);
city.innerHTML = jsonOject.name;
temp.innerHTML = parseInt(parseInt(jsonObject.main.temp - 273) + "°");
}
function httpRequestAsync(url,callback){
var httpRequest=new XMLHttpRequest();
httpRequest.onreadystatechange = () => {
if (httpRequest.readyState == 4 && httpRequest.status == 200)
callback(httpRequest.responseText);
}
request.open("GET", url, true); // true for asynchronous
request.send();
}
The expected outcome should be the weather api being called and displayed information in the console.
Try replacing last function with this:
function httpRequestAsync(url,callback){
var httpRequest=new XMLHttpRequest();
httpRequest.onreadystatechange = () => {
if (httpRequest.readyState == 4 && httpRequest.status == 200)
callback(httpRequest.responseText);
}
httpRequest.open("GET", url, true); // true for asynchronous
httpRequest.send();
}
I just corrected variable naming

How do I make an HTTP request to bitstamp?

I'm trying to use an API from bitstamp to fetch a currency trading price on my webpage.
I have researched this problem, but I still cannot get it to work as it always returns ERROR
The link used is https://www.bitstamp.net/api/ticker/ and the response should be last
Here is my code:
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.bitstamp.net/api/ticker/", true);
xhr.send();
xhr.addEventListener("readystatechange", processRequest, false);
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
window.alert(response.last);
}
else {
window.alert("ERROR");
} }
Try this:
function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var jsonRes= JSON.parse(this.responseText);
if (jsonRes.hasOwnProperty('last')) {
document.getElementById("demo").innerHTML =
jsonRes.last;
alert(jsonRes.last);
}
}
};
xhttp.open("GET", "https://www.bitstamp.net/api/ticker", true);
xhttp.send();
}
<h2>Using the XMLHttpRequest object</h2>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
<p>last attribute is: <span id="demo"></span></p>
Here is one way:
<script src="./jquery.min.js">
//none secure web page ?
jQuery.get("https://www.bitstamp.net/api/ticker/", function (data, status)
{
// use response here; jQuery passes it as the first parameter
var response = JSON.parse(data);
window.alert(response.last);
console.log("MyFunc: " + "response : " + response + "\nStatus: " + status);
});
</script>
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.bitstamp.net/api/ticker/", true);
xhr.send();
xhr.addEventListener("readystatechange", processRequest, false);
function processRequest(e) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
window.alert(response.last);
} else {
window.alert("ERROR");
}
}
}

Loop Calling Function in Native Ajax

Here's my native ajax code:
function script_grabbed(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("numvalue").value = xmlhttp.responseText;
var result = document.getElementById("numvalue").value;
if (typeof result !== 'undefined'){
alert('Data Found:' + result);
//start: new request data for #valdata
xmlhttp.open("POST", "inc.php?q="+str, true);
document.getElementById("valdata").value = xmlhttp.responseText;
xmlhttp.send(null);
var dataval = document.getElementById("valdata").value;
if (typeof dataval !== 'undefined'){
alert('Data Bound:' + dataval);
//continue to call maps
script_dkill()
}
//end: new request data for #valdata
}
}
}
xmlhttp.open("POST", "inc_num.php?q="+str, true);
xmlhttp.send(null);
}
From the code, let me explain that:
I want to get data/value from result and dataval. After I get the data, I execute script_dkill() function.
However, It creates loop and never get to script_dkill.
So, the question is: How to get to script_dkill and execute it?
For example:
The script_dkill() has content as follow:
function script_dkill(){
alert('Hallo, you call me!');
}
Any help, please...
You need to use a different XMLHttpRequest object for the second request, since you are using the same object it will call the same onreadystatechange event again and again
function script_grabbed(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("numvalue").value = xmlhttp.responseText;
var result = document.getElementById("numvalue").value;
if (typeof result !== 'undefined') {
alert('Data Found:' + result);
//start: new request data for #valdata
var xmlhttp2 = new XMLHttpRequest();
xmlhttp2.onreadystatechange = function() {
if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
document.getElementById("valdata").value = xmlhttp2.responseText;
var dataval = document.getElementById("valdata").value;
if (typeof dataval !== 'undefined') {
alert('Data Bound:' + dataval);
//continue to call maps
script_dkill()
}
}
}
xmlhttp2.open("POST", "inc.php?q=" + str, true);
xmlhttp2.send(null);
//end: new request data for #valdata
}
}
}
xmlhttp.open("POST", "inc_num.php?q=" + str, true);
xmlhttp.send(null);
}

set time out in ajax call while using core javascript

I have a JavaScript function to call ajax. Now I need to add time out in this function like while calling service took more than defile time ajax call should time out and display a default message. I don't want to use Jquery in it.
here is my code:
AJAX = function (url, callback, params) {
var dt = new Date();
url = (url.indexOf('?') == -1) ? url + '?_' + dt.getTime() : url + '&_' + dt.getTime();
if (url.indexOf('callback=') == -1) {
ajaxCallBack(url, function () {
if (this.readyState == 4 && this.status == 200) {
if (callback) {
if (params) {
callback(this.responseText, params);
} else {
callback(this.responseText);
}
}
}
});
} else {
var NewScript = d.createElement("script");
NewScript.type = "text/javascript";
NewScript.src = url + '&_' + Math.random();
d.getElementsByTagName('head')[0].appendChild(NewScript);
}
},
ajaxCallBack = function (url, callback) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = callback;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
Here's an example of how you can handle a timeout:
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://www.example.com", true);
xmlHttp.onreadystatechange=function(){
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
clearTimeout(xmlHttpTimeout);
alert(xmlHttp.responseText);
}
}
// Now that we're ready to handle the response, we can make the request
xmlHttp.send("");
// Timeout to abort in 5 seconds
var xmlHttpTimeout=setTimeout(ajaxTimeout,5000);
function ajaxTimeout(){
xmlHttp.abort();
alert("Request timed out");
}
In IE8, You can add a timeout event handler to the XMLHttpRequest object.
var xmlHttp = new XMLHttpRequest();
xmlHttp.ontimeout = function(){
alert("request timed out");
}
Use a javascript framework to do this though, i don't know why you're not using one, do you like uneccesary work? :)
If you want to simply add timeout, You can add it in the first function in three places:
setTimeout(function() {callback(this.responseText, params)}, 1000)
And your callback will execute around 1s later. The second palce is second call of callback.
Third place that i would suggest is to wrap this function like above:
ajaxCallBack(url, function () {
if (this.readyState == 4 && this.status == 200) {
if (callback) {
if (params) {
callback(this.responseText, params);
} else {
callback(this.responseText);
}
}
}
});
Usually when i get in to testing internet connection i rather add throttling in the chrome developer tools like this:
Here is your code with first approach:
AJAX = function (url, callback, params) {
var dt = new Date();
url = (url.indexOf('?') == -1) ? url + '?_' + dt.getTime() : url + '&_' + dt.getTime();
if (url.indexOf('callback=') == -1) {
ajaxCallBack(url, function () {
if (this.readyState == 4 && this.status == 200) {
if (callback) {
if (params) {
console.log(new Date());
setTimeout(function() {callback(this.responseText, params)}, 2000);
} else {
console.error((new Date()).getSeconds());
setTimeout(function() {callback(this.responseText)}, 2000);
}
}
}
});
} else {
var NewScript = d.createElement("script");
NewScript.type = "text/javascript";
NewScript.src = url + '&_' + Math.random();
d.getElementsByTagName('head')[0].appendChild(NewScript);
}
},
ajaxCallBack = function (url, callback) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = callback;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
AJAX('http://ip.jsontest.com/', function() {console.error((new Date()).getSeconds()); });
Maybe the answer to this question will help.
Timeout XMLHttpRequest
since from what i understand you need to set timeout for xmlhttprequest,
you can use xmlhttp.timeout = /*some number*/

Categories

Resources