callback function wont run when its called - ajax

ajax : function(typ,url,callback) {
if(window.XMLHttpRequest) {
var xml = new XMLHttpRequest();
}
if(window.ActiveXObject) {
var xml = new ActiveXObject("Microsoft.XMLHTTP");
}
xml.onreadystatechange = function(callback) {
if(xml.readyState == 4 && xml.status == 200) {
callback();
}
}
xml.open(typ,url,true);
xml.send();
}
}
//Function being called
window.onload = function() {
JS.ajax("GET","/server/chkEmail.php?email=email#email.com",function() {
alert(xml.responseText);
});
}
It throws the error saying:
Uncaught TypeError: callback is not a functionxml.onreadystatechange #
global.js:30
Any ideas?
I fixed it by passing the data variable through the onreadystatechange function and calling it in the callback function.
ajax : function(typ,url,callback) {
if(window.XMLHttpRequest) {
var xml = new XMLHttpRequest();
}
if(window.ActiveXObject) {
var xml = new ActiveXObject("Microsoft.XMLHTTP");
}
xml.onreadystatechange = function(data) {
if(xml.readyState == 4 && xml.status == 200) {
var data = xml.responseText;
callback(data);
}
};
xml.open(typ,url,true);
xml.send();
}
}
window.onload = function() {
JS.ajax("GET","/server/chkEmail.php? email=jonwcode#gmail.com",function(data){
alert(data);
});
}

Try like this:
xml.onreadystatechange = function() {
if (xml.readyState == 4 && xml.status == 200) {
callback();
}
};
Notice that the onreadystatechange function doesn't take any parameters whereas in your code you have passed it a parameter with the name callback which will override the callback variable from the outer scope.
UPDATE:
It looks like you have improperly scoped the xml variable and it isn't available in your AJAX callback. I strongly recommend you reading more about javascript variables scope. Here's how you could make the xml variable visible:
var xml = null;
if (window.XMLHttpRequest) {
xml = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xml = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xml == null) {
alert('Sorry, your browser doesn\'t seem to support AJAX - please upgrade to a modern browser');
} else {
xml.onreadystatechange = function() {
if(xml.readyState == 4 && xml.status == 200) {
var data = xml.responseText;
callback(data);
}
};
xml.open(typ,url,true);
xml.send();
}

Related

How can I send a synchronous ajax request to my server in onunload function

I need to send a ajax request to my server before web page close, my send code is below.
SendByAajx = function(msg) {
var response;
var xmlHttpReg;
if(window.XMLHttpRequest){
xmlHttpReg = new XMLHttpRequest();
} else if(window.ActiveXObject) {
xmlHttpReg = new ActiveXObject("Microsoft.XMLHTTP");
} else {
throw new Error("Unsupported borwser");
}
if(xmlHttpReg != null) {
xmlHttpReg.open("get", "https://127.0.0.1:57688/test"+'?'+msg, false);
xmlHttpReg.send(null);
if(xmlHttpReg.readyState==4){
if(xmlHttpReg.status == 200) {
var data = JSON.parse(xmlHttpReg.responseText);
if(typeof(data.errorcode) == "number" &&
data.errorcode != 0) {
throw("response error:" + data.errorcode);
}
response = data.result;
} else {
throw new Error("Error");
}
}
}
return response;
}
When I call this function in a button onclick event, it works.
function GetOnClick() {
try{
var result = SendByAajx (“data”);
} catch (e) {
//alert(errorInfo);
}
SetButtonDisabled(false);
}
But when I call this function when the page is unloaded, it doesn't work.
<body onload="javascript:OnLoad();" onunload="javascript:OnUnLoad()">
function OnUnLoad() {
try{
var result = SendByAajx(“data”);
} catch (e) {
//alert(errorInfo);
}
}
When I debug the application, the JS execution stops after this line:
xmlHttpReg.send(null);
It didn’t go to the next line:
if(xmlHttpReg.readyState==4)
The “data” is also not sent to the server.
What is wrong with my program, can ajax be called in an onunload function? What should I do to make it work?

Joomla 1.5 AJAX XMLHttpRequest Code Not Working in Joomla 2.5

Can someone tell me why this will not work in Joomla 2.5 but does in 1.5?
The error I'm receiving is - Uncaught TypeError: Cannot read property 'childNodes' of null ajax.php:33
If I enter in the url: index.php?option=com_mmg&controller=ajax&task=listModels&make_id=3
It outputs the ajxGetModels function like it's suppose to.
I know Joomla 2.5 Ajax Calls got changed or something like that but, I can't find a solution online to convert what I have below to the 2.5 version way of doing so.
Any help or direction would be very useful. Thank you.
function ajxGetModels(reload)
{
if (reload) {
var use_make = 'sel_make_id';
} else {
var use_make = 'make_id';
}
var make_id = document.getElementById(use_make).value;
var xhr = createXHR();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var model=document.getElementById("model_id");
try //Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(xhr.responseText);
}
catch(e)
{
try //Firefox, Mozilla, Opera, etc.
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(xhr.responseText,"text/xml");
}
catch(e) {alert(e.message)}
}
var options =xmlDoc.getElementsByTagName("options").item(0);
model.innerHTML='';
for (i=0; i < options.childNodes.length; i++){
var newoption=document.createElement("option");
var myoption=options.childNodes[i];
var newtext=document.createTextNode(myoption.childNodes[0].nodeValue);
newoption.setAttribute("value",myoption.getAttributeNode("id").value)
newoption.appendChild(newtext);
model.appendChild(newoption);
}
document.getElementById('model_id').disabled=false;
document.getElementById('year_id').innerHTML='';
document.getElementById('year_id').disabled=true;
if (reload) {
var preVal = document.getElementById('sel_model_id').value;
setMmgVal('model_id',preVal);
ajxGetYears(true);
}
} else {
alert('Error code ' + xhr.status);
}
}
}
xhr.open("GET","index.php?option=com_mmg&controller=ajax&task=listModels&make_id="+make_id,true);
xhr.send(null);
}
function createXHR() {
var xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
} catch (e) {}
}
return xhr;
}
It was not working because $error_reporting was set to "maximum" in configuration.php.
Still though - there has to be a better way.

ajax JSON dump as array

I have a simple ajax script which returns a json dump from the server:
var request = false;
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
function getIslandName() {
var islandGroup = document.getElementById("id_island_group").value;
var url = ".../find_island?island_group=" + escape(islandGroup);
request.open("GET", url, true);
request.onreadystatechange = updatePage;
request.send(null);
}
function updatePage() {
if (request.readyState == 4)
if (request.status == 200)
var data = JSON.decode(request.responseText);
update(data);
//document.getElementById("ajax_response").innerHTML = request.responseText;
else if (request.status == 404)
alert("Request URL does not exist");
else
alert("Error: status code is " + request.status);
}
function update(data) {
for (var key in data) {
alert(data[key]);
}
}
The problem seems to be in the updatePage() function. If I uncomment this line:
//document.getElementById("ajax_response").innerHTML = request.responseText;
the responseText json dump is displayed as expected. e.g.:
["Foo Island", "Bar Island", "Darwin Island"]
Also if I construct a fresh data array within the updatePage() function like so:
function updatePage() {
var string = "Something something ajax";
if (request.readyState == 4)
if (request.status == 200)
var data=new Array();
data[0]="Foo Island";
data[1]="Bar Island";
data[2]="Darwin Island";
update(data);
}
The update() function works as expected and gives the expected alert output.
Any suggestions as to what I'm doing wrong will be much appreciated.

How to use AJAX in Dart with async = true

I found a reference for an XMLHttpRequest
final req = new XMLHttpRequest();
req.open('GET', '${Sections.home}/data/$name', false);
req.send();
_htmlBody = req.responseText;
Full Source
But this is for async = false, is there a working example of async = true?
There is an example at https://code.google.com/p/dart/source/browse/branches/bleeding_edge/dart/samples/belay/bcap/bcap_client.dart
void privateInvoke(String ser, String method, String data,
SuccessI ski, FailureI fki) {
if (urlRegex.hasMatch(ser)) {
var req = new XMLHttpRequest();
req.open(method, ser, true);
req.on.readyStateChange.add(void _(evt) {
if (req.readyState == 4) {
if (req.status == 200) {
ski(req.responseText);
} else {
fki(new BcapError(req.status, req.statusText));
}
}
});
req.send(data);
return;
} else {
super.privateInvoke(ser, method, data, ski, fki);
}
}
also another asynchronous example in https://code.google.com/p/dart/source/browse/branches/bleeding_edge/dart/client/samples/total/src/ServerChart.dart
XMLHttpRequest request = new XMLHttpRequest();
request.on.readyStateChange.add((Event event) {
if (request.readyState == XMLHttpRequest.DONE && request.status == 200) {
callback("data:image/png;base64,${StringUtils.base64Encode(request.responseText)}");
}
});
...
request.open("POST", url, true, null, null);
request.setRequestHeader("Content-type", "text/plain");
request.overrideMimeType("text/plain; charset=x-user-defined");
print("Chart request: ${data}");
request.send(data);

Returning the responseText from ajax function

See the following function I have written
The code is to receive a url and send data to that page in post/get method.The function returns responseText from the target page
function $send(url,data,method)
{
if(window.XMLHttpRequest)
var connect = new XMLHttpRequest();
else
var connect = newActiveXObject("Microsoft.XMLHTTP");
if(connect)
{
method = method.toUpperCase();
if(method == 'GET')
{
url += '?'+data;
connect.open(method,url,true);
connect.send();
}
else
{
connect.setRequestHeader("Content-type","application/x-www-form-urlencoded");
connect.open(method,url,true);
connect.send(data);
}
connect.onreadystatechange = function()
{
alert(connect.readyState);
if(connect.readyState==4 &&connect.status == 200)
{
return connect.responseText ;
}
}
return "FALSE";
}
else
{
alert("$sendData() is not supported by your browser\n\nTRY ANOTHER BROWSER!!!");
return "FALSE";
}
}
As readstate is initially 0 and changes eventually,my function always return FALSE.Is there any way to return the responseText

Resources