Custom headers for ajax and php - php

So, I'm having a problem retrieving custom headers from ajax call.
This is my ajax call:
$.ajax({
url: 'api.php',
type: 'get',
processData: false,
beforeSend: function(xhr) {
xhr.setRequestHeader('HASH', '5c268592cd4db9c7f6b813bb689005c6');
},
success: function(data) {
console.log(data);
},
error: function(xhr, status, error) {
console.log(xhr);
}
});
And in my api.php, I have this:
<?php
$headers = getallheaders();
print_r(json_encode($headers));
the output:
......
"Access-Control-Request-Headers":"content-type,hash",
....
This returns null:
echo $headers['hash'];
// or this echo $headers['HASH'];

You are making a cross-origin request (you shouldn't be, since your code shows a relative URL, but perhaps there is an HTTP redirect in play somewhere) and adding custom headers.
This means that it is not a simple request, but requires a preflight OPTIONS request.
The output you see is the headers of the OPTIONS request asking permission from the server to send the request with the custom headers.
You need to grant that permission, then the browser will make a second request (which is the one you are expecting).
header("Access-Control-Allow-Origin: http://example.com/");
header("Access-Control-Allow-Headers: HASH, Content-Type");
header("Access-Control-Allow-Methods: GET");

Try this $_SERVER["HTTP_HASH"];

Related

jQuery AJAX http GET cross domain - required headers in response

I've made a web application running on domain http://app.mydomain.tld
and I've APIs on https://api.mydomain.tld (APIs are not developed by me).
I'm doing an AJAX HTTPs GET call with jQuery using this method:
$.ajax({
url: "https://api.mydomain.tld/GetSomething/read.php",
method: "GET",
contentType:"application/json; charset=utf-8",
dataType:"json",
async:false,
headers: {"Accept": "application/json; odata=verbose" },
success: function (data) { doSomething(); },
error: function (data) { showError(); }
});
This call is returning an error like NetworkError: failed to execute 'send' on 'XMLHttpRequest': Failed to load 'https://api.mydomain.tld/GetSomething/read.php'.
I've added the Access-Control-Allow-Origin extension for Chrome and the call is working fine.
So I've checked response headers. When Chrome extension is NOT enabled I've this response headers:
Access-Control-Allow-Origin: *
When the extension is enabled I've these headers:
Access-Control-Allow-Headers: access-control-allow-methods,access-control-allow-origin
Access-Control-Allow-Methods: GET, PUT, POST, DELETE, HEAD, OPTIONS
Access-Control-Allow-Origin: *
So my question, that could have an obvious answer, is: are these headers required to make correct cross domain calls?
If yes, do my APIs need the below additional code?
<?php
header("Access-Control-Allow-Origin","*");
header("Access-Control-Allow-Methods","GET, PUT, POST, DELETE, HEAD, OPTIONS");
header("Access-Control-Allow-Headers","access-control-allow-methods,access-control-allow-origin");
?>
Is correct what I said or am I missing something to make my call working without changing APIs code?
PS: if possibile I would not use JSONP.

XMLHttpRequest cannot load . Origin http://localhost:63342 is not allowed by Access-Control-Allow-Origin

$http({
method: "POST",
url: 'http://192.168.3.140:8081/SamplengcordovaApp/Savedata.php',
data: resdata,
dataType: "json"
})
.success(function (data, status, headers, config) {
debugger;
alert(data);
})
.error(function (data, status, headers, config) {
alert(status);
});
getting the success but not saved in database.please provide the supported code for me.
This is basically a Cross-origin resource sharing (CORS) problem.
You are making an ajax request from a page of different domain. which is not allowed.
To allow it you will have to append Access-Control-Allow-Origin in the response header of the server page by adding this on the top of the server page
header('Access-Control-Allow-Origin: *');
Note: the '*' at the end means it will accept any request from any website, for added security you could do this
header('Access-Control-Allow-Origin: http://yourwebsite.com');

jQuery - No Access Control Allow Origin

I'd like to load a site from a different domain. I've already set headers through php in my header.php file:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: *");
I've searched around for the correct way to do the ajax request with cross domain enabled and ended up with this:
$.ajax(
{
type: 'GET',
url: target,
processData: true,
data: {},
dataType: "json",
success: function (data)
{
$("#toolsarea").attr('src', target);
}
});
but I still get the error "No 'Access-Control-Allow-Origin". Is there still something I'm missing?
Your issue is related to Same origin policy which prevent JavaScript to make an AJAX request for security reasons.
You need to make sure CORS is enabled on your PHP server.
You can do it using:
<?php
header("Access-Control-Allow-Origin: *")
More information on how to enable CORS on your server can be found here:
http://enable-cors.org/server_php.html
You can read more about Same-origin policy on the client here:
https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy

XMLHttpRequest cannot load : only with headers in Ajax jQuery

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)

XMLHttpRequest cannot load url. Method DELETE is not allowed by Access-Control-Allow-Methods

I am trying to make an ajax request to my restserver:
<script>
var id = "104";
var postData = {
'id' : id
};
AJS.$.ajax({
url: "myurl",
crossDomain: true,
data: postData,
type: "DELETE",
// dataType: "json",
success: function(msg, textStatus, jqXHR) {
alert( "Data Saved: " + msg);
}
});
</script>
But I am receiving the following error:
XMLHttpRequest cannot load http ://myurl/rest/controller/resource/id/107. Method DELETE is not allowed by Access-Control-Allow-Methods.
I have added the following at the top of my php controller:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
header('Access-Control-Allow-Headers', 'x-requested-with');
The only methods it seems to accept is get and post but delete and put create an error.
Any ideas?
Thanks,
James
I learned the hard way the other day that it's pretty much impossible to perform a cross-domain ajax request from just about any browser. I would handle the redirecting HTTP request on the server-side instead. Have this ajax request go to a script on the same url/server, and have that script perform an HTTP request and wait for the data from the other server you're attempting to get data from.

Categories