AJAX works in IE but not in Firefox or Chrome - ajax

I'm new to using AJAX and my code works in Internet Explorer but not in Firefox or Chrome.
I do not know what it is exactly what should change in the code ...
// I think that error should be here :-)
function cerrar(div)
{
document.getElementById(div).style.display = 'none';
document.getElementById(div).innerHTML = '';
}
function get_ajax(url,capa,metodo){
var ajax=creaAjax();
var capaContenedora = document.getElementById(capa);
if (metodo.toUpperCase()=='GET'){
ajax.open ('GET', url, true);
ajax.onreadystatechange = function() {
if (ajax.readyState==1){
capaContenedora.innerHTML= "<center><img src=\"imagenes/down.gif\" /><br><font color='000000'><b>Cargando...</b></font></center>";
} else if (ajax.readyState==4){
if(ajax.status==200){
document.getElementById(capa).innerHTML=ajax.responseText;
}else if(ajax.status==404){
capaContenedora.innerHTML = "<CENTER><H2><B>ERROR 404</B></H2>EL ARTISTA NO ESTA</CENTER>";
} else {
capaContenedora.innerHTML = "Error: ".ajax.status;
}
} // ****
}
ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
ajax.send(null);
return
}
}
function creaAjax(){
var objetoAjax=false;
try{objetoAjax = new ActiveXObject("Msxml2.XMLHTTP");}
catch(e){try {objetoAjax = new ActiveXObject("Microsoft.XMLHTTP");}
catch (E){objetoAjax = false;}}
if(!objetoAjax && typeof XMLHttpRequest!='undefined') {
objetoAjax = new XMLHttpRequest();} return objetoAjax;
}
//These functions are connected with a form
function resultado(contenido){
var url='ajax/buscar.php?'+ contenido +'';// Vota Resultado
var capa='resultado';
var metodo='get';
get_ajax(url,capa,metodo);
}
function paginas(contenido){
var url='ajax/paginar.php?'+ contenido +'';// Vota Paginas
var capa='paginas';
var metodo='get';
get_ajax(url,capa,metodo);
}

Strongly suggest that you use a lib like jQuery that encapsulates a lot of what you're doing above, masking cross-browser issues (current and future). Even if you don't want to use jQuery site-wide, you could still use it just for its AJAX functionality.

Related

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

ajax add_endRequest never fires, on iPad only

I have some asp code in which I have a set of Telerik grids on separate jQueryUI tabs, and I am lazy-loading the grid data so that the grids only bind to live data if you actually view the tab that contains them. The rebind causes an ajax postback, and I have added an endRequest handler to re-apply the jQueryUI formatting once the request returns. This is working in Firefox, Chrome, Safari, and IE. But on the iPad the endRequest handler never fires. Any suggestions on how to troubleshoot this?
My code is as follows:
<script language="javascript" type="text/javascript">
(function ($, Sys) {
function setUpEmsDashboard() {
$('#emsDashboard').dnnTabs().dnnPanels();
$('#dInvoiceLink').click(function () {
lazyLoadOutstandingInvoicesGrid();
});
if ($('#dInvoice').is(':visible')) {
lazyLoadOutstandingInvoicesGrid();
}
$('#dCountsForStaffLink').click(function () {
lazyLoadCountsForStaffGrids();
});
if ($('#dCountsForStaff').is(':visible')) {
lazyLoadCountsForStaffGrids();
}
}
$(document).ready(function () {
setUpEmsDashboard();
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function () {
setUpEmsDashboard();
});
});
} (jQuery, window.Sys));
</script>
<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
<script language="javascript" type="text/javascript">
function lazyLoadOutstandingInvoicesGrid() {
var grid = $find("<%=OutstandingInvoicesGrid.ClientID%>");
var masterTableView = grid.get_masterTableView();
var name = masterTableView.get_name();
if (name == 'Temp Data') {
masterTableView.rebind();
}
return true;
}
function lazyLoadCountsForStaffGrids() {
var countsBySalesRegionGrid = $find("<%=CountsBySalesRegionGrid.ClientID%>");
var cbsrMasterTableView = countsBySalesRegionGrid.get_masterTableView();
var cbsrName = cbsrMasterTableView.get_name();
if (cbsrName == 'Temp Data') {
cbsrMasterTableView.rebind();
return true;
}
var countsBySupplierTypeGrid = $find("<%=CountsBySupplierTypeGrid.ClientID%>");
var cbstMasterTableView = countsBySupplierTypeGrid.get_masterTableView();
var cbstName = cbstMasterTableView.get_name();
if (cbstName == 'Temp Data') {
cbstMasterTableView.rebind();
return true;
}
var countsByCategoryGrid = $find("<%=CountsByCategoryGrid.ClientID%>");
var cbcMasterTableView = countsByCategoryGrid.get_masterTableView();
var cbcName = cbcMasterTableView.get_name();
if (cbcName == 'Temp Data') {
cbcMasterTableView.rebind();
}
return true;
}
</script>
</telerik:RadCodeBlock>
Never mind, I found the issue. What I had was a race condition where for some browsers in some circumstances, the grid objects were null.
I changed:
function lazyLoadOutstandingInvoicesGrid() {
var grid = $find("<%=OutstandingInvoicesGrid.ClientID%>");
var masterTableView = grid.get_masterTableView();
var name = masterTableView.get_name();
if (name == 'Temp Data') {
masterTableView.rebind();
}
return true;
}
to:
function lazyLoadOutstandingInvoicesGrid() {
var grid = $find("<%=OutstandingInvoicesGrid.ClientID%>");
if (typeof (grid) !== 'undefined' && grid != null) {
var masterTableView = grid.get_masterTableView();
var name = masterTableView.get_name();
if (name == 'Temp Data') {
masterTableView.rebind();
}
return true;
}
}
...and made similar changes to the other function. That prevented the object reference error that had been silently causing the rest of the main function to fail. Now it works consistently.

Firefox, Mozilla validator error

I am getting this one error when I use the Mozilla validator:
This is the JS file:
const STATE_START = Components.interfaces.nsIWebProgressListener.STATE_START;
const STATE_STOP = Components.interfaces.nsIWebProgressListener.STATE_STOP;
// Version changes:
// It used to get the lists from a PHP file, but that was putting too much of a strain on the servers
// now it uses xml files.
// Randomizes the servers to load balance
// Mozilla editor suggested no synchronous file gets, so changed it to asynchronous
// Added one more server to help with the updates (Ilovemafiaafire.net)
// Edited some redirect code that some idiots were spreading FUD about.
var xmlDoc = null;
var quickFilter_100_count_redirect_url='http://www.mafiaafire.com/help_us.php';
var countXmlUrl = 0;
//var xmlUrl = 'http://elxotica.com/xml-update/xml-list.php';
var xmlUrl = new Array(4);
xmlUrl[0] = 'http://mafiaafire.com/xml-update/mf_xml_list.xml';
xmlUrl[1] = 'http://ifucksexygirls.com/xml-update/mf_xml_list.xml';
xmlUrl[2] = 'http://ezee.se/xml-update/mf_xml_list.xml';
xmlUrl[3] = 'http://ilovemafiaafire.net/mf_xml_list.xml';
xmlUrl.sort(function() {return 0.5 - Math.random()})
var realXmlUrl = xmlUrl[countXmlUrl];
var notificationUrl = 'http://mafiaafire.com/xml-update/click_here_for_details.php';
var root_node = null;
var second_node = null;
var timervar = null;
var mafiaafireFilterUrl = '';
//Calling the interface for preferences
var prefManager = Components.classes["#mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
var quickfilter_mafiaafire =
{
// get the domain name from the current url
get_domain_name:function()
{
var urlbar = window.content.location.href;
domain_name_parts = urlbar.match(/:\/\/(.[^/]+)/)[1].split('.');
if(domain_name_parts.length >= 3){
domain_name_parts[0] = '';
}
var dn = domain_name_parts.join('.');
if(dn.indexOf('.') == 0)
return dn.substr(1);
else
return dn;
},
// send ajax request to server for loading the xml
request_xml:function ()
{
//alert(countXmlUrl);
http_request = false;
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
if (!http_request)
{
return false;
}
http_request.onreadystatechange = this.response_xml;
http_request.open('GET', realXmlUrl, true);
http_request.send(null);
xmlDoc = http_request.responseXML;
},
// receive the ajax response
response_xml:function ()
{
if (http_request.readyState == 4)
{
if(http_request.status == 404 && countXmlUrl<=3)
{
countXmlUrl++;
//alert(xmlUrl[countXmlUrl]);
realXmlUrl = xmlUrl[countXmlUrl];
quickfilter_mafiaafire.request_xml();
}
if (http_request.status == 200)
{
xmlDoc = http_request.responseXML;
}
}
},
filterUrl:function()
{
var urlBar = window.content.location.href;
//check if url bar is blank or empty
if (urlBar == 'about:blank' || urlBar == '' || urlBar.indexOf('http')<0)
return false;
//1. get domain
processing_domain = this.get_domain_name();
//alert(processing_domain);
//Couldn't fetch the XML config, so returning gracefully
if(xmlDoc == null)
return false;
try
{
root_node = '';
// Parsing the xml
root_node = xmlDoc.getElementsByTagName('filter');
for(i=0;i<=root_node.length;i++)
{
second_node = '';
second_node = root_node[i];
if(second_node.getElementsByTagName('realdomain')[0].firstChild.nodeValue == processing_domain)
{
this.notificationBox();
mafiaafireFilterUrl = '';
mafiaafireFilterUrl = second_node.getElementsByTagName('filterdomain')[0].firstChild.nodeValue;
timervar = setTimeout("quickfilter_mafiaafire.redirectToAnotherUrl()",1500);
//window.content.location.href = second_node.getElementsByTagName('filterdomain')[0].firstChild.nodeValue;
//this.redirectToAnotherUrl(this.filterUrl);
//timervar = setInterval("quickfilter_mafiaafire.redirectToAnotherUrl(quickfilter_mafiaafire.filterUrl)",1000);
}
}
}
catch(e){
//alert(e.toString());
}
},
// This function is called for showing the notification
notificationBox:function()
{
try{
// Firefox default notification interface
var notificationBox = gBrowser.getNotificationBox();
notificationBox.removeAllNotifications(false);
notificationBox.appendNotification('You are being redirected', "", "chrome://quickfilter/content/filter.png", notificationBox.PRIORITY_INFO_HIGH, [{
accessKey: '',
label: ' click here for details',
callback: function() {
// Showing the notification Bar
window.content.location.href = notificationUrl;
}
}]);
}catch(e){}
},
redirectToAnotherUrl:function()
{
var qucikFilterRedirectCount = '';
//Read the value from preferrences
qucikFilterRedirectCount = prefManager.getCharPref("extensions.quickfilter_redirect_count");
//alert(qucikFilterRedirectCount);
if(qucikFilterRedirectCount % 15 == 0)
{
// Disable for now, can comment this entire section but this is the easier fix incase we decide to enable it later
//window.content.location.href = quickFilter_100_count_redirect_url+"?d="+mafiaafireFilterUrl;
window.content.location.href = mafiaafireFilterUrl;
}
else
{
window.content.location.href = mafiaafireFilterUrl;
}
qucikFilterRedirectCount = parseInt(qucikFilterRedirectCount)+1;
prefManager.setCharPref("extensions.quickfilter_redirect_count",qucikFilterRedirectCount);
}
}
var quickfilter_urlBarListener = {
QueryInterface: function(aIID)
{
if (aIID.equals(Components.interfaces.nsIWebProgressListener) ||
aIID.equals(Components.interfaces.nsISupportsWeakReference) ||
aIID.equals(Components.interfaces.nsISupports))
return this;
throw Components.results.NS_NOINTERFACE;
},
//Called when the location of the window being watched changes
onLocationChange: function(aProgress, aRequest, aURI)
{
// This fires when the location bar changes; that is load event is confirmed
// or when the user switches tabs. If you use myListener for more than one tab/window,
// use aProgress.DOMWindow to obtain the tab/window which triggered the change.
quickfilter_mafiaafire.filterUrl();
},
//Notification indicating the state has changed for one of the requests associated with aWebProgress.
onStateChange: function(aProgress, aRequest, aFlag, aStatus)
{
if(aFlag & STATE_START)
{
// This fires when the load event is initiated
}
if(aFlag & STATE_STOP)
{
// This fires when the load finishes
}
},
//Notification that the progress has changed for one of the requests associated with aWebProgress
onProgressChange: function() {},
//Notification that the status of a request has changed. The status message is intended to be displayed to the user.
onStatusChange: function() {},
//Notification called for security progress
onSecurityChange: function() {},
onLinkIconAvailable: function() {}
};
var quickfilter_extension = {
init: function()
{
//Initiating the progressListerner
gBrowser.addProgressListener(quickfilter_urlBarListener, Components.interfaces.nsIWebProgress.NOTIFY_STATE_DOCUMENT);
//Load the block list xml form server
quickfilter_mafiaafire.request_xml();
},
uninit: function()
{
// Remove the progressListerner
gBrowser.removeProgressListener(quickfilter_urlBarListener);
}
};
// window.addEventListener("load", function () { TheGreatTest1.onFirefoxLoad(); }, false);
// this function is Called on window Onload event
window.addEventListener("load", function(e) {
quickfilter_extension.init();
}, false);
window.addEventListener("unload", function(e) {
quickfilter_extension.uninit();
}, false);
Can you tell me how to squash that error please?
It looks like the offending line is setTimeout("quickfilter_mafiaafire.redirectToAnotherUrl()",1500);
The setTimeout function can take a string (which then essentially gets eval'd) or a function (which gets called). Using a string is not recommended, for all the same reasons that using eval is not recommended. See https://developer.mozilla.org/en/DOM/window.setTimeout
In this case, the simplest fix would be to change it to setTimeout(function() { quickfilter_mafiaafire.redirectToAnotherUrl(); },1500);

Resources