1
first I wanted to say that I have been researching for this here in the forum and I found some similar questions, but no answer worked here.
Next, I have a php file on the server that connects to the database, makes a query and returns in json format the data I need:
<?php
header('Access-Control-Allow-Origin:','*');
header('Content-Type:application/json;charset=UTF-8');
error_reporting(E_ALL & ~ E_NOTICE);// para nao mostrar undefined variable
require("config.php");
$usuario = $_POST['usuario'];
$senha = $_POST['senha'];
$sql = $pdo->prepare("SELECT * FROM login WHERE usuario = :usuario AND senha = :senha");
$sql->bindValue(":usuario",$usuario,PDO::PARAM_STR);
$sql->bindValue(":senha",$senha,PDO::PARAM_STR);
$sql->execute();
$ln = $sql->fetchAll();
$n = $sql->rowCount();
if ($sql) {
if ($n>0){
//$retorno['status'] = "s";
$retorno['dados'] = $ln;
echo $_GET['callback'] . '('.json_encode($retorno).')';
//echo json_encode($retorno);
}else{
//$retorno['status'] = "n";
echo $_GET['callback'] . '('.json_encode($retorno).')';
//echo (json_encode($retorno));
}
}
However, when I receive it using ajax (from an external source), only the 'status' comes, and the 'return' comes as 'Undefined', and so I cannot get the correct result to do the operation.
Follow the javascript:
$(function () {
function onAppReady() {
if (navigator.splashscreen && navigator.splashscreen.hide) { // Cordova API detected
navigator.splashscreen.hide();
}
}
$('form[name=form-login]').submit( function(){
$.ajax({
type: 'POST',
crossDomain:true,
url: 'http://www.minhaurl.com.br/api/meuphp.php?callback=?',
dataType:'jsonp',
contentType : "application/json",
data: $(this).serialize() // pega os dados do form
}).done(function(data){
console.log(data);
if (data.status == "s"){
//faz a ação desejada
}
else if (data.status == "n"){
// sempre vem status:n, pois não vem dados para fazer a operação
alert('Credenciais Inválidas');
}
else {
alert('...');
}
})
.fail(function(data, textStatus, errorThrown){
alert('falhou');
console.log(data);
});
return false;
});
I mean, I can’t communicate with the server through an external source. Any help? Thanks.
Hi, I did this what you said, but continue with the mistake.
– Léo
I know, I’m correcting the answer...
– Hiago Souza
Hiago only has an error that has not noticed
header('Access-Control-Allow-Origin:','*');
, the correct isheader('Access-Control-Allow-Origin: *');
updates ae :)– Guilherme Nascimento
opa, true... but the problem is not of CORS is about an expected result incorrectly. It expects a JSON and returns a script
– Hiago Souza
But still I updated thank you.
– Hiago Souza