AJAX Script Only Works in Firefox, But Not IE - ajax

My ajax script only works in Firefox and not ie why??
========================================
<html>
<head>
<script language=Javascript>
function Inint_AJAX() {
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {} //IE
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} //IE
try { return new XMLHttpRequest(); } catch(e) {} //Native Javascript
alert("XMLHttpRequest not supported");
return null;
};
function dochange(src) {
var req = Inint_AJAX();
req.onreadystatechange = function () {
if (req.readyState==4) {
if (req.status==200) {
document.getElementById(src).innerHTML=req.responseText; //retuen value
setTimeout("dochange('showResult')",5000);
}
if (!req.responseXML.documentElement && req.responseStream)
req.responseXML.load(req.responseStream);
}
};
req.open("GET", "ajax.php"); //make connection
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); // set Header
req.send(null); //send value
}
window.onLoad=dochange('showResult');
</script>
</head>
<body>
<div id="showResult"></div> <!–page result will be displayed here–>
</body>
</html>

Luke, use the Source! Better yet, use a proven JS library, e.g. jQuery. They deal with all of this cr*p and they do it better than you would ever have the time to do yourself.
Update:
Alex -- all kidding aside. The reason we are all telling you to use jQuery (or one of the other major Javascript libraries) is because getting this stuff to work on all (or even close to all) browsers is genuinely hard. As mangled as MS's handling of HTML and CSS is (and believe me, it sucks) their various implementations of JavaScript run the gamut from crap to huge-steaming-pile-of-crap. The various JS libraries give you standard, cross-browser ways of doing things -- stuff that it has taken real pros years to get right. You really, really don't want to waste your time on this stuff.
So, use a good library, get it working in Firefox using Firebug as your debugger, and you have a pretty good chance it will work in IE.

Related

Razor: Expected';' when declaring string in C# in JavaScript Block

In the MVC View code below, isLoggedInDb is underlined in green with a tooltip displaying Expected ';'. There clearly is a ;, and it is hard to Google for ; on top of it. I've seen that others have problems creating JavaScript serverside in this manner, so maybe it's not best practice. Should this be ignored, or is there a legitimate reason for Intellisense to complain?
#* SHTML Code Above *#
<script type="text/javascript">
#{
string isLoggedInDb;
if(Session["isLoggedInDb"] != null)
{
if(Session["isLoggedInDb"].ToString() == "1")
{
isLoggedInDb = "1";
}
else
{
isLoggedInDb = "0";
}
}
}
var dblogin=#(isLoggedInDb);
#*....etc*#
}
Edit:
It just occurred to me that building JavaScript programatically, probably is not the best idea, since it might be considered best practice to keep JavaScript in separate files, which are often cached. I think I should program hidden variables in the HTML that JavaScript reads instead. Maybe someone can confirm this.
I'm not 100% sure, but I would think the compiler is viewing it as C# code because you have it in a Razor code block #{ }
Try this:
<script type="text/javascript">
string isLoggedInDb;
#if(Session["isLoggedInDb"] != null)
{
if(Session["isLoggedInDb"].ToString() == "1")
{
<text>isLoggedInDb = "1";</text>
}
else
{
<text>isLoggedInDb = "0";</text>
}
}
</script>
As for building JS on the server, I personally can't stand the idea (I don't like merging any client/server/css code). I can't speak to its performance but I can say you are setting yourself up for a nightmare maintenance scenario keeping track of where all your JS is coming from, not to mention you lose the ability to easily debug and manage your scripts.
Without a doubt think you should have the approach of taking something similar to:
var isLoggedOn = #Model.IsLoggedInDb
IsLoggedInDb should be part of your ViewModel, your View should not be checking the session, this is very brittle, not easily testable, and the controllers purpose is to orchestrate the data for the presentation layer (view)
The code should work as is, however the Razor Parser is fighting the javascript intellisense, so you might want to move all your C# code logic out of the script tags since it doesnt need to be inside, like the following:
#{
string isLoggedInDb;
if(Session["isLoggedInDb"] != null)
{
if(Session["isLoggedInDb"].ToString() == "1")
{
isLoggedInDb = "1";
}
else
{
isLoggedInDb = "0";
}
}
}
#*....etc*#
<script type="text/javascript">
var dblogin=#(isLoggedInDb);
..etc..
</script>

Webkit (Chrome or Safari) way doing AJAX safely on onunload / onbeforeunload

In my tests Chrome (and I guess as any other webkit browser probably) is UNABLE to perform an AJAX request BEFORE leaving a page.
Imagine for instance, that you need to clean up something on the server because the user clicked on some link or left the page.
First thing I noticed is that window.onunload DOES NOT work anyhow on Chrome (Webkit?)
Once you are using window.onbeforeunload MAKE SURE you DON'T put in the the body like this: Cause it is ignored. YOU HAVE TO do window.onbeforeunload=function() {...} to make sure the binding is done (or use jquery or protoype libs for this)
WITHIN your onbeforeunload code a ASYNCHRONOUS Ajax like this WON'T work either:
var req = new XMLHttpRequest();
req.open("GET", "dosomething.page");
req.send(null);
(although this will WORK in Firefox)
It will work if ONLY if the request is made SYNCHRONOUS like this:
var req = new XMLHttpRequest();
req.open("GET", "dosomething.page",false);
req.send(null);
Although keep in mind that synchronous can cause the browser to hang for 2minutes if the server does NOT reply.
Also Firefox DOES NOT seem to work with onunload.
So in the end YOU have to provide with a different code path for each browser or browser family.
I haven't been able to test IE properly on this.
Does anyone know?
Is IE more like Chrome or FF in this?
or is it different to both as well?
IE seems to work just like Firefox (Gecko) in this particular case:
With this code you can make it work for WebKit, Firefox and IE:
// Browser detection
var Browser={
IE: !!(window.attachEvent && !window.opera),
Opera: !!window.opera,
WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
Gecko: navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
};
// Ensures the Ajax Get is performed... Asynchronously if possible
// or Synchronously in WebKit Browsers (otherwise it'll most probably fail)
function ensureAJAXGet(url, args) {
var async=!Browser.WebKit;
var finalUrl=url;
var sep="";
for (var key in args) {
sep=(sep=="?")?"&":"?";
finalUrl=finalUrl+sep+encodeURIComponent(key)+"="+encodeURIComponent(args[key]);
}
var req = new XMLHttpRequest();
req.open("GET", finalUrl,async);
req.send();
return req;
}
// Sets up an unload function for all browsers to work (onunload or onbeforeunload)
function onUnload(func) {
if(Browser.WebKit) {
window.onbeforeunload=func;
} else {
window.onunload=func;
}
}
A test html could be this:
var browser="?"
if (Browser.IE) {
browser="IE";
} else if (Browser.Opera) {
browser="Opera";
} else if (Browser.WebKit) {
browser="WebKit";
} else if (Browser.Gecko) {
browser="Gecko";
} else if (Browser.MobileSafari) {
browser="MobileSafari";
}
function unload() {
ensureAJAXGet("testajax.jsp", {"browser": browser});
}
onUnload(function() { unload(); });
That is:
To do something onunload you call onUnload() instead of directly using either window.onload or window.onunload. This ensures that the proper event is used (onbeforeunload in WebKit and onunload on the rest)
To sent some GET Ajax on an unload function use ensureAjaxGet() that will be asynchronous AJAX when possible and synchronous when needed (WebKit)

AJAX support in Opera Mobile

I've heard that Opera Mobile is supporting AJAX.
So I've tied to wrote a simple page that uses ...
Can anyone tell me what is wrong with this page?
<html>
<head>
<script language="javascript">
<!--
var fname = "nav_test.html";
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
function mkDoc()
{
if (xmlhttp.readyState == 4)
{
document.open();
document.writeln(fname);
document.writeln(xmlhttp.responseText);
document.close();
}
}
xmlhttp.onreadystatechange= mkDoc;
xmlhttp.open("GET", fname, true);
xmlhttp.send(null);
-->
</script>
</head>
<body />
</html>
In nav_test.html, which is in the same directory as the file shown above, there is only one line:
<p>test</p>
After loading it with Opera Mobile 11 it displays only
"nav_test.html".
I've checked and this page works with Nokia N900 default browser. But it doesn't with Midori browser. I have also tested it with Firefox browser on my PC and it works there as well.
I wish to be able to run this page under Opera since Opera ca be installed on most of modern mobile phones.
Of course it supports AJAX. Just run any AJAX framework's showcase on it (such as Ext's showcase).
As for your code, at best download any working example and modify it, if you start learning JavaScript. Don't also write your own AJAX invocation support for various browsers, there's no need for it, because it was already written a thousend times. At best use prototype or jQuery - you can find tons of examples.

Ajax Broken in Browsers works in Android

I can run this code in Android app (using PhoneGap adn jQuery Mobile) but not on desktop browsers.
It gives me a syntax error in firebug for this line =
var TicketList = eval("(" + ajax.responseText + ")");
Here is the code
// JScript source code
// ran on body load
function doJsStuff()
{
var ajax = AJAX();
ajax.onreadystatechange = function () {
if (ajax.readyState == 4) {
var TicketList = eval("(" + ajax.responseText + ")");
if (TicketList.ListCount > 0) {
document.getElementById("opencount").innerHTML = TicketList.ListCount +" Open Tickets";
for (Ticket in TicketList.Tickets) {
// add stuff to DOM
//AddTicketToList(TicketList.Tickets[Ticket]);
}
}
else {
document.getElementById("opencount").innerHTML = "All Tickets Reviewed";
DisplayNoresults();
}
}
}
ajax.open("GET", "http://website.com/ListTicketsRequest.ashx?PageNumber=1&PageSize=1&Status=Open", true);
ajax.send(null);
//document.addEventListener("deviceready", onDeviceReady, false);
//event to check for PhoneGap
//$('ul').listview('refresh');
$('#mtickets').page();
//showVars();
}
function AJAX()
{
var xmlHttp;
try
{
xmlHttp = new XMLHttpRequest();
}
catch (e)
{
}
return xmlHttp;
}
**TicketList is a variable in the JSon that comes across like this=
{"Tickets" : [{"TicketID": "1054","Category": "N/A","SubmittedUserID": "bob.thebuilder","ShortDescription": "test question QID:16668","CreationDate": "2/16/2011 12:24:19 PM","TicketStatus": "Open","LongDescription": "Something is wrong with this question I know I hve the right answer but it keeps telling me I'm wrong"},{"TicketID": "1053","Category": "Mission Support","SubmittedUserID": "dave","ShortDescription": "Make courseware revisions","CreationDate": "2/16/2011 9:34:48 AM","TicketStatus": "Open","LongDescription": "Find help tickets generated by users for possible courseware update."}], "PageCount": "6", "ListCount": "11"}
Note about PhoneGap If you are trying to include phoengap functions in a place where the code may also be executed on in a browser make sure you only add the phone gap function with on "deviceready" or your browser will not render. Example:
function onload(){
//event to check for PhoneGap
document.addEventListener("deviceready", onDeviceReady, true);
}
...
function onDeviceReady()
{
// Now PhoneGap API ready
vibrate(90); // vib to ack pg ready
$("a").click(function(event){
vibrate(30); // add 30 sec vib to all links
});
}
My immediate response would be to use jQuery's getJSON method, since you're aready using jQuery. jQuery's AJAX provides a much broader base of browser compatibility. Also, every time you use eval(), a small baby somewhere cries.
var url = "http://website.com/ListTicketsRequest.ashx?PageNumber=1&PageSize=1&Status=Open";
$.getJSON(url ,function(TicketList){
if (TicketList.ListCount > 0) {
$("#opencount").html(TicketList.ListCount +" Open Tickets");
for (Ticket in TicketList.Tickets) {
...
}
} else {
$("#opencount").html("All Tickets Reviewed");
DisplayNoresults();
}
});
If this still doesn't work for you, ensure that the JSON being returned is valid. But please stick to this method, and don't use eval!!
SIMPLIFIED UPDATE
var url = "http://website.com/ListTicketsRequest.ashx?PageNumber=1&PageSize=1&Status=Open";
$.getJSON(url ,function(AnyNameYouWant){
alert(AnyNameYouWant.ListCount + " Open Tickets");
});
UPDATE USING 'DATA'
If your url becomes too long, you might begin to encounter problems. It is suggested to pass the url data via the data argument.
var url = "http://website.com/ListTicketsRequest.ashx";
var data = "PageNumber=1&PageSize=1&Status=Open";
$.getJSON(url, data, function(AnyNameYouWant){
alert(AnyNameYouWant.ListCount + " Open Tickets");
});
Looking at your code, it seems likely to me that the syntax error isn't in the code you posted, but instead is contained in the JSON object you're evaluating in ajax.responseText. Take a look at the data being returned by the AJAX request. Is it valid Javascript? Does the page you're calling return something different to desktop browsers vs mobile? Is there an error message where the JSON code should be?
Another possibility: Is your app running on website.com? If not, Firefox is probably blocking the XMLHttpRequest from functioning properly. Firefox 3 and below block cross-site AJAX requests. Firefox 3.5 seems to allow some exceptions.

ajax issue on IE8

I have an old site that uses xml documents, and when I created it i had firefox and IE7 to test on, and it worked just great. Since then, IE8 appeared, and it seams that the site does no longer work properly.
This is the current code:
if (window.XMLHttpRequest)
{
XMLHttpRequestObject = new XMLHttpRequest();
XMLHttpRequestObject.overrideMimeType("text/xml");
XMLHttpRequestObject.open("GET", "produse.xml", true);
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4)
{
xmlDocument = XMLHttpRequestObject.responseXML;
removeWhitespace(xmlDocument);
}
}
XMLHttpRequestObject.send(null);
}
else if (window.ActiveXObject)
{
xmlDocument= new ActiveXObject("Microsoft.XMLDOM");
xmlDocument.async=false;
if (xmlDocument .readyState == 4)
{
xmlDocument.load("produse.xml");
}
}
But I get this error:
Message: Object doesn't support this property or method
Line: 19
Char: 3
Code: 0
which relates to:
XMLHttpRequestObject.overrideMimeType("text/xml");
What should I use instead?
This page shows what the differences are between firefox/ie/ie8 are and has some examples of how to do it:
http://www.javascriptkit.com/jsref/ajax.shtml
Mostly it says that IE8 does not support this method and you have to make sure your server is adding the proper header (text/xml) to the outgoing response.
It also has a link to http://www.javascriptkit.com/dhtmltutors/ajaxgetpost3.shtml that explains the common pitfalls and IE problems.
It says do:
if (mygetrequest.overrideMimeType)
mygetrequest.overrideMimeType('text/xml')
jQuery would be my choice. It is a lot faster and is cross browser supported and on a CDN.
You could strip that code down to just a few lines.
$.get('ajax/test.html', function(data) {
$('.result').html(data);
alert('Load was performed.');
});

Resources