rewriting a function to a boolean - javascript

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()

Related

After authenticating via POST, I need to do a GET using Ajax

I'm attempting to create a dashboard that logs into an API then refreshes certain data elements that is fully automated. I can login and authenticate but after googling unsure how to 'chain' the GET request after the 'POST'
I've tried watching a few youtube tutorials and creating functions, attaching them to buttons and divs but I just can't get the data to display. The first batch of code completes and logs in OK, but then sits there and times out. I tried just adding a second open and making the login synchronous but it failed
<script type="text/javascript">
const xhr = new XMLHttpRequest();
var data = 'username=user&password=password';
xhr.onreadystatechange = function()
{
if (xhr.readyState == "4")
{
if (xhr.status == "200")
{
console.log(xhr.responseText);
}
if (xhr.status = "404")
{
console.log("FnF");
}
}
}
xhr.open('post','https://apiServer:8443/api/login', true)
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
xhr.setRequestHeader("Accept", "application/xml")
//xhr.open('get', 'https://apiServer:8443/api/resource/items', true);
xhr.send();
I'm expecting the login to be done behind the scenes and not visible, and just have the GET request show data in a div (I'll try and tidy up the xml response when I get the data working first).
In your code you never use your data variable :
const xhr = new XMLHttpRequest();
var data = 'username=user&password=password';
xhr.onreadystatechange = function()
{
if (xhr.readyState == "4")
{
if (xhr.status == "200")
{
console.log(xhr.responseText);
}
if (xhr.status = "404")
{
console.log("FnF");
}
}
}
xhr.open('post','https://apiServer:8443/api/login', true)
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
xhr.setRequestHeader("Accept", "application/xml")
//xhr.open('get', 'https://apiServer:8443/api/resource/items', true);
xhr.send(data); // <====== HERE

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

Async request with status = 0

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

Signature does not match s3 GET object

I have an image in the amazon s3 which has ACL of autherized-users. I'm trying to retrieve that image with GET method. The javascript method (in angular js) looks like this
(In the following example, response contains the necessary data such as authHeader)
var uri = 'https://sample.s3.amazonaws.com/sample/image.jpg';
var postParams = response.data;
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", downloadComplete, false);
xhr.addEventListener("error", downloadFailed, false);
xhr.addEventListener("abort", downloadCanceled, false);
function downloadComplete(e) {
var xhr = e.srcElement || e.target;
if(xhr.status === 200) { //success status
}
else {
}
}
function downloadFailed(e) {
debugger;
}
function downloadCanceled(e) {
debugger;
}
xhr.open('GET', uri, true);
xhr.setRequestHeader('Authorization', postParams.authHeader);
xhr.setRequestHeader('x-amz-content-sha256', postParams.payloadHash);
xhr.setRequestHeader('Host', "sample.s3.amazonaws.com");
xhr.setRequestHeader('x-amz-date', postParams.date);
xhr.send();
But I get a 403 exception which says SignatureDoesNotMatch. Is there anything i'm doing wrong? I'm quite sure that the values i'm providing are correct.
Thanks in advance

Ajax call not successful

I am making a javascript function call on onclick of any checkbox like this:
function getPGCountList(pageNo) {
var url = "someJsp.jsp?" + pageNo;
alert(1);
if (window.XMLHttpRequest) {
alert(2);
xmlhttp = new XMLHttpRequest();
} else {
alert(3);
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
alert(4);
xmlhttp.onreadystatechange = function () {
alert(5);
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(6);
document.getElementById("searchForPage").innerHTML = xmlhttp.responseText;
}
};
alert(7);
xmlhttp.open("GET", url, true);
alert(8);
xmlhttp.send();
}
The alert output I am getting is at my hosted site:
1-2-4-7-5-8-5-5-5
But in my local system it is:
1-2-4-7-5-8-5-5-5-6
I need to execute alert 6 also to change the content.
I am not sure where is the problem?
Your code looks fine to me. Check the path to someJsp.jsp
It's obviously not returning a normal response from the ajax call otherwise it would enter your if block and fire alert 6.
Just a thought too, but if you alert xmlhttp.readyState and xmlhttp.status maybe it'll help you find your problem. IF they are undefined, or refer to an object that is undefined, then your new XMLHttp requests failed. IF they give you results, you can see what the responses mean

Categories

Resources