Catch cross domain response in pure javascript ajax [duplicate] - javascript

This question already has answers here:
How to make a JSONP request from Javascript without JQuery?
(12 answers)
Closed 8 years ago.
I want to catch cross domain response in pure javascript ajax not using jquery or other external libraries.
var xmlhttp, response;
try {
xmlhttp = new XMLHttpRequest();
} catch(e) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e2) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4) {
if(callback != undefined) {
console.log(xmlhttp.responseText);
}
}
}
url = "http://xxxx.com/layer.php?callback=callRes";
xmlhttp.open("GET", url, false);
xmlhttp.setRequestHeader("Content-Type",
"application/json,application/javascript,text/javascript");
xmlhttp.send();
spent lots of time and googling but not find any solution
suggestions are most welcome but not script method only pure javascript ajax

I assume you want to see the response in console.
Before calling console.log() you are checking to see if callback exists. In the given piece of code callback is not yet defined so maybe this is the only barrier preventing the output of xmlhttp.responseText.
Solution: remove if (callback != undefined) and just call console.log(xmlhttp.responseText)

Related

Response.Redirect and javascript ajax call

I am using javascript to make call to server. The javascript code is following,
function cs() {
alert("");
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) {
//document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "lp.aspx?pb=true", true);
xmlhttp.send();
}
And my server code is following
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["pb"] != null)
{
Response.Redirect("main.aspx");
}
}
The problem is my Response.Redirect is not working with my ajax call. Why is that?
You can not redirect on ajax call, because, it expects some return value from the invoked page. And if that page itself redirects, it has no way to tell calling function to redirect, as it simply expects some return value in success callback.
So to solve this, you can return a param lets say { redirect: true } if condition satisfied. And on success callback , if redirect is true, then redirect using JS - window.location.href="required".
I believe that redirect doesn't work because the Response for the page with the javascript is closed before the AJAX call is even made.
Instead of using Response.Redirect you could send back a string containing the url and in your script use location.href to redirect.
Simple you can not use response on ur ajax call. use
window.location

Fill div with a php script via Ajax call?

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.

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

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