I have some JQuery code that logs a user into the system by connecting to my api, which is on a subdomain - api.foo.com
My JQuery code is:
$.ajax({
type: "POST",
crossDomain: true,
url: "http://api.foo.com",
data: {json:"true",com:"login",username:$('#LoginUsername').val(),password:$('#LoginPassword').val()},
dataType: "json",
success: function(Data) {
console.log("Request sent and data received");
console.log(Data);
}
});
The issue is that in the console, I get the error XMLHttpRequest cannot load http://api.foo.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://foo.com' is therefore not allowed access.
I know for a fact that I have set the 'Access-Control-Allow-Origin' header to * in my php code - header("Access-Control-Allow-Origin: *"); and I have checked in on google chrome (See screenshot below).
I originally opened a question about this issue but realised I had misspelled the header, whereas this time that is not the case.
The screenshot below is of the headers I receive when I connect to api.foo.com directly.
Related
On my local machine all Ajax requests work just fine and the app works perfectly. It is a different story on the host machine. When trying to execute below Ajax script I get :
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at https://googleads.g.doubleclick.net/pagead/id.
(Reason: CORS request did not succeed).
I spent all day trying to fix this error to no avail. I even added this in the head of every page
<?php ob_start();
header('Content-Type: text/html; charset=utf-8');
header("Access-Control-Allow-Origin: *");
?>
I read about JSONP and I'm wondering how to implement this solution?
This is the short version of the Ajax
$( ".submit-signup-form" ).click(function(e) {
e.preventDefault();
if(formvalues!==''){
$("#sign-up-form-2").submit(
$.ajax({
type: "POST",
url: 'queries/register.php',
data: formvalues,
success: function(customerarr){ //callback}
})
})
});
}
When debugging the app in the console I tried console.log(formvalues) and everything printed out okay. The form does get ALL the variables so I'm not understanding how to make the script work on live host.
You can use this in ajax request...
dataType: 'jsonp', //use jsonp data type in order to perform cross domain ajax
crossDomain: true,
I try to get JSON data from my own API, from a $.ajax method with jQuery.
I must have a header 'Authorization-api-key' in my request otherwise I'll have a 401 status code.
$.ajax({
type: "GET",
headers: {'Authorization-api-key' : 'key'},
dataType: "json",
crossDomain: true,
url: "http://urlofmyonlineapi.com/api/ressource",
success: function (data) {
alert(data);
}
});
I have read several threads on stackoverflow about CORS and the'XMLHttpRequest cannot load' problem. So, in my API I have added in response these headers (I use Slim Framework):
$app->response->headers->set('Access-Control-Allow-Origin', '*');
$app->response->headers->set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
$app->response->headers->set('Access-Control-Allow-Headers', '*');
$app->response->headers->set('Access-Control-Allow-Credentials', 'true');
The problem
If I put any header in $.ajax with 'headers: {...}' argument, I have two errors in my browser console:
'OPTIONS' error
'XMLHttpRequest cannot load' error
If I remove headers, I haven't error but I have my 401 status code.
If I remove headers AND my API's authentification with the key in request's headers, I get my data.
I have solved the problem: my API didn't accept OPTIONS request.
(Ajax with jQuery need to make an OPTIONS pre-request)
In php i do echo json_encode($dump);
If echo it out using php i get {"load":"0.64 0.58 0.52 2\/361 12978\n","procs":"8\n"}
Than i make CORS Request using dataType:jsonp
$(function () {
$.ajax({
type: "POST",
ContentType: 'application/json; charset=utf-8',
url: 'http://labs.isaumya.com/loadtest/load',
dataType: "jsonp",
success: function (response) {
console.log(response.data);
},
error: function (xhr, status, error) {
console.log(error);
}
});
});
I get this error on the console:
DEMO
You are dealing with JSON, not JSONP. dataType: "jsonp", should be dataType: "json",
You can remove the data parameter entirely if your server outputs the correct content-type header for JSON (application/json).
JSONP is a hack to work around the Same Origin Policy from before CORS was designed and implemented by browsers. CORS is the modern approach to making cross origin requests. You use it instead of JSONP.
Both CORS and JSONP are technologies that must be supported by the server. http://labs.isaumya.com/loadtest/load doesn't appear to support either. You will have to modify the server if you want it to supply data in JSONP format or grant permission with CORS.
Unrelated to your actual problem:
You have no data parameter so you aren't sending JSON to to the server, remove the ContentType parameter. Since you aren't POSTing any data, you should probably be making a GET request, not a POST request.
I'm trying to use php headers to accept cookies and various types of ajax requests to my api. Also the request can come from any server, so I can't whitelist them. I'd like to use
header("Access-Control-Allow-Origin: *");
but this blocks cookies. Is there a way around this?
Here's the setup for the ajax calls with jquery:
$.ajax({
type: 'POST',
data: $('#loginForm').serialize(),
crossDomain:true,
dataType: 'json',
beforeSend: function(xhr){
xhr.withCredentials = true;
},
url: "https://myothersite.com/login_submit.php"...
You can't set or read cookies on cross origin resource sharing requests through JavaScript. Cookies respect the browser's same origin policy.
I'm trying to get the SalesForce Rest API to work and I've debugged my problem down to this point:
When I make an AJAX call from my web app to my back-end (which is on a different domain than the backend), all of the AJAX headers end up crammed into $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'] and there is no way for me to get access to their values.
return $j.ajax({
type: 'POST',
url: my_endpoint_url,
cache: false,
processData: false,
data: 'grant_type=refresh_token&client_id=' + this.clientId + '&refresh_token=' + this.refreshToken,
success: callback ,
error: error ,
dataType: "json",
beforeSend: function(xhr) {
if (that.proxyUrl !== null) {
xhr.setRequestHeader('SalesforceProxy-Endpoint', url);
}
}
});
On the server side, I only receive:
[HTTP_ACCESS_CONTROL_REQUEST_HEADERS] => accept, salesforceproxy-endpoint, doiwork, origin, content-type
How can I access the value of "salesforceproxy-endpoint" over on the server side? Likewise, I can't seem to find the "data" of the ajax call anywhere..
UPDATE: Just for giggles I moved my end-point to the same domain. Now it is working as expected.
[HTTP_SALESFORCEPROXY_ENDPOINT] => https://login.salesforce.com//services/oauth2/token
Is there any way to get this working cross domain?
You just got aware what the Same origin policy is ;)