Opera + XMLHttpRequest - javascript

I`m from Russia, so sorry for my bad English.
I want to load the main page of my site by js, and i use this script:
<script type="text/javascript">
function httpGet(theUrl) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send(null);
return xmlHttp.responseText;
}
alert(httpGet('http://site.ru'));
</script>
Script located at site.ru/page123.
It works in Firefox and really alert my main page, but if i run it in Opera, nothing happens. Please, fix my code, i can`t see any error in it. Thanks in advance.

XHR is usually asynchronous (switching it to synchronous mode is not recommended for reasons like freezing the browser). You better use a callback.
Since dealing with XHR manually is annoying, I'd suggest you to use jQuery. Using jQuery your code would look like this (that's just the easiest/most simple way to do it):
$.get('http://site.ru', function(resp) {
alert(resp);
});

Related

javascript get html file from online link

i want to call a html online link using xmlhttprequest with javascript, here is my code
but when the code arrive to xmlhttp.open it stopped and does not continue the execution
function loadXMLDoc(size,downloadfromurl) {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var temp = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "http://app.arsel.qa/mobileappspeedtest/samples/256.htm?n=" + Math.random(), false);
xmlhttp.send(null);
}
What you are doing is an actual AJAX request to that page.
Cross domain AJAX requests are not allowed by default for security reasons.
However, there are several ways of performing cross domain requests, and you could take a look at how jQuery does it, so you don't have to reinvent the wheel all over again using plain JavaScript. This article should be helpful.
Anyway, if you actually want to crawl that page, there are tons of open source libraries for server side scripting languages like Java, PHP, Node.js, etc that are very useful in gathering the content, parsing the HTML and so on, depending on your needs.
You can use JSONP for overcoming cross domain barrier.
$.ajax({
type:'GET',
dataType:'jsonp',
jsonp: "jsonp",
url:"http://yoururl.com?callback=callbackFunction"
});
function callbackFunction(data){
//you can process the data here
console.log(date)
}

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.

Javascript security stopping me?

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.

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.

Categories

Resources