I'm having some problems with jQuery AJAX. I have a form that is validated with this Js controller, and I want it to validate with PHP via AJAX, and perform an action based on the response. Here is my Js code.
$(document).ready(function(){
$('form.loginSubmit').on('submit',function(event){
var that = $(this),
url=that.attr('action'),
type=that.attr('method'),
data={};
//data.text_login_username=that.val()
that.find('[name]').each(function(index,value){
var that=$(this),
name=that.attr('name');
value=that.val();
data[name]=value;
});
$.ajax({
url: url,
type: type,
data: data,
contenType:'application/json; charset=utf-8',
dataType:'json',
success: function(response){
console.log(response);
if(response.allClear==1){
window.location = "http://localhost/ServerObserver/dashboard.html";
}
else if(response.allClear==0){
console.log("[loc.W]: Wrong username or password.");
}
else{
console.log("[loc.E]: Something went terribly wrong.");
}
}
});
return 0;
});
});
The problem is that my browser redirects to the PHP file, and not the window.location
specified in the script. Here is the PHP file for reference:
<?php
include 'dbcon.php';
if(isset($_POST['text_login_username'],$_POST['text_login_password']))
{
header('Content-Type: application/json');
$loginResult=array();
$dbcon=getConnection();
$userName=mysqli_real_escape_string($dbcon, $_POST['text_login_username']);
$password=mysqli_real_escape_string($dbcon, $_POST['text_login_password']);
$loginQuery="SELECT * FROM userData WHERE userName='$userName' AND userPassword='$password'";
$queryResult=mysqli_query($dbcon, $loginQuery);
$legalRows=$queryResult->num_rows;
if($legalRows==1)
{
setcookie("currentUser", $userName);
$loginResult['allClear']=1;
}
else
{
$loginResult['allClear']=0;
}
echo json_encode($loginResult);
}
?>
I simply see this checkLogin.php
when I submit the form. I'm completely confused, as this was working perfectly a couple days ago! Here is the version of jQuery I'm using.
Thanks!
~Carpetfizz
Looks like you might just need to do an event.preventDefault();
at the start to stop it from going to the php file when you submit the form.
Docs:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.