First of all I wanted to say that I was researching for it 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 the json 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, at the time I receive it using ajax (from an external source), only 'status' comes in, and 'return' comes as 'undefined', so I can not 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;
});
That is, I can not communicate with the server through an external source. Some help? Thank you.