makerequest ajax,How to make JQuery-AJAX request synchronous

How do i make an ajax request synchronous?

I have a form which needs to be submitted. But it needs to be submitted only when the user enters the correct password.

Here is the form code:

And the jquery code for sending and checking password is this:

var ajaxSubmit = function(formE1) {

var password = $.trim($('#employee_password').val());

$.ajax({

type: "POST",

async: "false",

url: "checkpass.php",

data: "password="+password,

success: function(html) {

var arr=$.parseJSON(html);

if(arr == "Successful") {

return true;

} else {

return false;

}

}

});

}

However the form always submits, regardless of the value returned by the ajax request. I have checked everything else. The value of arr is coming out to be 'successful' when correct password is entered and works correctly vice versa too.

How do i make this request synchronous? as far as i can debug, the request is asynchronous so the form gets submitted before the request gets completed.

Code for checkpass.php

require("includes/apptop.php");

require("classes/class_employee.php");

require("classes/class_employee_attendance.php");

$employee_password=$_POST['password'];

$m=new employee();

$m->setbyid_employee(1);

$arr=$m->editdisplay_employee();

if($arr['employee_password'] == $employee_password)

{

$res="Successful";

}

else

{

$res="Password not match";

}

echo $res;

?>

Update: The solution has been found.

As pointed by Olaf Dietshche: The return value of ajaxSubmit is not the return value of the success: function(){...}. ajaxSubmit returns no value at all, which is equivalent to undefined, which in turn evaluates to true.

And that is the reason, why the form is always submitted and is independent of sending the request synchronous or not.

So, I set a variable to 1 inside success function upon successful. And checked its value out of success function, if it was 1 outside the success function, then I wrote return true ... else return false. And that worked.

Updated working code:

var ajaxsubmit=function(forme1) {

var password = $.trim($('#employee_password').val());

var test="0";

$.ajax({

type: "POST",

url: "checkpass.php",

async: false,

data: "password="+password,

success: function(html) {

if(html == "Successful") {

test="1";

} else {

alert("Password incorrect. Please enter correct password.");

test="0";

}

}

});

if(test=="1") {

return true;

} else if(test=="0") {

return false;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值