1
Using as example the request below and using as parameter the id
, I got the return as expected
Ajax
let id = 1;
$.ajax({
type: 'GET',
async: false,
contentType: 'application/json',
url : 'controller/get_objeto/' + id,
success: (function (data) {
console.log(data)
}),
....
PHP
// controller
public function get_objeto($id)
{
if ($id== 0)
{
$dados = $this->aviso->get();
}
else
{
$dados = $this->aviso->get_by_id($id);
}
header('Content-Type: application/json');
echo json_encode($dados);
}
Return
{"id":1,"tipo":"1","titulo":"teste","descricao":"teste"}
If I copy the request performed in the browser’s XRH console, I can request it directly in the browser’s URL address bar by changing the parameter id
, just using the full URL.
Example
http://localhost/aplicação/controller/get_objeto/1
I tried to use the same way in another existing application by copying the full URL of the request and pasting it into the browser’s URL address bar and got the following return:
{"error":"unauthorized_request","message":"Unauthorized request: no authentication given","status":401}
My question is: It is possible to do this type of authentication in an AJAX and PHP request, if yes, there is some simple way to do it ?
The code sample editor tool, which uses the grave accent, as the name says, was made for code samples, not to emphasize text or acronyms. If you really think a part of the text needs emphasis, use bold. Regarding the problem, did you check the headers sent from the AJAX request? For the server there will always be an HTTP request, regardless of whether it is from AJAX or not - and it should not even make a difference. Since it was blocked when accessed directly by the URL, it is very likely that the authentication is done from a header that you did not send.
– Woss
@Andersoncarloswoss, I did not send or check the sent headers, this is why I opened the question, to understand how it is done.
– Wagner Fillio
Then it would be interesting to put the requisitions in question in question, otherwise any answer will be based on achism may not represent the real situation.
– Woss
What I have, I’ve asked the question.
– Wagner Fillio
the
contentType: 'application/json',
you use to return in json format, is that it? If it is you can replace todataType: 'json'
and see if it makes the same mistake– adventistaam
Ai in your php you take header...
– adventistaam
@adventistaam, my question is not about returning json or not, this I get. My question is about authenticating the request if you pass the url directly through the address bar..
– Wagner Fillio
Try to remove the header
– adventistaam
@Andersoncarloswoss, this would be a valid http header send and check?
beforeSend: function(xhr){ xhr.setRequestHeader('X-Header'); },
andif(isset($_SERVER['HTTP_X_HEADER'])){ ... }
– Wagner Fillio