I have question about chechking file exists.
I have this piece of code.
function fileExists(url) {
if (url) {
var req = new XMLHttpRequest();
req.open('GET', url, false);
req.send();
console.log("exists");
return true;
} else {
console.log("no exists");
return false;
}
}
But it says me that file is exists. But it doesn't exists. In fact on my URL is 404 error XML file. Is possible somehow detect if requested URL is JSON? I need to return true only if checked file is JSON.
Thank you
Since this is a synchronous request, you can just try to parse the responseText you get back and if it fails to parse, you know it's not JSON:
var res = req.responseText;
try {
res = JSON.parse(res);
console.log('json', res);
} catch (e) {
console.log('not json')
}
If it were not a synchronous request, this would work:
If you look at the XMLHttpRequest docs, you'll see that in order to receive data back from an XMLHttpRequest, you need to add a callback function:
xhr.onreadystatechange = function() {//Call a function when the state changes.
if(this.readyState == XMLHttpRequest.DONE && this.status == 200) {
// Request finished. Do processing here.
}
}
If you wanted to check if your request is JSON, you could do this:
xhr.onreadystatechange = function() {//Call a function when the state changes.
if(this.readyState == XMLHttpRequest.DONE && this.status == 200) {
var res = this.responseText;
try {
JSON.parse(res);
console.log('json', res);
} catch (e) {
console.log('not json')
}
}
}
Related
I generally have been using XMLHttpRequest to perform Ajax calls. However, when the server has an error, I'd like to console.log the error so that I don't have to run to the server to see the event log there.
Here's what I generally do:
function LoadPage(){
var parameters="this=that";
var x = new GetXmlHttpObject();
x.open("POST", "Ajax.aspx?Function=LoadPage")
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
x.ontimeout = function () { location.reload(true); }
x.send(parameters);
x.onreadystatechange = function () {
if (x.readyState === 4 && x.status === 200){
//Do Stuff with the response
}
}
But if the server has an error with the request, I get the error on the x.send(parameters) line. I've tried to wrap that in a try..catch, but the error comes up in the console even with the command held inside the try.
How can I console.log the 500 errors from the server using this structure?
But if the server has an error with the request, I get the error on the x.send(parameters) line.
That won't happen. The client can't react to the response in any way before the response has arrived.
I've tried to wrap that in a try..catch
That won't work for two reasons.
It is asynchronous
It doesn't throw an exception
if (x.readyState == 4 && x.status == 200){
You're already testing for a 200 status here. Test for a 500 status in the same way.
Updated function
function LoadPage() {
return new Promise(function(succeed, fail) {
var req = new XMLHttpRequest();
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.open("POST", "Ajax.aspx?Function=LoadPage", true);
req.ontimeout = function () { location.reload(true); }
req.addEventListener("load", function() {
if (req.status < 400)
succeed(req.responseText);
else if (req.status == 500)
fail("Error 500: Internal Server Error");
else
fail(new Error("Request failed: " + req.statusText));
});
req.addEventListener("error", function() {
fail(new Error("Network error"));
});
req.send("this=that");
});
}
Usage:
LoadPage().then(function(text) {
console.log("data.txt: " + text);
}, function(error) {
console.log("Failed to fetch data.txt: " + error);
});
I know I could just do this with a global, but I'd like to be object oriented if I can. If my request response returns a false for that 'ok' value, I'd like to log the data that was originally posted. Is that data accessible by a listener function on the request object?
Thanks!
function reqListener () {
var data = this.responseText;
var jsonResponse = JSON.parse(data);
if (jsonResponse['ok'] == false) {
//Here I want to log the data that I originally posted
console.log(__TheFormDataThatWasPassedtoSend__);
}
}
var xhr = new XMLHttpRequest();
xhr.addEventListener("load",reqListener);
xhr.open('POST',urltopostto, true);
// Set up a handler for when the request finishes.
xhr.onload = function () {
if (xhr.status === 200) {
// File(s) uploaded.
console.log('Uploaded');
} else {
alert('An error occurred!');
}
};
xhr.send(formData);
So the problem you have is needing to use data known when you create the eventListener when the eventListener actually fires. Below is your code to do this with formData
function reqListener (formData) {
var data = this.responseText;
var jsonResponse = JSON.parse(data);
if (jsonResponse['ok'] == false) {
console.log(formData);
}
}
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", function() { reqListener.call(this,formData) });
xhr.open('POST',urltopostto, true);
// Set up a handler for when the request finishes.
xhr.onload = function () {
if (xhr.status === 200) {
// File(s) uploaded.
console.log('Uploaded');
} else {
alert('An error occurred!');
}
};
xhr.send(formData);
I'm checking if a file at a certain local URL exists via a XMLHttpRequest, kind of a workaround peek at the filesystem. Using the pingFile function described below, I try to see if I get a 200 or 404 for a given file and perform some actions depending on that result.
function pingFile(theURL, callback)
{
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (this.readyState === this.DONE) {
if (callback !== null) {
return callback(this.status);
} else {
return this.status;
}
}
};
req.open("HEAD", theURL);
req.send();
}
var q = pingFile('images/image1.png', null);
However, when I check the value of q, it is always undefined. I'm missing something about the asynchronous nature of an XHR here, I think, but I haven't been able to find where to wait so that this.status has either of the values I would expect from a file check.
EDIT: I've tried adding return 4; after req.send(); and that always gives q the value 4 regardless of whether the file is there.
How do I get the status value of a XMLHttpRequest back from the function it's in?
For async operations you could use callbacks or promises. Here is a simple example with callbacks:
(function () {
function pingFile(theURL, success, error) {
var req = new XMLHttpRequest();
req.onload = function (e) {
if (this.status === 200) {
success(e);
} else {
error(e);
}
};
req.open("HEAD", theURL);
req.send();
}
function fileExist(e) {
alert('File exist!');
}
function fileNotExist(e) {
alert('File does not exist!');
}
pingFile('images/image1.png', fileExist, fileNotExist);
}());
I am doing an XMLHttpRequest and I would like to fallback on doing something else (reading a local file) if it fails, but I want to do it outside of the XHR function (getDBfileXHR) itself.
I am using Jquery too.
How is that possible, given the fact that it doesn't seem to work with .done() and .fail(), maybe with a deferred variable or something else ?
getDBfileXHR( encode_utf8("http://john:hispasswd#mysite.com/DBfile.jsonp") );
//here I want to do something else if getDBfileXHR fails like this :
fallbackToLocalDBfile();
function getDBfileXHR(url) {
var request = new XMLHttpRequest();
request.open("GET", url, true); //3rd parameter is sync/async
request.onreadystatechange = function() { //Call a function when the state changes.
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0) {
console.log('we get a response from XHR');
var jsonText = request.responseText.replace("callback(", "");
jsonText = jsonText.replace(");", "");
storeJsonInProdata(JSON.parse(jsonText));
dbReadyDeferred.resolve();
} else {
console.log('error : request.status = '+request.status);
}
}
}
console.log("Sending XMLHttpRequest...");
request.send();
}
function fallbackToLocalDBfile(){
$.get('proDB.jsonp').done(function(data){
console.log(data);
//storeJsonInProdata(data);
//dbReadyDeferred.resolve();
});
}
Mmm something like this maybe :
var d=$.Deferred()
function getDBfileXHR(url) {
....
if (request.readyState == 4) {
...
d.resolve(_MyData);
} else {
console.log('error : request.status = '+request.status);
d.reject(_myError);
}
}
}
console.log("Sending XMLHttpRequest...");
request.send();
}
d.done(function (a){...}).fail(function (b){});
I have created XHR and I am also getting response from server correctly.
But for some reason the callback is not happening. Please help.
function uploadDr(){
var url = "UploadExcelServlet";
if (req != null) {
try {
req.open("GET", url, true);
} catch (e) {
alert(e);
}
req.onreadystatechange = callBk;
req.setRequestHeader("Content-Type", "multipart/form-data");
req.send();
} else {
alert("Null Request");
}
}
function callBk(){
if (req.readyState == 4){
if (req.status == 200){
alert(req.responseXml);
} else {
alert(req.statusText);
}
}
}
For GET requests you don't need set the "Content-Type" header, because the data are always passed in the URL.
And maybe you need set request data to send as follows:
req.send(null);
Then test readyState in callback function:
function callBk(){
console.log(req.readyState); // don't stop the script by using alert!
// other stuff
}
Make shure that readyState is not equal to 0 (XMLHttpRequest.UNSENT).