1
Hello, I developed an API using the Slim Framework and testing one of the endpoints that with Postman works perfectly but when I request with AJAX, although it is sending exactly the same data that I send with Postman it seems that the data does not arrive correctly and I do not know why it happens.
Request no Postman:
AJAX function:
function ajaxRequest(verb, endpoint, headers = null, body = null) {
try {
//Animação do loading
$('.container').waitMe({
effect: 'facebook'
});
var resp = null;
$.ajax({
url: 'http://localhost/projetos/soccerama/api/' + endpoint,
type: verb,
ContentType: 'application/json',
async: false,
headers: {
'xAuthChaveApi': localStorage.xAuthChaveApi,
'xAuthCambistaID': localStorage.xAuthCambistaID,
'xAuthCambistaToken': localStorage.xAuthCambistaToken
},
success: function(response) {
resp = response
},
error: function(error) {
notificar(Status.SERVER_ERR);
},
beforeSend: function(xhr) {
if(headers !== null) {
for(var key in headers) {
xhr.setRequestHeader(key, headers[key]);
}
}
}
});
} catch (error) {
notificar(error);
} finally {
$('.container').waitMe('hide');
return resp;
}
}
Calling the ajax function in the authentication function:
function autenticar() {
var usuario = $('#inputUsuario').val();
var senha = $('#inputSenha').val();
var pin = $('#inputPin').val();
if(!usuario || !senha || !pin) {
notificar('Ops! Tem algo errado, tem certeza que digitou o seu usuário, senha e PIN corretamente?');
return null;
}
//Declarando os headers
var headers = {
usuario: usuario,
senha: senha,
}
var cambista = ajaxRequest(Verb.GET, Endpoint.AUTH_CAMBISTA, headers);
}
Request data collected from browser:
Request URL:http://localhost/projetos/soccerama/api/cambista/autenticar
Request Method:GET
Status Code:200 OK
Remote Address:[::1]:80
Referrer Policy:no-referrer-when-downgrade
Response Headers
view source
Connection:Keep-Alive
Content-Length:315
Content-Type:application/json;charset=utf-8
Date:Fri, 03 Nov 2017 16:04:59 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.4.28 (Unix) OpenSSL/1.0.2l PHP/7.1.10 mod_perl/2.0.8-dev Perl/v5.16.3
X-Powered-By:PHP/7.1.10
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7
Connection:keep-alive
Host:localhost
Referer:http://localhost/projetos/soccerama/mobile/www/login.html
senha:teste
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36
usuario:admin
X-Requested-With:XMLHttpRequest
xAuthChaveApi:3851b1ae73ca0ca6e3c24a0256a80ace
Browser response:
{
"meta":{
"status":"warning",
"message":"Um erro ocorreu ao executar a opera\u00e7\u00e3o. Tente
novamente ou entre em contato com o administrador."
}
}
Notice: Undefined variable: cambista in /opt/lampp/htdocs/projetos/soccerama/api/app/controllers/CambistaController.php on line 168
API method:
public static function autenticar(Request $request, Response $response) {
try {
$credenciais = array(
'login' => (array_key_exists(0, $request->getHeader('login')) ? $request->getHeader('login')[0] : null),
'senha' => (array_key_exists(0, $request->getHeader('senha')) ? md5(SALT . $request->getHeader('senha')[0]) : null)
);
if ( isset($credenciais['login']) && isset($credenciais['senha']) ) {
$cambista = Cambista::where($credenciais)
->get()
->first();
if (isset($cambista)) {
$cambista->sessao = new Sessao();
$cambista->sessao->idCambista = $cambista->id;
$cambista->sessao->token = md5(uniqid(rand(), true));
$cambista->sessao->save();
$cambista = cambista::where('id', $cambista->id)
->with('telefones')
->with('regional')
->with([
'sessao' => function($query) {
$query->orderBy('criado', 'DESC')->take(1);
}
])
->get()
->first();
$meta = Helper::metaArray(Enum::SUCS_STS, Enum::AUTHORIZED);
} else {
$meta = Helper::metaArray(Enum::WARN_STS, Enum::LOGIN_ERROR);
}
} else {
$meta = Helper::metaArray(Enum::WARN_STS, Enum::INTERNAL_ERROR);
}
return $response->withCustomJson($meta, $cambista);
} catch (Exception $ex) {
$meta = Helper::metaArray(Enum::ERR_STS, Helper::exceptionError($ex), 400);
return $response->withCustomJson($meta);
}
}
Oops, I just forgot to add the API method. It seems to me that what happens is that the variables $credentials['login'] and $credentials['password'] do not pass the verification method 'isset()' and the code falls into 'Else' but this only happens if the request is Ajax because Postman works smoothly.
– Guilherme Ramalho
In your ajax you don’t send any value... have some header business
xAuthCambistaID
but there’s nothing tologin
orsenha
– rray
Actually I send in the function call an array with the headers.
– Guilherme Ramalho
If you give a
console.log(headers)
has been riding right?– rray
I can see that is being sent pq in the request debug in the browser the login headers, password and xAuthChaveApi are there and these are exactly the headers that I am going through in Postman.
– Guilherme Ramalho
There seems to be a mistake here
$cambista = cambista::where('id', $cambista->id)
. Should beCambista::where(...);
. And one question: the message"message":"Um erro ocorreu ao executar a opera\u00e7\u00e3o. Tente 
 novamente ou entre em contato com o administrador."
indicates that he entered some Else, catch, or reached the end of Try? I think the Return at the end oftry{}
should be moved somewhere where there would surely be the variable$cambista
(doesn’t mean it’s the cause of the problem).– Juven_v