I'd like to detect 401 errors in AJAX calls and redirect to login.html. But I ended up writing many duplicate of code like
if (xhr.status === 401) {
location.assign('/login.html');
}
in the error callback.
My question is, is there a way (the best way?) to handle them uniformly? Could I could inject some code into all of those Ajax calls?
You can use ajaxError() for this. This event triggers when an ajax completed with error. Then you can check the status like this,
$(document).ajaxError(function (event, jqxhr, settings, exception) {
if (jqxhr.status == 401) {
location.assign('/login.html');
}
});
function myAJax(sURL,fnSuccess,fnError) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4) {
if(xhttp.status == 200){
fnSuccess(xhttp.responseText);
}else{
fnError('Http Error',xhttp)
}
}
}
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
myAJax('server/url',function(data){
//success code here
},function(){
//error code here
});
Related
This issue is literally driving me mad and I've already spent hours researching possible solutions :)
My problem is: I've got a script that, upon loading, makes some AJAX calls to the server. This script is a widget and is already configured for cross-domain , etc.
Everything was working fine until now when 1 request has stopped working. The crazy thing is that is only that one, the others work just fine.
You can see in the screenshot below:
This is the code I use to send AJAX requests:
ajax: {
xhr: null,
request: function (url, method, data, success, failure){
if (!this.xhr){
this.xhr = window.ActiveX ? new ActiveXObject("Microsoft.XMLHTTP"): new XMLHttpRequest();
}
var self = this.xhr;
self.onreadystatechange = function () {
if (self.readyState === 4 && self.status === 200){
success(JSON.parse(self.responseText));
} else if (self.readyState === 4) { // something went wrong but complete
if (failure) {
failure();
} else { console.error("Ajax calls has failed."); }
}
};
self.onerror = function() {
if (failure) {
failure();
} else { console.error("Ajax calls has failed."); }
};
this.xhr.open(method,url,true);
this.xhr.setRequestHeader('Content-Type', 'application/json');
this.xhr.send(JSON.stringify(data));
}
}
And this is the call that causes the problem:
this.ajax.request(
this.getWidgetUrl() +"/check_referral_code",
"POST",
{uuid: SL.uuid, ref_code: ref},
function(data) {
if (data.response == "ok") {
// Do something
} else {
console.error(data.message);
}
},
function(data) {
console.error(data.message);
}
);
Can anybody help here?
UPDATE:
The problem seems to be intermittent. If I reload the page it will literally happen 50% of the times
I use jquery to auto scroll blog post.. They normally works fine but it doesn't scroll or work at all when I load that page via AJAX.. The problem could be how I'm calling ajax to load the page..may be callback function issue which I'm not getting right? here is the ajax code I'm using:
function loadme() {
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("loadcontent").innerHTML = this.responseText;
}
};
xhttp.open("GET", "http://xxxyyy.com/blogs/", true);
xhttp.send();
}
They all work but jquery post auto scroll will not work.. Is that due to callback function? I'm not sure.. Someone suggest or correct the code... Would appreciate volunteered help
Addition
I did alternative callback function but that too doesn't work either..
<div id="loadcontent"> Content to load/replace</div>
<button onclick="loadDoc('http://xxxyyy.com/blogs', myFunction)">Browse
Blogs</button>
//ajax with callback function
function loadDoc(url, cFunction) {
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function myFunction(xhttp) {
document.getElementById("loadcontent").innerHTML =
xhttp.responseText;
}
Since you have tagged jquery and you also mentioned jquery in your anwser,
I am providing a jquery solution.
//bind click event to the button, set an id for the button to make it just for that particular button
$(button).click(function() {
ajaxRequest("url", loadcontent);
});
// this will be the function for ajax, with the callback as parameter
function ajaxRequest(url, callback) {
$.ajax({
url: url,
method: "get",
success: function (response) {
callback(response);
},
error: function (jqXHR, exception) {
// handle errors
}
});
}
// this will be passed as callback to the ajaxRequest function
//you just need to set the innerHTML and the use animate to scroll to the bottom or to whatever height you would like
function loadcontent(message) {
$("#loadcontent").html(message);
$("#loadcontent").animate ({ scrollTop: $("#container").prop("scrollHeight") }, 10);
}
Say in window.onload function i call a bunch of other methods:
function window.onload(){
method1();
alert("test1");
method2();
alert("test2");
}
So my test1 method is working fine, i get the alert "test1", but then it appears that my code is "freezing" on method2, so the alert "test2" is not being called.
Here is what my test2 method looks like
function method2(){
alert("testing");
var xhr = new XMLHttpRequest();
xhr.open("GET", "url that i want to call from", true);
xhr.onload = function() {
if (xhr.status==200) {
alert(xhr.responseText);
alert("yay");
}
else{
alert("Aww");
}
}
xhr.send();
}
what i dont understand is why i dont even get the alert "testing", if my code is freezing somewhere why doesnt it at least run the first line in the method?
Can anyone explain why this occurs in javascript?
thanks
I have always hooked into to the 'on ready state change' event.
<h2>AJAX</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
$(document).ready(function () {
loadDoc();
});
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
alert("yay");
}
};
xhttp.open("GET", "demo", true);
xhttp.send();
}
</script>
http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
From the information you provided, I am guessing that you are running into browser security issues ...
I would recommend using jquery to handle the job for you. the $(document).ready function in jquery has always worked awesomely for me in the years I have been using the framework.
If you can't use jquery, then you need to have the user click on a button in order to initiate the http request you desire.
Also, if you need to perform the 'Awww' action you can append it to the if statement but I would recommend using if else based on xhttp.readyState values or your 'Awww' will repeat often.
Hey guys, this is driving me absolutely insane so I wanted to ask the experts on this site to see if you know how to do it =)
I'm trying to create some javascript code that can read out elements of a web page (eg. what does the first paragraph say?). Here's what I have so far, but it doesnt work and I cant figure out why:
<script type="text/javascript">
<!--
var req;
// handle onreadystatechange event of req object
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
//document.write(req.responseText);
alert("done loading");
var responseDoc = new DOMParser().parseFromString(req.responseText, "text/xml");
alert(responseDoc.evaluate("//title",responseDoc,null,
XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue);
}
else {
document.write("<error>could not load page</error>");
}
}
}
req = new XMLHttpRequest();
req.onreadystatechange = processReqChange;
req.open("GET", "http://www.apple.com", true);
req.send(null);
// -->
The alert that keeps appearing is "null" and I can't figure out why. Any ideas?
This may be due to cross domain restriction... unless you're hosting your web page on apple.com. :) You could also use jQuery and avoid writing all that out and/or dealing with any common possible cross-browser XML loading/parsing issues. http://api.jquery.com/category/ajax/
Update:
Looks like it may have something to do with the source web site's Content-Type or something similar... For example, this code seems to work... (Notice the domain loaded...)
var req;
// handle onreadystatechange event of req object
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
//document.write(req.responseText);
//alert("done loading");
//alert(req.responseText);
var responseDoc = new DOMParser();
var xmlText = responseDoc.parseFromString(req.responseText, "text/xml");
try{
alert(xmlText.evaluate("//title",xmlText,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue);
}catch(e){
alert("error");
}
}
else {
document.write("could not load page");
}
}
}
req = new XMLHttpRequest();
req.onreadystatechange = processReqChange;
req.open("GET", "http://www.jquery.com", true);
req.send(null);
I also tried loading espn.com and google.com, and noticed they both have "Content-Encoding:gzip" so maybe that's the issue, just guessing though.
I'm dynamically loading content into a div when the user clicks a link using this code:
function ahah(url, target) {
document.getElementById(target).innerHTML = 'Opening form...';
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req != undefined) {
req.onreadystatechange = function() {ahahDone(url, target);};
req.open("GET", url, true);
req.send("");
}
}
function ahahDone(url, target) {
if (req.readyState == 4) { // only if req is "loaded"
if (req.status == 200) { // only if "OK"
document.getElementById(target).innerHTML = req.responseText;
} else {
document.getElementById(target).innerHTML=" AHAH Error:\n"+ req.status + "\n" +req.statusText;
}
}
}
function load(name, div) {
ahah(name,div);
return false;
}
This works fine, however I can't get any javascript to work in this new content, such as a jquery datapicker, or even just a document.write hello world. The js in there in the code, just not working. I've loaded the content directly in a browser and it works fine.
I'm at loss, any ideas greatly appreciated!
If you are using jquery anyways, might as well try using jquery.ajax().
You could include whatever scripts you need in the <head> and then call your datepicker or w/e in the callback function of your jquery ajax call.