What is XMLHttpRequest's life cycle? When will the XMLHttpRequest be destroyed? - ajax

When is XMLHttpRequest destroyed?
I just wrote the simple function below, and xmlhttp has been sent successfully, but responseText isn't sent to the function SetStringinDiv(). The variable str is empty and the variable location has value.
I have no idea how to fix it, and I don't know what the keyword for this problem is, either. If this kind of question already exists, please tell me how to find it or what the keyword is.
<script>
function foo(){
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var str = xmlhttp.responseText;
SetStringinDiv("div1", str);
}
}
xmlhttp.open("GET", "uri", true);
xmlhttp.send();
}
</script>
<script>
function SetStringinDiv(location, str) {
document.getElementById("location").innerHTML = location;
document.getElementById("str").innerHTML = str;
if (document.getElementByID(location) == null) {
document.getElementById("error").innerHTML += ">> error, can not find the div, "
+ location + "\n";
}
document.getElementByID(location).innerHTML = str;
}
</script>

Check for xmlhttp.status != 200 and print out an error. Print out the readystate and status on each call to onreadystatechange. I think you will see an error message in statusText.
These days it is recommended to not use the onreadystatechange callback. I use the code below. Note that if the server does not respond and does not close the connection that your request won't timeout for quite some time (2-5 minutes) - either in your code or that below. If it is sitting there, shut down the server. You will get an immediate error response then.
var req = new XMLHttpRequest(),
done = function(response) {
callback(cache[uri.split('/').pop()] = cache[uri] = response);
};
req.open("GET", uri + ".lispz", true);
req.onerror = function(err) {
done({
uri: uri,
error: err
});
}
req.onload = function() {
return (req.status != 200) ? req.onerror(req.statusText) : done(run(req.responseText));
};
req.send();

Related

How to solve the error of router not found where I did defined it

I am trying to pull some information from the database by ajax call and render it to html.
This is my ajax function:
function getActor(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
const actorList = jsonToTable(this.response, 'default');
document.getElementById('tbody').innerText = actorList;
}
}
console.log("getActor called");
xhttp.open('GET','/actor', true);
xhttp.send();
}
This is my router:
router.get('/actor', function(req, res){
console.log("router.get /actor called");
req.pool.getConnection(function(err, connection){
if(err){
res.sendStatus(500);
return;
}
var query = "USE mydb; SELECT first_name, last_name FROM actor;";
connection.query(query, function(err, rows, fields){
connection.release();
if(err){
res.sendStatus(500);
return;
}
res.json(rows);
})
})
});
The console statement inside getActor is called but an error is reported:
"GET /actor" Error (404): "Not found"
What am I missing here?
just a followup here.
I solved this problem by deleting a previously added line:
app.use(express.static('../public', {index: 'actor.html'}))

Async XMLHttpRequest not returning response when followed by code to redirect to another URL in Firefox and Safari

I am facing problem with my code in FireFox and Safari as below:
xhr = new window['XMLHttpRequest'];
xhr.onreadystatechange = function() {
if (done || xhr.readyState != 4) {
return;
}
done = true;
handleResponse(xhr.responseText, callback);
};
}
xhr.open('GET', uri+params, true);
xhr.withCredentials = true;
xhr.send(null);
function handleResponse(responseText, callback) {
var error;
var result;
try {
result = toucan.JSON.parse(responseText)['result']; //connectedAuth
logout result.
} catch (ex) {
result = undefined;
}
console.log("Result is" + result);
if (!result) {
var errorCode = 'UnknownError';
var errorMessage = 'An unknown error ocurred';
error = toucan.Base.format('%s: %s', errorCode, errorMessage);
}
invokeCallback(error, callback);
}
This is followed by redirection as :window.location.href = "index.php?module=login&method=logout";
However, I am not getting any response back from the request I made if it is followed by redirection in FireFox.
This works fine in Chrome but not in Firefox and is specific to the case when request is followed by redirection.
I do not have control on redirection code to be changed. Is there a way that the browser can be enforced to first complete the request and get the response before going for redirection while keeping the call asynchronous.
I would suggest you to use a promise, first create a function that run the ajax call that return the response from your server:
ajax_AuthUser(id,pass){
return $.ajax({
method: "POST",
url: "authUser.php",
data: { id: id, pass: pass}
})
}
Second use a done statement:
ajax_AuthUser(id,pass)
.done(function(response){
//check the response here !! maybe validate the json ?
var auth = JSON.parse(response)
if(auth.response == "approved"){
//do something here
}else{
//do other stuff here
}
}).fail(function(response){
//do something if fail
}).always(function(){
//do something after the call finished
})
If you want a live example here is a jsfiddle that show how promises work
Hope it helps

AJAX XMLHttpRequest state undefined

In the following piece of JavaScript code, i'm executing GetData.php using AJAX. However, when i remove the comments to see the request object's state property, it turns up as undefined, although the PHP script is getting executed properly and my page is changing as i want it to. But i still need the state property. Any clue on what's going on here ?
function refreshPage()
{
var curr = document.getElementById('list').value;
var opts = document.getElementById('list').options;
for(var i=0;i<opts.length;i++)
document.getElementById('list').remove(opts[i]);
var request = new XMLHttpRequest();
request.onreadystatechange=
function()
{
if(request.readyState == 4)
{
//alert(request.state);
//if(request.state == 200)
{
fillOptions();
var exists = checkOption(curr);
var opts = document.getElementById('list').options;
if(exists == true)
{
for(var i=0;i<opts.length;i++)
if(curr == opts[i])
{
opts[i].selected = true;
break;
}
}
else
{
opts[0].selected = true;
}
refreshData();
}
/*else
{
alert(request.responseText);
//document.close();
}*/
}
}
request.open("GET","GetData.php?Address=" + address + "&Port=" + port,true);
request.send();
}
Do you mean request.status not request.state?
Try changing it to the .status and it should work just fine :)

AJAX - Return responseText

I've seen the myriad threads sprawled across the Internet about the following similar code in an AJAX request returning undefined:
AJAX.onreadystatechange = function() {
if(AJAX.readyState == 4) {
if(AJAX.status == 200) {
var response = AJAX.responseText;
return response;
}
else {
window.alert('Error: ' + AJAX.status);
return false;
}
}
};
I know that I'm supposed to "do something with" responseText like writing it to the HTML. The problem: I don't have that luxury. This bit of code is intended to be inside of a generic method for running fast AJAX requests that way all the code for making an AJAX request doesn't have to written out over and over again (~40×) with the chance of a minor problem here or there that breaks the application.
My method HAS to explicitly return responseText "or else." No writing to HTML. How would I do this? Also, I'd appreciate a lack of plugs for JQuery.
What I'm looking for:
function doAjax(param) {
// set up XmlHttpRequest
AJAX.onreadystatechange = function() {
if(AJAX.readyState == 4) {
if(AJAX.status == 200) {
var response = AJAX.responseText;
return response;
}
else {
window.alert('Error: ' + AJAX.status);
return false;
}
}
};
// send data
}
...
function doSpecificAjax() {
var param = array();
var result = doAjax(param);
// manipulate result
}
Doing a little research I came across this SOF post:
Ajax responseText comes back as undefined
Based on that post, it looks like you may want to implement your ajax method like this:
function doRequest(url, callback) {
var xmlhttp = ....; // create a new request here
xmlhttp.open("GET", url, true); // for async
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
if (xmlhttp.status == 200) {
// pass the response to the callback function
callback(null, xmlhttp.responseText);
} else {
// pass the error to the callback function
callback(xmlhttp.statusText);
}
}
}
xmlhttp.send(null);
}
Then, you can call that method like this...
doRequest('http://mysite.com/foo', function(err, response) { // pass an anonymous function
if (err) {
return "";
} else {
return response;
}
});
This should return the responseText accurately. Let me know if this doesn't give you back the correct results.

AJAX Ready State stuck on 1

Hi I can see this has been discussed but after perusing the issues/answers I still don't seem to be able to get even this simple AJAX call to bump out of ready state 1.
Here's the Javascript I have:
<script language="javascript" type="text/javascript">
var request;
function createRequest()
{
try
{
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
if (!request)
alert("Error initializing XMLHttpRequest!");
}
function loadClassesBySchool()
{
//get require web form pieces for this call
createRequest(); // function to get xmlhttp object
var schoolId = getDDLSelectionValue("ddlSchools");
var grade = getDDLSelectionValue("ddlGrades");
var url = "courses.php?grades=" + escape(grade) + "&schoolId=" + escape(schoolId);
//open server connection
request.open("GET", url, true);
//Setup callback function for server response
//+++read on overflow that some fixed the issue with an onload event this simply had
//+++the handle spitback 2 readystate = 1 alerts
request.onload = updateCourses();
request.onreadystatechanged = updateCourses();
//send the result
request.send();
}
function updateCourses()
{
alert('ready state changed' + request.readyState);
}
function getDDLSelectionValue(ddlID)
{
return document.getElementById(ddlID).options[document.getElementById(ddlID).selectedIndex].value;
}
</script>
The PHP is HERE just a simple print which if i navigate to in the browser (IE/Chrome) loads fine:
<?php
print "test";
?>
I'm quite new at this but seems like I can't get the most bare bones AJAX calls to work, any help as to how work past this would be greatly appreciated.
All I get out of my callback function 'updateCourses' is a 1...
Well after more digging I actually gave up and switched over to jQuery which should for all intents and purposes be doing the EXACT same thing except for the fact that jQuery works... I was just less comfortable with it but so be it.
Here's the jQuery to accomplish the same:
function loadCoursesBySchool(){
var grades = getDDLSelectionValue("ddlGrades");
var schoolId = getDDLSelectionValue("ddlSchools");
jQuery.ajax({
url: "courses.php?grades=" + grades + "&schoolId=" + schoolId,
success: function (data) {
courseDisplay(data);
}
});
}
function courseDisplay(response)
{
//check if anything was setn back!?
if(!response)
{
$("#ddlCourses").html("");
//do nothing?
}
else
{
//empty DLL
$("#ddlCourses").html("");
//add entries
$(response).appendTo("#ddlCourses");
}
}

Resources