I'm trying to fetch some content from another source using XHR as shown below:
function fetchPage(str)
{
if(str=="")
{
document.getElementById("table").innerHTML="";
resetFilters();
$('#progress').hide(); //fetching progress bar <div>
return;
}
if (window.XMLHttpRequest) // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
else // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange=postCallback;
xmlhttp.open("GET", "fetch.php?url=http://www.sis.itu.edu.tr/tr/ders_programlari/LSprogramlar/prg.php?fb="+str, true);
xmlhttp.send();
// any stuff that goes here will happen before callback
// (this is a good place to update a UI element showing a call is resolving.)
// (for example a spinner or text saying "fetching")
$('#progress').show();
progressFetching();
switch(xmlhttp.readyState){ //loading bar adjustments
case 0:
$('.bar').css("width","0%");
$('.bar').text("0%");
break;
case 1:
$('.bar').css("width","25%");
$('.bar').text("25%");
break;
case 2:
$('.bar').css("width","50%");
$('.bar').text("50%");
break;
case 3:
$('.bar').css("width","75%");
$('.bar').text("75%");
break;
}
}
function postCallback()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200){
progressDone(); //loading is finished
$('#error').hide();
document.getElementById("table").innerHTML=xmlhttp.responseText;
// continue to process post callback.
resetFilters();
}
else {
// report error with fetch
/*if(xmlhttp.status==404 || xmlhttp.responseText == "")
$('#error').show();*/
//$('#error').show();
}
}
I want my page to display error when connection timeout occurs, or when the computer doesn't have an internet connection (maybe a disconnection occurred while hanging around) or any other situation where the webpage fails to fetch the contents of the other source.
Using the code above, in the else block, if I go for if(xmlhttp.status==404 || xmlhttp.responseText == "") in the /* */ comment section, I won't get an error unless its not a 404 error. If i go for // comment section, error will be displayed after the fetching process is started until it is completed, i.e. between xmlhttp.readyState = 0 through xmlhttp.readyState = 4. How can I display connection error messages using these attributes or something else?
Thank your for your attention:)
According to this stackoverflow: XMLHttpRequest (Ajax) Error
xmlhttp.onreadystatechange = function (oEvent) {
if (xmlhttp.readyState === 4) {
if (xmlhttp.status === 200) {
console.log(xmlhttp.responseText)
} else {
console.log("Error", xmlhttp.statusText)
}
}
}
The problem is my template in prior question was flawed. I believe this will work better because it creates a closure to pass the variable you need to work with.
Once again, I did not test this so it might have typos and bugs -- nor did I change anything except how postCallback() is invoked and added a parameter to it.
function fetchPage(str)
{
if(str=="")
{
document.getElementById("table").innerHTML="";
resetFilters();
$('#progress').hide(); //fetching progress bar <div>
return;
}
var xmlhttp;
if (window.XMLHttpRequest) // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
else // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange=function () { postCallback(xmlhttp); };
xmlhttp.open("GET", "fetch.php?url=http://www.sis.itu.edu.tr/tr/ders_programlari/LSprogramlar/prg.php?fb="+str, true);
xmlhttp.send();
// any stuff that goes here will happen before callback
// (this is a good place to update a UI element showing a call is resolving.)
// (for example a spinner or text saying "fetching")
$('#progress').show();
progressFetching();
switch(xmlhttp.readyState){ //loading bar adjustments
case 0:
$('.bar').css("width","0%");
$('.bar').text("0%");
break;
case 1:
$('.bar').css("width","25%");
$('.bar').text("25%");
break;
case 2:
$('.bar').css("width","50%");
$('.bar').text("50%");
break;
case 3:
$('.bar').css("width","75%");
$('.bar').text("75%");
break;
}
}
function postCallback(xmlhttp)
{
if (xmlhttp.readyState==4 && xmlhttp.status==200){
progressDone(); //loading is finished
$('#error').hide();
document.getElementById("table").innerHTML=xmlhttp.responseText;
// continue to process post callback.
resetFilters();
}
else {
// report error with fetch
/*if(xmlhttp.status==404 || xmlhttp.responseText == "")
$('#error').show();*/
//$('#error').show();
}
}
Related
I have the following generic Ajax response writer which I recently added some logic to, in order to dynamically parse the results for script objects, and run them when I find them using jQuery.globalEval().
Here is the code:
//Generic Results Writter method for Ajax Calls
function writeAjaxResponse(targetId, response) {
document.getElementById(targetId).innerHTML = response;
try {
var dom = $j(response);
dom.find('script').each( function(){
$j.globalEval(this.text || this.textContent || this.innerHTML || '');
});
} catch (e) {
console.error("Error parsing for script reloads: "+e);
}
}
This solution works very nicely the first time its called. However writeAjaxResponse(targetId, response); is called each time a user loads some dynamic Ajax content. And unfortunately after the first time, the scripts are no longer loaded. To be clear, after the server side generated page is loaded, there are numerous links on the page which the users may click, which invoke this handler for the Ajax response.
No error occurs, and no console.error() is written.. The Ajax data loads as normal, its just that the scripts in the response are no longer loaded.
In debugging, $j.globalEval is still getting called and this.text still has the script content in it, and the data looks correct, but still no joy.
Any light someone could shed on this would be very much appreciated!
Adding main ajax call for GET for reference:
function doAjaxGet(targetId, getUrl, handler) {`
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
try {
handler(targetId, xmlhttp.response);
}
catch (err) {
alert("Failed calling handler, detail: " + err + " Got responseText: " + xmlhttp.responseText);
}
}
}
xmlhttp.open("GET", getUrl, true);
xmlhttp.send(null);
}
This is my first php project. I have imlemented partial ajax postback by refering to this article: PHP AJAX SQL reference article
Now, I am trying to show a loading gif when the partial loading starts and hide it when the partial loading completes. Here is the code that I am using in Javascript:
function showUser1(str)
{
if (str == "")
{
document.getElementById("mems").innerHTML = "I caanot fetch: " + str;
return;
}
else
{
document.getElementById("loadgif").style.visibility= "visible";
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("outerpicwrapper").innerHTML = "";
document.getElementById("mems").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getmembers.php?q2="+str,true);
xmlhttp.send();
document.getElementById("loadgif").style.visibility= "hidden";
}
}
In the first line of body, I have written:
<img id="loadgif" src="img/loading.gif" class="loadinggif" />
In the CSS file, i have written:
.loadinggif
{
position: absolute;
z-index: 200;
visibility: hidden;
}
The code is working fine and shows the data but, loading gif is not shown.
I have even tried display:none and display:block in place of visibility.
Kindly help.
The problem is AJAX is asynchronous. Thus your code doesn't wait for the data to be fetched and
document.getElementById("loadgif").style.visibility= "visible";
document.getElementById("loadgif").style.visibility= "hidden";
These lines are executed simultaneously.
To prevent this from happening you can put
document.getElementById("loadgif").style.visibility= "hidden";
inside the callback as well
function showUser1(str)
{
if (str == "")
{
document.getElementById("mems").innerHTML = "I caanot fetch: " + str;
return;
}
else
{
document.getElementById("loadgif").style.visibility= "visible"; // This line displays the loading gif
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("outerpicwrapper").innerHTML = "";
document.getElementById("mems").innerHTML = xmlhttp.responseText;
document.getElementById("loadgif").style.visibility= "hidden"; // This line hides the loading gif
}
};
xmlhttp.open("GET","getmembers.php?q2="+str,true);
xmlhttp.send();
}
}
Finally, I made my issue work out using JQuery.
I just made display:none in CSS and called the show() function of jquery on the loading gif div. This show function was written inside the javascript code.
I have some bit of code from the internet that updates my webpage when I type in a text input.
My code is below
function validate(field, query) {
var xmlhttp;
if (window.XMLHttpRequest) { // for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState != 4 && xmlhttp.status == 200) {
document.getElementById(field).innerHTML = "Validating..";
} else if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(field).innerHTML = xmlhttp.responseText;
} else {
document.getElementById(field).innerHTML = "Error Occurred. <a href='index.php'>Reload Or Try Again</a> the page.";
}
}
xmlhttp.open("GET", "validation.php?field=" + field + "&query=" + query, false);
xmlhttp.send();
}
After debugging I found out that the code is run twice (afaik). The first time xmlhttp.readyState is 1, meaning that the request is being set up. The second time it's 4 meaning it's complete. So this is working like intended.
The problem is that it always returns the Error Occurred bit in the field. The reason why is that xmlhttp.status keeps the status number 404, meaning that it is not found. I have no clue why it returns 404. If the browser I'm using is important, I'm using the latest version of Safari. I also checked the latest version of Chrome and got the same problem.
Make sure that your code is actually requesting the correct URL. You can do this with most modern browser's developer tools, including the Network tab of Chrome's.
Im trying to setup a redirect for a chat script. If the chat goes unanswered after x amount of time the page will redirect.
I posted a question here yesterday regarding the same thing, but at the time knowing little in regards to JS I was trying to mix php with js. I have changed tactics.
Here is what I got thus far:
function opCheck()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert("Your browser does not support XMLHTTP!");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
opCheck();
// alert('working2');
}
}
opjoined = "newchattimer.php";
xmlhttp.open("GET",opjoined,true);
xmlhttp.send(null);
}
function opResult()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert("Your browser does not support XMLHTTP!");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
//alert('state = 4');
var op = xmlhttp.responseText;
}
}
ajaxurl = "ajaxfiles/opAnswer_12.txt";
xmlhttp.open("GET",ajaxurl,true);
xmlhttp.send(null);
}
setTimeout(function() {
opCheck();
opResult();
//alert(op);
if (op == 'n') window.location.replace("chatnoop.php");
}, 3000);
It creates the text file properly but ultimately no redirect. I used the chrome deveolpers tool and no errors. I also tried to alert(op); to see if the result is being grabbed, but I get no alert.
What is wrong with this code?
Thanks.
If you had taken the time to indent your code, you'd see that var op is declared inside the scope of the onreadystatechange function, which is both out of scope and asynchronous.
function opResult() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Your browser does not support XMLHTTP!");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
var op = xmlhttp.responseText; //declared here
}
}
ajaxurl = "ajaxfiles/opAnswer_12.txt";
xmlhttp.open("GET", ajaxurl, true);
xmlhttp.send(null);
}
setTimeout(function () {
opCheck();
opResult();
// op is out of scope here
if (op == 'n') window.location.replace("chatnoop.php");
}, 3000);
Since timeouts aren't generally the way to handle async functions, and doing ajax request when all you intend to do when it finishes is to redirect anyway is'nt really neccessary, you could just do a regular form submit, which will redirect all by itself, or move the redirecting inside the right scope!
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if(xmlhttp.responseText == 'n') window.location.href = 'chatnoop.php';
}
}
You may find what you want here http://www.tizag.com/javascriptT/javascriptredirect.php but basically i don't think that window.location.replace("chatnoop.php"); is correct. You should consider using JQuery to manage all the Ajax stuff in addition, but it should work like you've done anyway
I have these two buttons that a user can click to either approve/deny somebody on a site, and the code works perfect in IE, but when I try and use firefox, nothing at all happens when I click the buttons.
the javascipt/ajax code is:
function ApproveOrDenyStudent(i, action){
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var newStudentEmail = "newStudentEmail" + i;
var emailField = document.getElementById(newStudentEmail);
var email = emailField ? emailField.value : '';
// Approve/deny the user
if (action == 0){
xmlhttp.open("GET","ApproveStudent.php?email="+email,true);
}
else if (action == 1){
xmlhttp.open("GET","DenyStudent.php?email="+email,true);
}
xmlhttp.send();
window.location.reload();
}
any help would be great! Thanks!
You got a race condition!
xmlhttp.send();
window.location.reload();
You are making an asynchronous call. You are making the Ajax request and replacing the page right away! The call to the server is not getting out.
Reload the page when the request is complete.
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4){
window.location.reload(true);
}
};
xmlhttp.send();