XMLHttpRequest status returning 404 - javascript

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.

Related

how to get NEWLY created select width with JS

I am ganging my head against the wall for 3 hours now. I have this code:
function showpctask() {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
var xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("pcactivitytask").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","showpctask.php"+,true);
xmlhttp.send();
}
that opens up a php file inside a div (id = pcactivitytask). That php file builds a 'select'
I also have this function right here:
function setpctaskwidth() {
var maxtaskwidth = 0;
$("div .pcactivitytask").each(function(){
c_width = parseInt($(this).width());
if (c_width > maxtaskwidth) {
maxtaskwidth = c_width;
}
});
alert (maxtaskwidth);
}
that will show me the max width of all elements with the the class of "pcactivitytask". Yes, the select created by the previous script has that class. If I call both these function it will NOT include the width of the NEWLY created select..... I need to run it AGAIN 'manuall'. I need my script to "onclick" BOTH build the NEW select AND include it in finding the max width by the second script. Thank you.
XMLhttprequest works asynchronously, meaning it does not happen in order.
that is why you have the xmlhttp.onreadystatechange callback function, that only runs once the request is finished
you do not specify how you call these two functions but I would expect to see the call to setpctaskwidth() inside the onreadystatechange function like this:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("pcactivitytask").innerHTML = xmlhttp.responseText;
setpctaskwidth();
}
};
be advised that if the response includes images or other external resources (fonts etc) that don't already exist in the page you might get a different size than the actual final size (it will measure the size before the image is loaded)

Ajax Timed Event Redirect

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

How to handle XHR error display messages?

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

Javascript/AJAX function that works in Internet Explorer, but not in Firefox

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

how to get the source code based on url using java script?

i wrote some code to get the html source code but it is working only IE8,but not working on mozila and chrome , what is the problem , please give me suggestion.
my code
<script>
function processStateChange() {
statusDiv = document.getElementById("stats");
if (req.readyState == 0) { statusDiv.innerHTML = "UNINITIALIZED"; }
if (req.readyState == 1) { statusDiv.innerHTML = "LOADING"; }
if (req.readyState == 2) { statusDiv.innerHTML = "LOADED"; }
if (req.readyState == 3) { statusDiv.innerHTML = "INTERACTIVE"; }
if (req.readyState == 4) {
statusDiv.innerHTML = "COMPLETE";
statusDiv.innerHTML = req.responseText;
}
}
function GetXmlHttpObject() {
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
} if (window.ActiveXObject) { // code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
} return null;
}
//req = new XMLHttpRequest("Msxml2.XMLHTTP");
req = GetXmlHttpObject();
debugger;
if (req) {
req.onreadystatechange = processStateChange;
req.open("GET", "http://whatismyipaddress.com/", true);
req.send();
}
</script>
i checked to debug the code IE was completely working the loop(req.readystate==4 to finally get the response text) but mozila or chromes are only working loop(req.readystate==2 after abort the loop), what is the problem, please give me some suggestion, using jquery or java script to solve the problem
Thank u
hemanth
Due to the same origin policy restriction you cannot send cross domain AJAX calls. The reason this works in IE is probably that you are using some old dinosaurish version of IE that has some bugs and allows such an AJAX request. But no modern browser will ever allow you to do that.
You can send AJAX requests only to the domain from which originated the page containing the javascript code sending the AJAX request.
There are some workarounds depending on the level of control you have over the remote domain. In your case I guess that you have no control over http://whatismyipaddress.com/. So your only option is to write a server side script on your domain that will serve as a bridge between your domain and the remote domain and then send the AJAX request to your script:
req.open("GET", "/myscript", true);

Categories

Resources