How can I change this variable with ajax? - javascript

I'm curious as to why this isn't working, here's the code:
function Ajax(sUrl, fCallback) {
var url = sUrl || '';
var callback = fCallback || function () {};
var xmlhttp = (function () {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
return new ActiveXObject("Msxml2.XMLHTTP.6.0");
} catch (e) {
try {
return new ActiveXObject("Msxml2.XMLHTTP.3.0");
} catch (err) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
} else {
return null;
}
}());
this.setUrl = function (newUrl) {
url = newUrl;
};
this.setCallback = function (func) {
callback = func;
};
this.request = function (method, data) {
if (xmlhttp === null) { return false; }
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4) {
callback(xmlhttp.status, xmlhttp.responseXML, xmlhttp.responseText);
}
};
data = data || '';
data = encodeURIComponent(data);
if ((/post/i).test(method)) {
xmlhttp.open('POST', url);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(data);
} else {
var uri = data === '' ? url : url + '?' + data;
xmlhttp.open('GET', uri);
xmlhttp.send();
}
return true;
};
return this;
}
var ajax = new Ajax(''); // sets the url, not necessary for this demonstration
var changed = false;
function change() {
changed = true;
}
function foo() {
ajax.setCallback(change);
ajax.request();
alert(changed);
}
foo();
There is a fiddle here: http://jsfiddle.net/dTqKG/
I feel like the change function would create a closure that would indeed change the changed variable. Does anyone know what's going on?

The ajax.request(); will return before change() is called. That is the async nature of the AJAX calls, and the reason why you need the callback as opposed to just getting return value from send() method.
Other than that there might be some other issues in the code. I question why wouldn't you use one of the many AJAX frameworks readily available instead of writing your own.

Related

Return datas inside XMLHttpRequest.onreadystatechange [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have this function :
function getDatas() {
var xmlhttp = new XMLHttpRequest();
var response = null;
xmlhttp.open("POST", "getdatas.php", true);
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState === 4) {
if(xmlhttp.status === 200) {
response = xmlhttp.responseText;
return response;
}
else {return xmlhttp.statusText;}
}
};
xmlhttp.send(null);
}
The response is in a JSON format and correctly filled.
How to return the response for another use like :
var datas = getDatas();
UPDATE :
After the callback I have this :
function AppViewModel() {
var _self = this;
getDatas(function(error, result) {
if(error) {
alert(error);
} else {
_self.datas = result;
console.log(_self.datas);
}
});
console.log(_self.datas);
}
The first console.log(_self.datas); works well but the second is undefined.
AJAX is asynchronous, so you don't return any values from such functions, you use callbacks and use the value inside the callback:
function getDatas(callback) {
var xmlhttp = new XMLHttpRequest();
var response = null;
xmlhttp.open("POST", "getdatas.php", true);
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState === 4) {
if(xmlhttp.status === 200) {
response = xmlhttp.responseText;
callback(null, response);
}
else {
callback(xmlhttp.statusText, null);
}
}
};
xmlhttp.send(null);
}
and then when you call the getDatas function you provide a callback which will be invoked when the AJAX request finishes and it will either contain the result or an error:
getDatas(function(error, result) {
if (error) {
alert('An error occurred while retrieving data: ' + error);
} else {
// Use the result variable here
}
});

Need to modify this onlinejs code (internet detection script) to fire manually, not on a timer

I am using the excellent onlinejs (https://github.com/PixelsCommander/OnlineJS) library for checking that my app has a live internet connection. However, I don't need it to fire regularly, but rather upon the manual calling of the main function.
I would like to modify this code so that it is not firing on a timer, and know the name of the function to call for manual firing, which assume is just getterSetter.
My previous attempts to modify the code below have broken the script as I'm no expert at JavaScript. I appreciate any help in adapting this very useful code.
function getterSetter(variableParent, variableName, getterFunction, setterFunction) {
if (Object.defineProperty) {
Object.defineProperty(variableParent, variableName, {
get: getterFunction,
set: setterFunction
});
}
else if (document.__defineGetter__) {
variableParent.__defineGetter__(variableName, getterFunction);
variableParent.__defineSetter__(variableName, setterFunction);
}
}
(function (w) {
w.onlinejs = w.onlinejs || {};
//Checks interval can be changed in runtime
w.onLineCheckTimeout = 5000;
//Use window.onLineURL incapsulated variable
w.onlinejs._onLineURL = "http://lascelles.us/wavestream/online.php";
w.onlinejs.setOnLineURL = function (newURL) {
w.onlinejs._onLineURL = newURL;
w.onlinejs.getStatusFromNavigatorOnLine();
}
w.onlinejs.getOnLineURL = function () {
return w.onlinejs._onLineURL;
}
getterSetter(w, 'onLineURL', w.onlinejs.getOnLineURL, w.onlinejs.setOnLineURL);
//Verification logic
w.onlinejs.setStatus = function (newStatus) {
w.onlinejs.fireHandlerDependOnStatus(newStatus);
w.onLine = newStatus;
}
w.onlinejs.fireHandlerDependOnStatus = function (newStatus) {
if (newStatus === true && w.onLineHandler !== undefined && (w.onLine !== true || w.onlinejs.handlerFired === false)) {
w.onLineHandler();
}
if (newStatus === false && w.offLineHandler !== undefined && (w.onLine !== false || w.onlinejs.handlerFired === false)) {
w.offLineHandler();
}
w.onlinejs.handlerFired = true;
};
w.onlinejs.startCheck = function () {
setInterval("window.onlinejs.logic.checkConnectionWithRequest(true)", w.onLineCheckTimeout);
}
w.onlinejs.stopCheck = function () {
clearInterval("window.onlinejs.logic.checkConnectionWithRequest(true)", w.onLineCheckTimeout);
}
w.checkOnLine = function () {
w.onlinejs.logic.checkConnectionWithRequest(false);
}
w.onlinejs.getOnLineCheckURL = function () {
return w.onlinejs._onLineURL + '?' + Date.now();
}
w.onlinejs.getStatusFromNavigatorOnLine = function () {
if (w.navigator.onLine !== undefined) {
w.onlinejs.setStatus(w.navigator.onLine);
} else {
w.onlinejs.setStatus(true);
}
}
//Network transport layer
var xmlhttp = new XMLHttpRequest();
w.onlinejs.isXMLHttp = function () {
return "withCredentials" in xmlhttp;
}
w.onlinejs.isXDomain = function () {
return typeof XDomainRequest != "undefined";
}
//For IE we use XDomainRequest and sometimes it uses a bit different logic, so adding decorator for this
w.onlinejs.XDomainLogic = {
init: function () {
xmlhttp = new XDomainRequest();
xmlhttp.onerror = function () {
xmlhttp.status = 404;
w.onlinejs.processXmlhttpStatus();
}
xmlhttp.ontimeout = function () {
xmlhttp.status = 404;
w.onlinejs.processXmlhttpStatus();
}
},
onInternetAsyncStatus: function () {
try {
xmlhttp.status = 200;
w.onlinejs.processXmlhttpStatus();
} catch (err) {
w.onlinejs.setStatus(false);
}
},
checkConnectionWithRequest: function (async) {
xmlhttp.onload = w.onlinejs.logic.onInternetAsyncStatus;
var url = w.onlinejs.getOnLineCheckURL();
xmlhttp.open("GET", url);
w.onlinejs.tryToSend(xmlhttp);
}
}
//Another case for decoration is XMLHttpRequest
w.onlinejs.XMLHttpLogic = {
init: function () {
},
onInternetAsyncStatus: function () {
if (xmlhttp.readyState === 4) {
try {
w.onlinejs.processXmlhttpStatus();
} catch (err) {
w.onlinejs.setStatus(false);
}
}
},
checkConnectionWithRequest: function (async) {
if (async) {
xmlhttp.onreadystatechange = w.onlinejs.logic.onInternetAsyncStatus;
} else {
xmlhttp.onreadystatechange = undefined;
}
var url = w.onlinejs.getOnLineCheckURL();
xmlhttp.open("HEAD", url, async);
w.onlinejs.tryToSend(xmlhttp);
if (async === false) {
w.onlinejs.processXmlhttpStatus();
return w.onLine;
}
}
}
if (w.onlinejs.isXDomain()) {
w.onlinejs.logic = w.onlinejs.XDomainLogic;
} else {
w.onlinejs.logic = w.onlinejs.XMLHttpLogic;
}
w.onlinejs.processXmlhttpStatus = function () {
var tempOnLine = w.onlinejs.verifyStatus(xmlhttp.status);
w.onlinejs.setStatus(tempOnLine);
}
w.onlinejs.verifyStatus = function (status) {
return status === 200;
}
w.onlinejs.tryToSend = function (xmlhttprequest) {
try {
xmlhttprequest.send();
} catch(e) {
w.onlinejs.setStatus(false);
}
}
//Events handling
w.onlinejs.addEvent = function (obj, type, callback) {
if (window.attachEvent) {
obj.attachEvent('on' + type, callback);
} else {
obj.addEventListener(type, callback);
}
}
w.onlinejs.addEvent(w, 'load', function () {
w.onlinejs.fireHandlerDependOnStatus(w.onLine);
});
w.onlinejs.addEvent(w, 'online', function () {
window.onlinejs.logic.checkConnectionWithRequest(true);
})
w.onlinejs.addEvent(w, 'offline', function () {
window.onlinejs.logic.checkConnectionWithRequest(true);
})
w.onlinejs.getStatusFromNavigatorOnLine();
w.onlinejs.logic.init();
w.checkOnLine();
w.onlinejs.startCheck();
w.onlinejs.handlerFired = false;
})(window);
Looking at the source, I believe you can simply call onlinejs.logic.checkConnectionWithRequest(false) to get the status synchronously. This function will return either true or false.
PS: I am sure there are better libraries for this task out there, I really do not like the way it's written and clearly, the author doesn't know JS very well. E.g., the following code taken from the library makes no sense at all.
w.onlinejs.stopCheck = function () {
clearInterval("window.onlinejs.logic.checkConnectionWithRequest(true)", w.onLineCheckTimeout);
}

Second call out of two xmlhttprequest doesn't work

I've read a lot of how to try and make two xmlhttprequest in parallel, but it looks like something doesn't quite work.
I have 1 php file. which includes 2 .js files.
The first runs xmlhttprequest every 3 seconds.
I want the second to run on demand, but whenever i trigger it, it returns with status 4 but the responseText is always empty. (the PHP file prints with no question, i even tried to put on the PHP file just window.open('1') to see that the file is called and its not).
Here is the first JS :
var req1 = createXMLHttpRequest2();
var user_redirected = false;
function createXMLHttpRequest2() {
var ua2;
if(window.XMLHttpRequest) {
try {
ua2 = new XMLHttpRequest();
} catch(e) {
ua2 = false;
}
} else if(window.ActiveXObject) {
try {
ua2 = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
ua2 = false;
}
}
return ua2;
}
function set_user_redirected_false() {
user_redirected = false;
}
function get_user_redirected() {
return user_redirected;
}
function handleResponse(username, game_id, isInvitation) {
if(req1.readyState == 4 && req1.status==200) {
var response = req1.responseText;
if (response == "true") {
// Ask to set the game_accepted var to 1 (user is redirected and not leaving)
user_redirected = true;
if (isInvitation == "true") {
window.location.href = "game.php?game_id="+game_id+"&position=2";
} else {
window.location.href = "game.php?game_id="+game_id+"&position=1";
}
}
else {
setTimeout(function(){sendRequest();}, 3000);
}
}
}
function sendRequest() {
user_redirected = false;
var username = "";
var game_id = -1;
var isInvitation = "false";
username = document.getElementById("username").value;
game_id = document.getElementById("game_id").value;
isInvitation = document.getElementById("invitation").value;
if (isInvitation == "true") {
req1.open('GET', 'check_for_inviter.php?username='+username+'&game_id='+game_id ,true);
} else {
req1.open('GET', 'check_for_opponent.php?username='+username+'&game_id='+game_id,true);
}
req1.onreadystatechange = function(){handleResponse(username, game_id, isInvitation);};
req1.send(null);
}
This is the second JS file :
function createXMLHttpRequest() {
var ua;
if(window.XMLHttpRequest) {
try {
ua = new XMLHttpRequest();
} catch(e) {
ua = false;
}
} else if(window.ActiveXObject) {
try {
ua = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
ua = false;
}
}
return ua;
}
function delete_waiting_games(username) {
var req2 = createXMLHttpRequest();
req2.open('GET', 'delete_waiting_games_for_username.php');
req2.onreadystatechange = function(){
window.open(req2.readyState+'&'+req2.responseText);
};
req2.send(null);
}
As you can see i open a new window to see the response and the ready state (just for testing) and i always get status 4 and empty responseText.
Thanks.
Use setTimeout to separate the calls, and with to encapsulate the XMLHTTPRequest:
function xhr()
{
with(new XMLHttpRequest)
{
open("GET",{},true);
setRequestHeader("Foo", "Bar");
send("");
onreadystatechange = handler;
}
}
function handler(event)
{
!!event.target && !!event.target.readyState && event.target.readyState === 4 && ( console.log(event) );
}
setTimeout(xhr, 500);
setTimeout(xhr, 1000);

Run one ajax after another one

I'm working on the project where I (sadly) cannot use jQuery. And I need to do something which is simple in jQuery but I cannot do it in pure JavaScript. So, I need to run one ajax request using a response form another one. In jQuery it will look like:
$.get("date.php", "", function(data) {
var date=data;
$("#date").load("doku.php?id="+date.replace(" ", "_")+" #to_display", function() {
$(document.createElement("strong")).html(""+date+":").prependTo($(this));
});
});
And this is my code in pure JS which isn't working:
if (window.XMLHttpRequest)
{
ObiektXMLHttp = new XMLHttpRequest();
} else if (window.ActiveXObject)
{
ObiektXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if(ObiektXMLHttp)
{
ObiektXMLHttp.open("GET", "date.php");
ObiektXMLHttp.onreadystatechange = function()
{
if (ObiektXMLHttp.readyState == 4)
{
var date = ObiektXMLHttp.responseText;
if (window.XMLHttpRequest)
{
ObiektXMLHttp = new XMLHttpRequest();
} else if (window.ActiveXObject)
{
ObiektXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
ObiektXMLHttp.open("GET", "doku.php?id="+date.replace(" ", "_"));
ObiektXMLHttp.onreadystatechange = function()
{
if (ObiektXMLHttp.readyState == 4)
{
alert(ObiektXMLHttp.responseText);
}
}
}
}
ObiektXMLHttp.send(null);
}
What am I doing worng?
You forgot to call ObiektXMLHttp.send(null); on second case:
//....
ObiektXMLHttp.open("GET", "doku.php?id="+date.replace(" ", "_"));
ObiektXMLHttp.onreadystatechange = function() {
if (ObiektXMLHttp.readyState == 4)
{
alert(ObiektXMLHttp.responseText);
}
};
//Here
ObiektXMLHttp.send(null);
How about something like this (naive prototype):
// xhr object def
var xhr = {
obj: function() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
throw new Error("can't init xhr object");
},
get: function(url, fn) {
var xhr = this.obj();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
fn(xhr.responseText);
}
};
xhr.open("GET", url);
xhr.send(null);
}
};
// implementation
xhr.get("date.php", function(data){
xhr.get("doku.php?id=" + data.replace(" ", "_"), function(data){
alert(data);
});
});
It's not clear what you got wrong (can you tell us?), but I'd suggest to rely on some helper function like this:
function xhrGet(url, callback) {
if (window.XMLHttpRequest)
var xhr = new XMLHttpRequest();
else if (window.ActiveXObject)
var xhr = new ActiveXObject("Microsoft.XMLHTTP");
if (!xhr) return;
xhr.open("GET", url);
xhr.onreadystatechange = function() {
if (xhr.readyState !== 4) return;
if (typeof callback === "function") callback(xhr);
};
xhr.send(null);
return xhr;
}
So all you have to do is to use this function:
xhrGet("date.php", function(x1) {
xhrGet("doku.php?id=" + date.replace(" ", "_"), function(x2) {
// do stuff
// x1 and x2 are respectively the XHR object of the two requests
});
});

ajax synchronous call problem

I have an Ajax function which looks like :
function getData(p) {
loadingImage();
p = p.replace("frame_", "");
if (window.XMLHttpRequest) {
AJAX=new XMLHttpRequest();
} else {
AJAX=new ActiveXObject("Microsoft.XMLHTTP");
}
if (AJAX) {
var __page =encodeURIComponent(p);
AJAX.open("GET", "page.php?page="+__page, false);
AJAX.send(null);
var __data = AJAX.responseText.match(/<data>[\s\S]*?<\/data>/gmi);
if(!__data) { return false; }
return __data;
} else {
return false;
}
}
then i have very simple loading function ( an loading image must appear in center of page ) :
function loadingImage(type)
{
document.getElementById("body").innerHTML = "<div class='loading'></div>";
}
then how i call ajax function :
var loadedData = getData("home");
if(loadedData)
{
document.getElementById("body").innerHTML = loadedData;
}
else
{
document.getElementById("body").innerHTML = "Error";
}
but the loading image won't appear, it's quite simple, but i'm stuck here , how make it to show that loading image while requesting data, then to replace loading image with loaded data. Thanks
function getData(p, cb) {
loadingImage();
p = p.replace("frame_", "");
if (window.XMLHttpRequest) {
AJAX = new XMLHttpRequest();
} else {
AJAX = new ActiveXObject("Microsoft.XMLHTTP");
}
if (AJAX) {
var __page = encodeURIComponent(p);
AJAX.open("GET", "page.php?page=" + __page, true);
AJAX.onreadystatechange = function(e) {
if (AJAX.readystate === 4) {
var __data = AJAX.responseText.match(/<data>[\s\S]*?<\/data>/gmi);
cb(data);
}
};
AJAX.send(null);
} else {
cb(null);
}
}
getData("home", function(loadedData) {
if (loadedData) {
document.getElementById("body").innerHTML = loadedData;
}
else {
document.getElementById("body").innerHTML = "Error";
}
});
Use async = true in the .open call.
Bind an eventhandler to readystatechange. If the readystate is 4 (LOADED) then get the data and send it to your callback.
If the AJAX fails call the callback with null or false.
In your callback get the loadedData and either render it or throw an error if there is no data.

Categories