Tuesday 18 October 2016

jquery - Ajax call PHP Service cross domain

I'm starting developing an app and I'm having trouble with the login.



I have a form with an Ajax call to a PHP service to validate the user, I uploaded both files to my server and it works perfect. I input user and password, goes to the PHP file and validate the user, so far so good.



The problem is that these two files will be in different servers. Now I have the PHP file hosted on my server, and the form/ajax call localhost and it doesn't work.



Here's the code:




PHP:



header('Content-type: application/json');
$server = "localhost";
$username = "****";
$password = "****";
$database = "*****";


$con = mysql_connect($server, $username, $password) or die ("Error: " . mysql_error());

mysql_select_db($database, $con);

$user = mysql_real_escape_string($_POST["user"]);
$pass = mysql_real_escape_string($_POST["pass"]);

$result = mysql_query("SELECT * FROM Usuarios WHERE IdUsuario = '" . $user . "' AND Clave = '" . $pass . "'");

$numResults = mysql_num_rows($result);


echo $numResults;

mysql_close($con);
?>


JS:



$( document ).ready(function() {


$('form').submit(function(event){
event.preventDefault();

var user = $(this).find("#user").val();
var pass = $(this).find("#pass").val();

$.ajax({
type: 'POST',
crossdomain: true,

data: 'user=' + user + '&pass=' + pass,
url: 'http://www.url.com/login.php',
success: function(data){
if(data == 1){
alert("YES!");
}else{
alert("NO");
}
},
error: function(){

alert('Error');
}
});
return false;
});
});


I have also tried with dataType: "json" and "jsonp"

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...