Javascript security stopping me? - javascript

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.

Related

Ajax working only in IE

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.

Do I have to keep checking if the XMLHttpRequest object exists?

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

XMLHTTPrequest request not working

I tried the following code to send request to jsp page on a click of button. I checked on Httpfox but no request is going. I just used the whole of this code in the body of the html code. Am I doing some silly mistake. Kindly suggest..
<button type="button" onClick="handleButtonClick();">Click Me!</button>
<script type="text/javascript">
function handleButtonClick()
{
// Declare the variables we'll be using
var xmlHttp, handleRequestStateChange;
// Define the function to be called when our AJAX request's state changes:
handleRequestStateChange = function()
{
// Check to see if this state change was "request complete", and
// there was no server error (404 Not Found, 500 Server Error, etc)
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var substring=xmlHttp.responseText;
// Do something with the text here
alert(substring);
}
}
xmlhttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://csce:8080/test/index.jsp?id=c6c684d9cc99476a7e7e853d77540ceb", true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
}
</script>
Well, in JavaScript, variables are case-sensitive. You have xmlHttp and xmlhttp; those should be the same.
You've also got <pre><code> at the beginning of your <script> block, which is a JavaScript syntax error.
Since no request is being made, I am not convinced you can actually make requests to "http://csce:8080" as FireFox may not see that URL as being on the same subdomain (You cannot make Ajax requests for resources not on the same domain as the requestor).
Suppose you made the URL relative. Is a request even generated then? If so, that is likely your problem.
Quote: xmlhttp = new XMLHttpRequest();
Two things. First, you might want to use a more robust method of getting an XMLHttpRequest object. Second, javascript is case-sensitive; xmlhttp != xmlHttp
xmlHttp = (function (x,y,i) {
if (x) return new x();
for (i=0; i<y.length; y++) try {
return new ActiveXObject(y[i]);
} catch (e) {}
})(
window.XMLHttpRequest,
['Msxml2.XMLHTTP','Microsoft.XMLHTTP']
);
Quote: http://csce:8080/test/ind...
Keep in mind that cross-domain xmlhttp is verboten. Unless you're serving from csce:8080, that ain't gonna work.

Running Ajax in IE, FF, and Safari

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.

Try/Catch for Javascript in mobile safari?

Can I wrap a try/catch around the opening of a URL in mobile safari? I know the question has been asked a number of different ways but essentially what I'm after is the trapping of bad URLs or the detection of when a specific URL cannot be opened by the browser.
If the URL is within the same domain, then you can use an XMLHttpRequest to determine if it returns a valid response.
e.g
var xhr = new XMLHttpRequest();
function handler(){
if (xhr.readyState != 4) { return; }
if (xhr.status != 200) { return "THIS IS A BAD LINK"}
}
if (xhr != null) {
xhr.open("GET", URL_YOU_ARE_TESTING, true);
xhr.send();
xhr.onreadystatechange = handler;
}
However this won't work for links to other sites (which is what I guess you want) due to the browser's same origin policy. I don't believe there is a javascript solution for this case.

Categories

Resources