Can someone tell me which are the main differences, or aspects that I should look for, if the AJAX I'm using works perfectly on IE but does not work at all on Google Chrome or Firefox?
Are there some things that IE accept but the others dont? Or is there any code that I should add in order to works for all the browsers?
I dont know if this affect something, but I'm working with PYTHON!
Here is the code that all the Ajax functions use as base:
var xmlhttp;
var request = true;
function GetXmlHttpObject() {
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml12.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
return false; //or null
}
}
}
if (!request)
alert ("Error initializing XMLHTTPRequest!");
return request;
}
After doing this, I use a regular Javascript function which includes something like this:
var url = 'evaluacionDesempenoBD.py?cadena=' + cadena + '&comentario=' + comentario + '&idEvaluacion=' + idEvaluacion + '&seccion=' + seccion;
xmlhttp = GetXmlHttpObject();
if (!xmlhttp) {
alert ("Browser does not support HTTP Request");
return;
}
var xml = xmlhttp;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);'''
I hope i made myself clear
Thanks a lot!
You probably use the ActiveX AJAX object and not the native implementation supported by all browsers.
Use new XMLHttpRequest() to create an AJAX object on browsers with native implementation.
Wikipedia has an awesome article on XMLHttpRequest with some sample code that should help you get your AJAX thingie work across all browsers.
Perhaps you might be facing a problem due to browser differences with regards to the internals of the XMLHttpRequest object, particularly how you handle readystate changes. Quirksmode has a document on this.
Related
I'm trying to use the API from https://www.themoviedb.org/. (The key is free and can be changed easily, so I'll include it because without it, you can’t even test their functions).
Now my JavaScript is working fine in FF when it's hosted local, but not on GitHub pages.
Here is a function that doesn’t work. Error is:
NetworkError: A network error occurred.
…and it appears to happen after bhttp.send();.
function getMovieDetails() {
var reqURL = "https://api.themoviedb.org/3/movie/latest?api_key=afe4e10abbb804e2b4a4f8a3ef067ad5&language=en-US";
var bhttp = new XMLHttpRequest();
bhttp.open("GET", reqURL, false);
bhttp.setRequestHeader("Content-type", "json");
bhttp.send();
var response = JSON.parse(bhttp.responseText);
var str = JSON.stringify(response, null, 2);
return response;
}
console.log(getMovieDetails());
It works fine in Chrome. Googling appears to indicate it’s a CORS problem, but as far as I know GitHub pages supports CORS, so I don't know what I'm doing wrong.
I'm not a firefox user, so you will need to test this. But if the theory of async blocking is true this should work.
I've modified it to use a simple callback, personally I wouldn't use callbacks but would make into promises, but that's another question :)
function getMovieDetails(callback) {
var reqURL = "https://api.themoviedb.org/3/movie/latest?api_key=afe4e10abbb804e2b4a4f8a3ef067ad5&language=en-US";
var bhttp = new XMLHttpRequest();
bhttp.open("GET", reqURL, true);
bhttp.setRequestHeader("Content-type", "json");
bhttp.onload = function() {
if (bhttp.readyState === 4) {
if (bhttp.status === 200) {
callback(JSON.parse(bhttp.responseText));
} else {
console.error(bhttp.statusText);
}
}
};
bhttp.send();
}
getMovieDetails(function (movie) {
console.log(movie);
});
Alright looks like skirtle was correct, the issue was the firefox addon Privacy-Badger blocking the API. I feel pretty stupid now but at least my code is now pretty clean.
i have just started working on ajax for my chat application which i am making in php.
While studying ajax online I cam across 2 ways in on different sites where ajax had been implemented.
What is the difference between these 2 implementations of ajax?
Any help will be greatly appreciated :)
First Implementation-
<script type"text/javascript">
$(document).ready(function() {
var dept = '<?php echo $deptId; ?>';
var interval = setInterval(function() {
$.ajax({
url: 'scripts/php/Chat.php',
data: {dept:dept},
success: function(data) {
$('#messages').html(data);
}
});
}, 1000);
});
</script>
Second Implementation-
<script language="javascript" type="text/javascript">
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
var age = document.getElementById('age').value;
var wpm = document.getElementById('wpm').value;
var sex = document.getElementById('sex').value;
var queryString = "?age=" + age ;
queryString += "&wpm=" + wpm + "&sex=" + sex;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
ajaxRequest.send(null);
}
Functionality-wise, it could be argued that there is no difference between them.
That said, the first "difference" between them is that the first method is using JQuery, and thus to use it, you need to have the JQuery Javascript library included in your project or the page where you need the ajax functionality. The second method, however, uses "plain ole Javascript".
Again, the first (JQuery) method, handles a lot of the "dirty" details for you, providing you with an ($.ajax) interface and requiring only that you pass in some parameters:
url : The URL you wish to call
data : The data (GET or POST) you wish to pass to the URL
success : The callback function that should be executed when the ajax request successfully returns.
In doing this, this method abstracts the internal implementation from you. For example, it handles for you the following:
browser-sniffing/capabilities detection
readyStateChange (event) checks
and some other mundane details.
Besides, also, using the second method, you can rest-assured that your code will mostly work in the majority of scenarios (if not all), if you "honour" the interface specification of the $.ajax call. Using the second method, however, you'll need to do a lot of testing and checks to ensure that your code works across all browser and platform types.
Your first code use jQuery. JQuery is a rich js lib that helps you coding quickly. See http://api.jquery.com/ (and in your particular case : http://api.jquery.com/jQuery.ajax/
Your second code is only javascript without any help from other library. It uses the XMLHttpRequest wich allows ajax call. See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
The use of jQuery is easier but some find it "overkill" :)
I'm pretty sure it's a security issue keeping me from doing this, but I wonder if there's a workaround I don't know of...
I have a script to inject a user's email into the contact DB of my client and it's bombing in IE but working in FF, Chrome (as usual). Just wondering if I can add the server to the trust or something to make it work?
<script type="text/javascript">
window.onload = init;
//Global XMLHTTP Request object
var XmlHttp;
function CreateXmlHttp() {
//Creating object of XMLHTTP in IE
try {
XmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (ex) {
XmlHttp = null;
}
}
//Creating object of XMLHTTP in Mozilla and Safari
if (!XmlHttp && typeof XMLHttpRequest != "undefined") {
XmlHttp = new XMLHttpRequest();
}
}
function init() {
var x = document.getElementsByName("btnContinue");
x[0].onclick = submitForm;
}
function submitForm() {
var x = document.getElementsByName('Email');
if (x[0].value.length > 0) {
CreateXmlHttp();
XmlHttp.open("POST", "https://app.icontact.com/icp/signup.php", false);
XmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
XmlHttp.send("redirect='http://www.xyz.com/articles.asp?ID=97'&errorredirect='http://www.xyz.com/articles.asp?ID=256'&fields_email=" +
x[0].value + "&listid=123&specialid:123=YP7I&clientid=123&formid=123&reallistid=1&doubleopt=0&Submit=Submit");
}
}
</script>
I'd appreciate any insight.
Thanks!
My first suggestion would be to try creating XMLHttpRequest before ActiveX Objects. IE7 and up DO support AJAX the way other browsers do.
Next, you should use relative paths in the open() method. Although I think form your question it's something that'll need to be able to run on any site? In that case I'd suggest creating a form and an iframe and using the "old" method.
It is a same-origin policy issue. The allow access content headers may be set, but the IE ActiveXObject won't use them. XMLHttpRequests obey the headers and will work on browsers that support them.
See this question:
AJAX Permission Denied On IE?
Though it doesn't look like they found a solution for an IE compatible cross-domain POST...
If you could proxy it through your web server (Make a POST to your server), and have the server make the POST, your problem would be solved.
On new browsers, you can use cross-domain XHR if you can have a special HTTP header on the page you request.
http://ejohn.org/blog/cross-site-xmlhttprequest/
Or you can use dynamic script loading.
I used to be a programmer but now do periodic "scripting." I'm trying to create an Ajax-based game.
I have a .php file with the following javascript:
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if ( window.ActiveXObject ) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.SML.HTTP");
}
Then whenever I want to use a request I have, for example:
if ( XMLHttpRequestObject ) {
XMLHttpRequestObject.open("GET","gameinfo.php?cmd=setgame&game=" + arg);
XMLHttpRequestObject.onreadystatechange = function() {
// handler ...
}
XMLHttpRequestObject.send(null);
}
I don't understand why I need to always be sure the XMLHttpRequest object exists before I refer to it. Didn't I create it? How could it not exist? Is this just good coding practice or is there some real risk?
OK, I'm convinced to try jQuery. But if I were sticking to pure javascript, would this be safe?
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if ( window.ActiveXObject ) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.SML.HTTP");
} else {
alert("Sorry but it looks like this game won't work in your browser.");
}
Then whenever I want to use a request I have, for example:
XMLHttpRequestObject.open("GET","gameinfo.php?cmd=setgame&game=" + arg);
XMLHttpRequestObject.onreadystatechange = function() {
// handler ...
}
XMLHttpRequestObject.send(null);
The way that your IFs are structured, there's some potential, logically, for you to not create anything. Basically you're looking for if window.XMLHttpRequest exist OR IF window.ActiveXObject exists, you create your request object. But if neither of those instances exist, you get nothing.
So, what may perhaps be a better check is to put a check afterwards to alert the user "Hey, I can't seem to find any kind of XMLHttpRequestObject, so I can't do much from here.".
When can this happen? Beats me, but the simple fact is that the way your logic is laid out, it POTENTIALLY can happen.
Just to start out here: Use jQuery it abstracts messy things with bad cross-browser compatibility like that.
That first block of code is for feature detection, since IE handles XMLHttpRequests differently to other browsers, you need to figure out which object to use.
The check is there on the off-chance that the compatibility code (the if (window.XMLHttpRequest) {... stuff) has missed a case, otherwise you'll get nasty errors.
I will repeat myself, because this is very important, use jQuery. It is hands down the most powerful javascript library out there. For an example, the request you want to do is
$.get("gameinfo.php",
{cmd: "setgame", game: arg},
function () {
//Success function
}
);
And that handles all of the cross-browser stuff transparently and just works. (There are more in-depth function on jQuery if you need them though)
It's possible that both conditions are wrong.
But if you're creating an ajax-based game, I realllly encourage you to check out jquery or another js framework...
Actually, I did exactly the same few years ago. I started building an ajax game, from scratch, using raw javascript. Then I discovered jQuery... It's really fast to learn.
How do you want then to catch it up if it exists? Are you sure that it will be 100% created? Checked all browsers? Checked all possibilities?
This might help. You check if XMLHttpRequest exist, so you can use something older that connects to the server for data. Note: I noticed the Jquery AJAX seems to work more consistently if you have a lot of these being called. If you fire this one off a lot it randomly buggers up.
var xmlHttp = null;
if (window.XMLHttpRequest) { //typeof XMLHttpRequest !== 'undefined'
xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
var versions = [
"MSXML2.XmlHttp.6.0",
"MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"];
var xhr;
for (var i = 0; i < versions.length; i++) {
try {
xmlHttp = new ActiveXObject(versions[i]);
break;
} catch (e) {
}
}
}
if (xmlHttp != null) {
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
var data = JSON.parse(xmlHttp.responseText);
s_DateNow = data;
dt_Now = new Date(data);
}
}
xmlHttp.onerror = function () {
}
xmlHttp.open("POST", "/Home/ServerDate/", true);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.send('__RequestVerificationToken=' + sToken);
}
else {
document.getElementById("spParkingTracker").innerHTML = "Browser not supported!";
}
I'm trying to create an ajax connection to a weather xml feed and then parse returned data. I don't have any issues making a connection via IE, but for some reason I don't have any luck in FF or Safari. Basically what I'm doing is running an html file that contains the following code.
<html>
<script type="text/javascript" language="javascript">
function makeRequest(zip) {
var url = 'http://rdona.accu-weather.com/widget/rdona/weather-data.asp?location=' + zip;
//var httpRequest;
var httpRequest = false;
if (window.XMLHttpRequest) {
document.write("xmlhttprequest");
httpRequest = new XMLHttpRequest();
if (httpRequest.overrideMimeType) {
httpRequest.overrideMimeType('text/xml');
// See note below about this line
}
}
else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = function() { alertContents(httpRequest); };
httpRequest.open('GET', url, true);
httpRequest.send('');
}
function alertContents(httpRequest) {
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
makeRequest(84405);
</script>
</html>
Any help and or suggestions would be greatly appreciated.
I'm afraid you will run into some issues because of same origin policy, meaning that you cant do XMLHTTPRequests to another domain.
Not even jQuery (which you really should check out anyways) can help you with that.
I strongly suggest you use a framework to do this sort of thing. Frameworks will do all of the browser compatibility stuff for you.
On the other hand, if you are interested in how to do this as an academic exercise... still get a framework! See how the framework does it and you will immediately learn all of the pitfalls.
Mootools is my framework of choice.
In order to perform a basic AJAX request in Mootools you would do the following:
window.addEvent('domReady', function() {
new Request({
'url': "The url where you want to send the request
'data': "Some data to send. It can be an object."
}).send();
});
Full documentation for the Request class can be found here.
If you want to see how Mootools implements cross-browser AJAX, you can find the source of the Request class here.
You'll find the source for Browser.Request particularly useful.
For cross browser stuff, I recommend you use a library like JQuery because it will quietly smooth over IE vs Firefox vs Safari etc issues. Also to make the code format properly, use the 101010 button in the toolbar.