XDomainRequest Errors, but developer tools shows response body - ajax

I am using XDomainRequest to send a cross domain request. The onerror handler is firing; however, nothing is logged and when tracing network in developer tools I can see the response in the response body.
Anyone have any ideas? Below is the code I am using. Thanks in advance for any help.
var createCORSRequest = function(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Most browsers.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// IE8 & IE9
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
};
var url = 'https://myurl';
var method = 'GET';
var xhr = createCORSRequest(method, url);
xhr.onload = function() {
// Success code goes here.
//alert("load");
alert(xhr.responseText);
};
xhr.onprogress = function(){
alert("Progress");
}
xhr.onerror = function() {
alert("error");
};
xhr.send();

XDomainRequest object does not provide anyway to determine what is the status code of error, and returns empty string in xdr.responseText.

Related

Async XMLHttpRequest not returning response when followed by code to redirect to another URL in Firefox and Safari

I am facing problem with my code in FireFox and Safari as below:
xhr = new window['XMLHttpRequest'];
xhr.onreadystatechange = function() {
if (done || xhr.readyState != 4) {
return;
}
done = true;
handleResponse(xhr.responseText, callback);
};
}
xhr.open('GET', uri+params, true);
xhr.withCredentials = true;
xhr.send(null);
function handleResponse(responseText, callback) {
var error;
var result;
try {
result = toucan.JSON.parse(responseText)['result']; //connectedAuth
logout result.
} catch (ex) {
result = undefined;
}
console.log("Result is" + result);
if (!result) {
var errorCode = 'UnknownError';
var errorMessage = 'An unknown error ocurred';
error = toucan.Base.format('%s: %s', errorCode, errorMessage);
}
invokeCallback(error, callback);
}
This is followed by redirection as :window.location.href = "index.php?module=login&method=logout";
However, I am not getting any response back from the request I made if it is followed by redirection in FireFox.
This works fine in Chrome but not in Firefox and is specific to the case when request is followed by redirection.
I do not have control on redirection code to be changed. Is there a way that the browser can be enforced to first complete the request and get the response before going for redirection while keeping the call asynchronous.
I would suggest you to use a promise, first create a function that run the ajax call that return the response from your server:
ajax_AuthUser(id,pass){
return $.ajax({
method: "POST",
url: "authUser.php",
data: { id: id, pass: pass}
})
}
Second use a done statement:
ajax_AuthUser(id,pass)
.done(function(response){
//check the response here !! maybe validate the json ?
var auth = JSON.parse(response)
if(auth.response == "approved"){
//do something here
}else{
//do other stuff here
}
}).fail(function(response){
//do something if fail
}).always(function(){
//do something after the call finished
})
If you want a live example here is a jsfiddle that show how promises work
Hope it helps

IE9 CORS XDomainRequest Access Denied

I'm keep getting 'Access Denied' when doing XDomainRequest in IE9.
I Have tried lots of different solutions, nothing works so far.
Note: the script is on HTTP while the server it's doing request to is HTTPS
Below is my code:
let xhr = new XMLHttpRequest();
if ('withCredentials' in xhr){
xhr.open('POST', XHR_URL, true);
} else if (typeof XDomainRequest != 'undefined'){
xhr = new XDomainRequest();
xhr.open('POST', XHR_URL);
} else {
xhr = null;
return;
}
xhr.setRequestHeader('Content-type', 'text/plain');
xhr.onreadystatechange = () => {
if(xhr.readyState == 4 && xhr.status == 200) {
// do something
}
}
xhr.onprogress = function () { };
xhr.ontimeout = function () { };
setTimeout(function () {
xhr.send(params);
}, 0);
Need help, Thanks!
If you start on IE9, then your xhr calls new XDomainRequest(a.k.a xdr). But, xdr doesn't have 'setRequestHeader'.

Pass a url as a parameter with the GET methoid in the django-rest framework?

I am going to pass a url as a GET parameter to the restful API, but it can not match the url pattern, therefore 404 returns.
I use the django-rest framework as the server side.
Here is the urls.py
url(r'^method/?P<url>(https?:\/\/(www\.)?[-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9#:%_\+.~#?&//=]*))$',views.Method.as_view()), name='method'),
And the client xhr code is something like this.
var xhr = new XMLHttpRequest();
// url is like https://storage.googleapis.com/xxx/cccc/abc.txt
xhr.open('GET', 'method/' + url, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) {
// do something
}
};
xhr.send();
The regex is ok, but still returns 404 by the server.
Even though I pass the request url something like
xhr.open('GET', 'method?=' + url, true);
It still returns 404 not found.
What is the proper way to do this?
Thank you!
Change your client xhr code like:
var xhr = new XMLHttpRequest();
var url = 'https://storage.googleapis.com/xxx/cccc/abc.txt';
xhr.open('GET', 'method/?url=' + encodeURIComponent(url), true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) {
// do something
}
};
xhr.send();

Can i use and is secure to use AJAX in my Server Node?

i would like to use native ajax to make some calls inside my node.js server.
Is this secure ?? Can i do it without problems ???
Here's and example:
.... NODE
app.post('/postReceptor', function(req, res, next) {
var data1 = req.body['input1'];
var data2 = req.body['input2'];
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
xhr = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (e) {
try {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
catch (e) {}
}
}
xhr.open('GET', encodeURI('HTTP://WWW.WEBSITE.COM'), true);
xhr.send(null);
xhr.onreadystatechange = function() {
if(xhr.readyState === 4) { // done
if(xhr.status === 200) { // complete
res.render('renderPage', {
sendingData: xhr.responseText
});
}
}
};
});
This is to verify an external page some customer data sent by the client !
Thanks !
Doing AJAX calls is a concept that is originated from the client side and you are in the server so you don't have the XMLHttpRequest function available on Node.JS.
So to make a HTTP request from Node.JS, you could use http.request or use another library like request helping you to code without complexities, here is an example using the request library:
var request = require('request');
var URL = 'http://www.google.com';
request(URL, function(error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body);
}
});
Thanks for the answers. I got the answer to the question using the library https://www.npmjs.com/package/xmlhttprequest
Risto Novik, this is a simple example and of course i have to validate the fields!

AJAX doesn't send POST query

$(document).ready(function() {
function ajaxselectrss(rssurlvar) {
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
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('news');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
//var rssurlvar = $(this).attr("title");
var queryString = "rurl=" + rssurlvar;
var urltofile = "rssget.php";
ajaxRequest.open("POST", urltofile, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.setRequestHeader("Content-length", queryString.length);
ajaxRequest.setRequestHeader("Connection", "close");
ajaxRequest.send(queryString);
}
$(".rshownews").click(function() {
window.setInterval(function() {ajaxselectrss($(this).attr("title"))}, 1000);
});
});
The POST query is "undefined" (Firebug).
You should use $.ajax - it will standardise the whole XmlHTTPRequest thing across browsers.
$.ajax({
type: "POST",
url: "rssget.php",
data: queryString,
success: function(data) {
$('#news').html(data);
}
});
(And, BTW, if you setInterval in your click handler, you will start a new periodic call to your ajaxselectrss function every time the button is clicked.)
Also, your context has changed due to the wrapper function. Try changing your click handler like so:
$(".rshownews").click(function() {
var _this = this;
window.setInterval(function() {ajaxselectrss($(_this).attr("title"))}, 1000);
});
Since you seem to use jquery anyway ($(document).ready) you could use it's wrapper for simplifying ajax-requests.
http://api.jquery.com/jQuery.post

Resources