I have a server running a service, I want to run at some interval a ping request to the service so I can know when it's ready or not.
Got the following ping.dat file:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:dvt="[private]">
<soapenv:Header />
<soapenv:Body>
<dvt:Ping/>
</soapenv:Body>
</soapenv:Envelope>
And the following Javascript functions (which will be included into the setInterval() function):
function doAjax() {
//load request document
$.ajax({
cache: false,
crossDomain: true,
async: true,
dataType: 'xml',
type: 'POST',
data: null,
url: "./ping.dat",
error: function(xhr, sta, err){ alert(err); },
success: function(ret, sta, xhr){
//ping service
$.ajax({
cache: false,
crossDomain: true,
async: false,
processData: false,
contentType: "text/xml; charset=\"UTF-8\"",
dataType: 'xml',
data: processXML(xhr.responseText),
type: 'POST',
url: "[private]",
error: function(xhr, sta, err){
alert(err);
},
success: function(ret, sta, xhr){
$('#response').text($.trim(ret));
},
complete: function(xhr, sta){
alert('complete');
},
});
}
});
}
function processXML(text){
var ret = null;
if ((typeof(ret) !== 'undefined')&&(text !== null)&&(text.length !== 0))
ret = $.trim(text.replace(/[\n\t]+/g, ''));
return ret;
}
When I use SoapUI to call the service and load the ping request, it works.
When I use the JS functions, browser reports:
OPTIONS [private] 200 (OK) jquery-1.10.2.js:8706
XMLHttpRequest cannot load [private]. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
What's causing this?
The message is clear: No 'Access-Control-Allow-Origin' header is present on the requested resource.
If you are indeed doing a cross domain Ajax request, then the server must respond with the appropriate HTTP headers. Browser issues an OPTIONS HTTP request and checks to see if the server "approves" access by looking at the received headers. If the headers are missing then the browser is obligated to return an error and disallow the request to the resource.
See here for details: HTTP access control (CORS)
SoapUI is not affected by the same origin security policy like a browser is, so that's why pinging the web service from SoapUI works.
Related
But the same error into browser
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://abc-test123.com/login. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘(null)’).
My Browser supports Cors
I have an extenstion of Cors for Chrome and CorsE ad-ons for Firefox
All API's working perfectly from same domain into my localhost server but one of our project API's are not working anymore
We are working on Slim Framework here is PHP file Code
$corsOptions = array(
"origin" => "*",
"exposeHeaders" => array("X-My-Custom-Header", "X-Another-Custom-Header"),
"maxAge" => 1728000,
"allowCredentials" => True,
"allowMethods" => array(" PUT, GET, POST, DELETE, OPTIONS"),
"allowHeaders" => array("X-PINGOTHER")
);
$cors = new \CorsSlim\CorsSlim($corsOptions);
$app->add($cors);
I am calling ajax function(which was working before)
var dataString = {
username: "test",
password: "test123"
}
$.ajax({
method: "POST",
url: varURI, //My url variable
data: dataString,
crossDomain: true,
success: function(data)
{
if(data.status == "success")
{
alert("Success");
}
else
{
alert("Failure");
}
}
});
I have tried below new things after API error
//(1)
$.support.cors = true;
//(2)
$.ajax({
method: "POST",
url: varURI, //My url variable
data: dataString,
dataType: "jsonp",
async: false, //and true too
crossDomain: true,
success: function(data)
{}
});
But the same error...
I have checked many questions and applied everything then after asked question here. So need help or any require info which I am missing here.
Add following code in your .htaccess
<ifModule mod_headers.c>
Header set Access-Control-Allow-Origin: *
</ifModule>
And also look on answer from this link
http://enable-cors.org/server_apache.html
I have built a client application, that uses Ajax to call a WebService on another domain (the server supports CORS).
Sometimes when Ajax makes the preflight call, it gets a http error code 400 or 500 from the server, and a response in the format:
{
"httpStatus": 400,
"statusCode": 400
}
I can see the error in the browsers console, but in my JavaScript code, I just get status 0 and statusText "error". Does anyone know how to retrieve the output from the preflight call in JavaScript?
My Ajax call looks lige this:
$.ajax({
type: method,
xhrFields: { withCredentials: true },
url: url,
cache: false,
data: data || '',
contentType: 'application/json; charset=UTF-8',
dataType: 'json',
beforeSend: function(r) {
r.setRequestHeader('Authorization', 'Bearer ' + oauthtoken);
r.setRequestHeader("X-Client-Version", "0.0.1");
}
}).success(function(response) {
console.log("success - service " + url);
callback(response);
}).fail(function(response, textStatus, errorThrown) {
console.log("fail - service " + url);
callback(response);
});
I hope someone can help me with this.
Every time I try to run the code below, I get the following error:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
This is the client JS code:
function checkIP() {
jQuery.ajax({
async: false,
url: "http://www.acme.ie/test/checkip.php",
type: "get",
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'jsoncallback',
success: function(data) {
alert("success");
},
beforeSend: function(XMLHttpRequest) {},
error: function(XMLHttpRequest, textStatus, errorThrown) {}
})
}
jQuery.noConflict();
checkIP();
This is the server response code (http://www.acme.ie/test/checkip.php):
header("Content-Type: application/json");
echo "jsonCallback({'1' : '1'})";
I've looked at many examples and I appear to be doing everything correctly.
Do you have any idea what's wrong?
Thanks
Try to add:
headers: {'Access-Control-Allow-Origin': '*'},
I'm trying to do some searching in Twitter using jQuery. Unfortunately, It's returning only:
https://api.twitter.com/1.1/search/tweets.json?q=django 405 (Method Not Allowed)
XMLHttpRequest cannot load https://api.twitter.com/1.1/search/tweets.json?q=django.
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Here's the code:
(function(){
var Twitter = {
init: function(){
this.url = 'https://api.twitter.com/1.1/search/tweets.json?q=django';
this.fetch();
},
fetch: function(){
$.ajax({
url: this.url,
type: 'GET',
dataType: 'json',
success: function(data){ console.log(data); },
error: function(data){ console.log(data); },
beforeSend: this.setHeader
})
},
setHeader: function(xhr){
xhr.setRequestHeader('X-HostCommonName', 'api.twitter.com');
xhr.setRequestHeader('Authorization', 'OAuth my_oauth_data');
xhr.setRequestHeader('Host', 'api.twitter.com');
xhr.setRequestHeader('X-Target-URI', 'https://api.twitter.com');
}
};
Twitter.init();
})();
I've tested the same query with the same headers using REST Console extension for Google Chrome and It worked.
Well, It looks like (here's the info) you can't do OAuth authentication on client side.
So, the only solution here is to code this thing to be invoked on your server.
I am developing my web app and run it on localhost:8080, in my js file, I have an ajax call to get xml data from server:
$.ajax({
url: 'http://COMPANY_DOMAIN.com/company-interface/the-id',
type: 'GET',
async: false,
dataType: 'application/xml',
data: {id: 43},
success: function(data) {
alert(data);
},
error: function(xhr, status, error){
alert('error happens');
}
})
I can access the url http://COMPANY_DOMAIN.com/company-interface/the-id/?id=43 which will show the xml result on browswer, but my above ajax call always go to error function.
I checked in firebug, the 'xml' tab shows "XML Parsing Error: no element found Location: moz-nullprincipal:{9fd0dca8-cf07-4401-b1de-ab04e8aa00bc} Line Number 1, Column 1:" and firebug shows the URL GET is http://COMPANY_DOMAIN.com/company-interface/the-id/?id=43& =1302610001570.
Why firebug GET shows the "...& =1302610001570"? what does it means? why my ajax call is failed, though I can access that URL?
----------------EDIT---------------
Hi, I changed to use localhost request like:
$.ajax({
url: 'http://localhost:8080/company-interface/the-id',
type: 'GET',
async: false,
dataType: 'xml',
data: {id: 43},
success: function(data) {
alert(data);
},
error: function(xhr, status, error){
alert('error happens');
}
})
But I got the same error... more suggestions please... thank you.
This is possibly due to cross domain access control. You are accessing the site which is on your machine which tries to connect to another website. This is not allowed unless you define Access-Control-Allow-Origin headers.
Also as #Craig said, content type as xml is needs to be changed.
Javascript is subject to the same origin policy. Your script running on localhost can't access COMPANY_DOMAIN.com.
Try Below code :
$.ajax({
url: 'http://localhost:8080/company-interface/the-id',
type: 'GET',
async: false,
dataType: 'text',
data: {id: 43},
success: function(data) {
// Assume response like..
// <note>
// <from>Jani</from>
// <to>Tove</to>
// <message>Remember me this weekend</message>
// </note>
xmlDoc = $.parseXML( data ),
$xml = $( xmlDoc ),
$message = $xml.find("message")
alert($message.text());
$("#xmlResonse").html($message.text());
},
error: function(xhr, status, error){
alert('error happens');
}
})
1302610001570 is for measuring response,
did you checked if the response create valid xml?
change your datatype to application/xml or text/xml
As the other comment suggests, is your URL on another domain? If not then try using relative URL's instead.