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.
Related
I've been looking at how to integrate AJAX calls into a Python Django application and I'm somewhat new to both. I have been following the advice here:
https://www.quora.com/Can-I-execute-a-Python-function-from-JavaScript
Which led to this and this respectively for AJAX and Django advice.Both made pretty good sense to me. The desired end result is that a template in this fourth folder down (dashboard) call a function in a file called logic.py under the api folder above it:
In a JavaScript file hooked up to my django template, I have the following code I stole from the AJAX resource I listed above and made some light edits to:
window.onerror = function() {
debugger;
}
// browser - safety
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if(window.ActiveXObject) { // ie
try {
request = new ActiveXObject('Msxml2.XMLHTTP');
}
catch(e) {
try {
request = new ActiveXObject('Microsoft.XMLHTTP');
}
catch(e) {}
}
}
function step2() {
console.log('something');
}
function testLogin() {
request.open('POST', '../../../api/logic');
// I've also been trying ^^^ logic.py, if it matters
request.send(null);
console.log('testLogin ran');
step2();
}
request.onreadystatechange = function () {
if(request.readystate === 4) {
if(request.status === 200) {
console.log(request.responseText);
}
}
}
It still is hooked up to a URL POST action in the django views, so when I hit the submit button in question I see the following two requests get generated:
That is the correct filepath for that location:
So I'm wondering if I'm missing something either about the AJAX setup, or the way it needs to interact with Django, or some combination of the two. Other resources I've been consulting in looking into this:
Call Python function from Javascript code
https://codehandbook.org/python-flask-jquery-ajax-post/
https://www.makeuseof.com/tag/python-javascript-communicate-json/
https://bytes.com/topic/javascript/answers/737354-how-call-python-function-javascript
And I originally started way earlier in the day so there were a few more, but needless to say I didn't see my issue immediately from looking at any of them. Any help is much appreciated.
So this wound up being a quirk of the Django url setup, I can't believe I didn't figure it out but I hadn't been in that part of the code base for some time.
In our urls.py script, the place I was pinging (which was in the location of the URL described) had a redirect on it and for that reason, the traffic wasn't going to the place I thought.
I'm wondering what is the simplest way to fill a div by grabbing a PHP script (and send data like POST or GET) to process what data to return.
But without the use of a library... All I ever find is prototype and jquery examples.
Has any one done this without a library?
var xmlhttp;
function showUser()
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="yourpage.php";
url=url+"?q="+str;
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("yourdiv_id").innerHTML=xmlhttp.responseText;
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
I'd suggest you look at this code.
You will see how to handle perfectly XHR objects, and it also gives you some sugar syntax.
Btw, a less-than-one-hundred-lines "library" should be fine, since it basically does what you want it to, and no more.
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.
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!";
}