Async request with status = 0 - javascript

I have some issues with async requests. My website and api are on different ports, Access-Control-Allow-Origin header is set on API side correctly (because synchronious requests work just fine).
The following code always returns 'ERR'. I
function load() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://domain:8801/api/', true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status != 200) {
alert( "ERR" + " Status: " + xhr.statusText + " Response: "+xhr.responseText ); //always ERR in browser
}
else {
alert( "SUCCESS" );
}
}
};
xhr.send();
}

Set a listener for the returned async
function reqListener() {
console.log(this.responseText);
}
function load() {
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", reqListener);
xhr.open('GET', 'http://domain:8801/api/');
xhr.send();
}
Not putting in true/false makes it async by default
SO this is all wrong and the "submit" button is the issue - and the async operates differently - the sync waits for response, THEN submits while the async does not and it never returns prior to the submit action

Related

rewriting a function to a boolean

hi guys I have this function:
its checking if the image URL is an actual image, but I want to change it , instead of console log I want it to return true or false,
function checkImage(url) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.send();
request.onload = function() {
status = request.status;
if (request.status == 200) //if(statusText == OK)
{
console.log("image exists");
} else {
console.log("image doesn't exist");
}
}
}
checkImage("https://picsum.photos/200/300");
I want checkImage to return True/False instead of console logging, but when i write return true or false, that doesn't seem to work,
anyone knows why?
If the whole purpose of this function is to check if the image exists with the intent of displaying a default image I would use a much simpler approach. Why not use the following method:
<img src="imagenotfound.gif" alt="Image not found" onerror="this.src='imagefound.gif';" />
This is described at further length here
Just change the console to callback may help u solve it
function checkImg(url,success,error){
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.send();
request.onload = function() {
status = request.status;
if (request.status == 200) //.if(statusText == OK)
{
success && success()
} else {
error && error()
}
}
}
Replace the Ajax with Image.onload()

HTML5 java script XMLHttpRequest status 0 and responseText is empty

I am trying to call web service in html5 javascript. But XMLHttpRequest status value getting ZERO insted of 200 and responseText is empty. help me to solve the issue, My code below
<script type="text/javascript">
var xhr;
function Getdet()
{
try {
xhr = new XMLHttpRequest();
xhr.open('POST', "URL", true); // URL-->Webservice link
xhr.send();
xhr.addEventListener("readystatechange", processRequest, false);
xhr.responseType = 'json';
}
catch(err)
{
alert(err.message);
}
}
function processRequest(e) {
try{
var prn=JSON.stringify(e);
alert("xhr.readyState-->"+xhr.readyState);
alert("xhr.status-->"+xhr.status);
alert("xhr response-->"+ xhr.response);
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
alert(response.ip);
}
}
catch(err)
{
alert(err.message);
}
}
}
</script>

AJAX XHR request onReadyStateChange events order and number of times clarification

I'm learning and trying to write a simple stock quote tool using Python-Flask and Javascript.
I specifically want to learn plain Javascript. My code is working, but what I don't understand is when I'm watching the developer console, I get 3 error messages printed before I get the successful console.log(response).
Is it simply that the code loops 3 times before the response comes back, so it logged 'ERROR' each of those times before finally returning the 200 status? Would someone explain it to me or point me to a good article/post?
My event listener:
document.getElementById("btn_quote").addEventListener("click", getQuote);
The ajax call:
function getQuote(e){
e.preventDefault();
var ticker = document.getElementById("ticker").value
var shares = document.getElementById("shares").value
var url = "/quote/"+ticker+"/"+shares
// Fetch the latest data.
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status === 200) {
var response = JSON.parse(request.response);
console.log(response);
}
} else {
// TODO, handle error when no data is available.
console.log('ERROR');
return false;
}
};
request.open('GET', url);
request.send();
}
It's not returning separate HTTP status codes, its returning different ready states.
Change your console.log("ERROR");. To console.log(request.readyState);.
Then you will see what it is reporting and why.
i think you should be checking your readyState values with the actual values of the response. For you reference, following are the possible values of readyState:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
So you could basically check it to be 4 in your case:
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === 4) {
//response statements
} else {
//error statements
}
};
Basically, ajax calls will get notified for the following events which is called as readyStateChange event.
For most cases, you used to get 4 ready state changes based on the speed of the connection (rare cases only only one if it's very quick) and you should check whether it is 4 which means the response is completed now.
To check whether the request is suceess or not, you should check the request.status === 200 which means success and can check for other http status code for errors like 404, 500 etc.
document.getElementById("btn_quote").addEventListener("click", getQuote);
document.getElementById("btn_quote_error").addEventListener("click", getQuoteError);
function getQuote(e){
e.preventDefault();
var ticker = document.getElementById("ticker").value;
var shares = document.getElementById("shares").value;
//var url = "/quote/" + ticker + "/" + shares;
var url = 'http://stackoverflow.com/';
// Fetch the latest data.
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
console.log(request.readyState);
if (request.readyState === XMLHttpRequest.DONE) {
console.log(request.status);
if (request.status === 200) {
//var response = JSON.parse(request.response);
//console.log(response);
}
}
//else {
// TODO, handle error when no data is available.
//console.log('ERROR');
//return false;
//}
};
request.open('GET', url, true);
request.send();
}
function getQuoteError(e){
e.preventDefault();
var ticker = document.getElementById("ticker").value;
var shares = document.getElementById("shares").value;
//var url = "/quote/" + ticker + "/" + shares;
var url = 'http://stackoverflow404.com/';
// Fetch the latest data.
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
console.log(request.readyState);
if (request.readyState === XMLHttpRequest.DONE) {
console.log(request.status);
if (request.status === 200) {
//var response = JSON.parse(request.response);
//console.log(response);
}
}
//else {
// TODO, handle error when no data is available.
//console.log('ERROR');
//return false;
//}
};
request.open('GET', url, true);
request.send();
}
<input type="text" id="ticker"/>
<input type="text" id="shares"/>
<input type="button" id="btn_quote" value="Get Quote" />
<input type="button" id="btn_quote_error" value="Get Quote Error" />

Detect browser tab close without jquery and send some data to php file

I have wrote a script that send some data to an external php file without jquery.
<script type="text/javascript">
var statsPage = 'http://www.my-url.com/response.php';
function ca(c,o,n,t,e,t,u){return p={type:c,userid:o,gender:n}}
ca("pageview", "1", "male");
var params = Object.keys(p).map(function(k) {
return encodeURIComponent(k) + '=' + encodeURIComponent(p[k])
}).join('&')
const req = new XMLHttpRequest();
//req.addEventListener('load' /*callback after req is complete*/);
req.open('GET', statsPage + '?' + params);
req.send();
req.onreadystatechange = function() {
if (req.readyState == XMLHttpRequest.DONE) {
alert(req.responseText);
}
}
</script>
What i also want to do is to send data when the browser tab is closed, so i wrote a script like below but it is not working. I don't get a response from the php file here.
navigator.sendBeacon = navigator.sendBeacon || function () {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.my-url.com/response.php?pag_title=1');
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert(xhr.responseText);
}
}
};
I found also this script but it gives me also no response from the response.php file as an alert:
window.onbeforeunload = function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.my-url.com/response.php?pag_titel=1', true);
// If specified, responseType must be empty string or "text"
xhr.responseType = 'test';
xhr.onload = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
//console.log(xhr.response);
//console.log(xhr.responseText);
alert(xhr.responseText);
}
}
};
xhr.send(null);
}
EDIT
I did also the following test but now it gives me an alertbox with the value 1 first and then an alert with the response of the function ca (see first part of the code on top for the function). So i think the onbeforeunload is not working here. If i close browser tab i get nothing in response.
window.onbeforeunload = function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.digital-productions.be/dev/analytics/response.php?pag_titel=1', true);
// If specified, responseType must be empty string or "text"
xhr.responseType = 'test';
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert(xhr.responseText);
}
}
xhr.send(null);
}
You can use the beforeunload event to execute code before the user leaves the page, or you could warn them that there is unsaved changes. You can return a message by using e.returnValue = "Message";.
window.addEventListener("beforeunload", function(e) {
//code
});
Here is a link from the mozilla documentation: https://developer.mozilla.org/en/docs/Web/Events/beforeunload

Can't receive in javascript XMLHttpRequest response from java server

Here is my code in javascript
<script type="text/javascript">
startingListener();
function startingListener() {
setInterval(function(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:32081/", false);
xhr.send();
var result = xhr.response;
console.log(result);
}
}, 100);
}
</script>
And my server on Java
public static void main (String... args) throws IOException, Exception {
String clientSentence;
ServerSocket welcomeSocket = new ServerSocket(32081);
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
PrintWriter outToClient = new PrintWriter(connectionSocket.getOutputStream(), true);
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
System.out.println("begin");
outToClient.println("fu");
System.out.println("Received: done");
}
}
I just want to receive answer string in JS and work with it further.
So when I run server and run JS, they connected and I received in IDE send() from JS
After that I saw in console of Java that begin and done received, but in browser console I didn't see any answer and script just handled. What do I do wrong?
Thank you for your help
Your client code is missing a state change handler and using setInterval with 100 ms it is very heavy on the server. Here is a better JS. Your JAVA issue is another problem. Downvoters: Do comment
function listener() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:32081/", false);
xhr.onreadystatechange = function () {
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log(xhr.responseText);
}
}
}
listener();
If you want to call listener repeatedly, you can do
function listener() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:32081/", false);
xhr.onreadystatechange = function () {
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
if (xhr.responseText != "done") {
console.log("server still busy");
setTimeout(listener,1000); // repeat the call
}
else {
console.log("finally done");
}
}
}
}

Categories

Resources