javascript - $.ajax submiting a form, sometimes get success and sometimes error -
i have simple log-in form passed php through $.ajax function. problem on localhost $.ajax function result success , error. of time when i'm getting success when i'm using chrome debugger. when checked file on server got error result $.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 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 * users uname '$uname' , upass '$pass'"); $outp = "["; while($rs = $result->fetch_array(mysqli_assoc)) { $outp .= '{"uid":"'.$rs["uid"].'"}'; } $outp .="]"; $conn->close(); echo($outp);
your form still trying submit normal way because aren't intercepting it.
add id form.
<form id="myform" method="post" action="">
change code below , give shot. we're doing intercepting form submit , preventing default action.
$("#myform").submit(function(event){ $.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 problem!"); }, }); event.preventdefault(); });
Comments
Post a Comment