I am using $.ajax() function in my script which is calling web service from other domain. but I am getting error in IE. Then after doing research, I came to know error was coming due to Internet Explorer by default set "Access data sources across domains" to "prompt". How to set it "Enable" using script..?
Code:
var serviceURL = "https://www.other-domain.com/webservice/showbills?billID=12458";
if ($.browser.msie && window.XDomainRequest) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var data = xhr.responseText;
var xmlDoc = $.parseXML(data); // then parse into xml
var xml = $(xmlDoc); // create doc
console.log(xml);
// show bill here in table.
}
}
xhr.open('POST', serviceURL, true);
xhr.send();
} else {
$.ajax({
type: "POST",
url: serviceURL,
dataType: "text",
crossOrigin: true,
crossDomain: true,
success: function (data) {
var xmlDoc = $.parseXML(data); // then parse into xml
var xml = $(xmlDoc);// create doc
console.log(xml);
// show bill here in table.
}
});
}
This giving error in browser.
I am getting SEC7120: Origin http://localhost:8080 not found in Access-Control-Allow-Origin header and SCRIPT7002: XMLHttpRequest: Network Error 0x80070005, Access is denied
Microsoft has created its own solution for cross domain AJAX requests in Internet Explorer, called XDomainRequest.
There is a plugin for jQuery to support this: https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest
You just have to include this script after including jQuery and then it should work.
Related
I tried to use xmlHttpRequest POST to upload file in Meteor project. With Django REST framework 2.3.14.
I used:
var file = $('#control_import_file')[0].files[0];
var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.onreadystatechange = function (e) {
if (e.target.status == 200) {
var resp = JSON.parse(e.target.response);
if (resp.status == 'success') {
alert("success");
} else {
alert("fail");
}
}
};
xmlHttpRequest.onload = function () {};
xmlHttpRequest.open("POST", "http://mydemosite.net/orders/import-coupon/25/", true);
if (window.FormData) {
var formData = new FormData();
formData.append("datafile", file);
xmlHttpRequest.send(formData);
}
In Chrome, it returns:
Event {isTrusted: true, type: "readystatechange", target:
XMLHttpRequest, currentTarget: XMLHttpRequest, eventPhase: 2…}
So I can easyly get Json string: target.response object:
""{"status": "error", "data": {"error_data": ["test123"],
"error_code": 0, "error_msg": "Check failed"}, "error_data":
["test123"], "error_code": 0, "error_msg": "Check failed"}"
JSON.parse(e.target.response); --> get sth I want.
However in Firefox: it returns all that json string above in HTML format:
<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><meta name="robots" content="NONE,NOARCHIVE"...</html>
Anyone can help me how to handle error response in Firefox? Or Is there any way to get response in all browsers?
Thanks a lot!
Django Rest Framwork checks the "Accept" header to define if he must return HTML, JSON, CSV or any other format that he can render (cf: http://www.django-rest-framework.org/api-guide/renderers/)
since you are manually using XMLHttpRequest, try adding the accept header with setRequestHeader. Something like:
xmlHttpRequest.setRequestHeader("Accept","application/json");
check in your console that you are passing the correct headers on Chrome and Firefox
Hope this helps
I have a method WCF, which returns a JSON:
enter image description here
the client has a script that should take the data from the wcf service
Script:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
$(document).ready(function () {
$('#btn').click(function () {
$.ajax({
url: 'http://192.168.200.100/Searching.BE.Service//WCFRESTService.svc/GetCategories',
method: 'get',
contentType: 'application/json;charset=utf-8',
dataType: 'json',
success:function(data)
{
alet(data.Announcing[0].Categories.id);
},
error: function (error)
{
alert(error);
}
})
var request = createCORSRequest("get", "http://192.168.200.100/Searching.BE.Service//WCFRESTService.svc/GetCategories");
request.send();
})
})
</script>
<input id="btn" type="button" />
After click button i have this error: Object object
and i have console message:
SCRIPT7002: XMLHttpRequest: Network error 0x80070005, Access Denied .
SEC7120: Source http: // localhost: 4945 is not found in the header Access-Control-Allow-Origin ..
How to solve these problems?
Well, because your web server is running locally (see the 192.168...) address, I can't test it, but your error messages tell me the following:
The first one indicates that you are trying to access an unavailable resource. Try visiting the url with your browser, and see if that gives a response. Also in, http://192.168.200.100/Searching.BE.Service//WCFRESTService.svc/GetCategories, the double slash might indicate it's the wrong url.
The second error is not complete, but are you maybe serving the web page from a different server than the api? Because a quick google search reveals that it has something to do with a cross-site request.
I am using dojo.request.xhr to make a post reqeust to geoserver.
But the problem is when i'm using XMLHttpRequest to make the post request , it is working fine on the other hand when i'm using dojo.reqeust.xhr for the same thing its giving the following error.
*
org.xmlpull.v1.XmlPullParserException: only whitespace content allowed
before start tag and not i (position: START_DOCUMENT seen i... #1:1)
only whitespace content allowed before start tag and not i (position:
START_DOCUMENT seen i... #1:1)
*
dojo.request.xhr code -
xhr(url, {
handleAs : "xml",
data : postData,
method : "POST",
headers : {
'Content-Type' : 'text/xml',
},
}).then(function(data){
console.log(data);
}, function(err){
console.log("Error : " + err);
});
above code is not working and giving the above mentioned error.
This is same post request using the XMLHttpRequest :-
var req = new XMLHttpRequest();
req.open("POST", url, true);
req.setRequestHeader('Content-type', 'text/xml');
req.onreadystatechange = function () {
if (req.readyState != 4) return;
if (req.status != 200 && req.status != 304) {
alert("Error");
return;
}
var xml = req.responseXML;
console.log(xml);
}
if (req.readyState == 4) return;
req.send(postData);
To check the XML(that i'm sending as postData) whether it is valid or not i used GeoServer's demo request tool to build the WFS request and its working fine.
UPDATE :- This is the link of XML file that i'm sending as a postData.
post_XML_File
Can anyone have any idea what i'm doing wrong?? Thanks in advance.
I'm using some JavaScript to send an Ajax request to an Arduino webserver and change the HTML on a webpage.
In Safari this has been working great, but when I try to load it in Firefox and Google Chrome the document elements never update. In the debugger consoles I can see the requests and responses coming back so I'm guessing that there is an issue with parsing the response to an array?
Here is the code:
function GetSwitchState()
{
nocache = "&nocache=" + Math.random() * 1000000;
var request = new XMLHttpRequest();
request.onreadystatechange = function()
{
if (this.readyState == 4) {
if (this.status == 200) {
if (this.responseText != null) {
var response = this.responseText;
var comma = ",";
var inputArray = response.split(comma);
var green = inputArray[0];
var red = inputArray[1];
var fault = inputArray[2];
var counter = inputArray[3];
document.getElementById('green').innerHTML = green;
document.getElementById("red").innerHTML = red;
document.getElementById("status").innerHTML = fault;
document.getElementById("cars").innerHTML = counter;
}
}
}
}
request.open("GET", "url" + nocache, true);
request.send(null);
setTimeout('GetSwitchState()', 1000);
}
The response from the Arduino webserver is four comma-separated values.
Okay it looks like the issue was actually getting past the
{
if (this.readyState == 4) {
if (this.status == 200) {
arguments. When I changed it to:
{
if(response.readState == 4) {
I was able to move past that statement in firefox. To get the status to 200 instead of 0 I needed to modify the response header on the arduino side to include:
Access-Control-Allow-Origin: *
To allow Cross Origin Domain Requests in FireFox. Once I made these changes the code works great, I guess I was barking up the wrong tree with my array assumption.
Thanks for the help!
What I did today was pretty much the same!
When I ran an Ajax request to a PHP file and wanted to return an array I needed to specify the return-datatype as "json". In my PHP file I then returned my values like this:
return json_encode(array(
'success' => false,
'error' => $_POST['password_hashed']
));
I was acctually using jQuery to run the request. That looks like this:
$.ajax({
type: 'POST',
url: 'script.php',
data: 'password_hashed=' + hex_sha512(str_password) + '&email=' + str_email, //Clientside password hashing
cache: false,
dataType: 'json',
success: function(value){
//Ajax successfully ran
alert(value.success + '_' + value.error); //=false_[hash]
},
error: function(){
//Ajax error occured -> Display error message in specified element
alert('error with request');
}
});
I just started with Ajax two days ago, and this may not help a lot, but it is worth trying.
I'm submitting an Ajax request from an https page to an https page. In all other browsers, this goes through instantly, but in Chrome it hangs for a long time (usually about 40 seconds).
What could be causing this? how do I fix it?
EXAMPLE JQUERY CODE THAT ALSO CAUSES THE HANG
<html>
<head>
<script type="text/javascript" src="jquery-1-9-1.js"></script>
</head>
<body>
<br/>
<a onclick="doit()">go</a>
<script>
function doit()
{
var myData = { "key": "value" };
$.ajax({
url: "myhandlepage.php",
data: myData,
dataType: 'json',
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
success: function (data) { alert("OK = " + data.eric); },
error: function (data, status) { alert("FAILED:" + status); }
});
}
</script>
</body>
</html>
EXAMPLE CODE
//Create browser-compliant request object
if( typeof XMLHttpRequest === "undefined" ) XMLHttpRequest = function()
{
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
throw new Error( "This browser does not support XMLHttpRequest." );
};
//Create object
var ajax = new XMLHttpRequest();
//We need to open the object
ajax.open( "post", "/myhandlepage.php", true );
//Now set the callback
ajax.onreadystatechange = function()
{
//elided, but doesn't matter, I can see the 40+ second delay in chrome developer tools
}.bind( this );
//Send the request
ajax.send( mycontent );
For clarification: no errors are shown in Chrome's developer tools.
EDIT: It appears that this issue only happens on the first request for a tab/page in Chrome. All ajax requests in that same tab/page seem to go through instantly after the first lagging request.
MORE INFO
Looking in chrome:net-internals/#events on the hanging request only, in the middle of all the requests, I see this:
t=1360622033867 [st= 4] HTTP_STREAM_PARSER_READ_HEADERS [dt=38643]
--> net_error = -100 (ERR_CONNECTION_CLOSED)
Then it sends the entire request again, and that second time it goes through instantly. What could be causing this first failed request? It occurs every time I do the request for the first time to that URL since opening the browser.