mardi 14 avril 2015

$.ajax submiting a form, sometimes get success and sometimes error

I have a simple log-in form that passed to the php through $.ajax function. The problem is that on localhost the $.ajax function result is sometimes success and sometimes error. most of the time when i'm getting success is when i'm using chrome debugger. When I checked the file on a server i only got error result by the $.ajax.


Thanks in advance..


form code:



<form method="post" action="">
<h3>Login</h3>
<label>User Name:<input type="text" name="uname" id="uname"></label>
<br>
<label>Password:<input type="password" name="pass" id="pass"></label>
<br>
<button type="submit" id="submit">login</button>
</form>


$.ajax code



$("#submit").click(function(){
$.ajax({
cache: false,
url: 'php/login.php',
type: 'POST',
dataType: 'json',
data: {
uname: $('#uname').val(),
pass: $('#pass').val()
},

success: function (data) {
Cookies.set('uid', data[0].uid);
alert("test");
},
error: function (xhr, status) {
alert("Sorry, there was a problem!");
},
});
})


php code



header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

require_once 'config.php';
$conn = mysqli_connect($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error);

$uname=mysql_real_escape_string($_POST['uname']);
$pass=md5(mysql_real_escape_string($_POST['pass']));

$result = $conn->query("SELECT * FROM users WHERE uname LIKE '$uname' AND upass LIKE '$pass'");

$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
$outp .= '{"uid":"'.$rs["uid"].'"}';
}
$outp .="]";

$conn->close();
echo($outp);

Aucun commentaire:

Enregistrer un commentaire