Again, AJAX is async. So the showMsg function will be called only after success response from the server.. and the form submit event will not wait until AJAX success.
Move the e.preventDefault();
as first line in the click handler.
$("form").submit(function (e) {
e.preventDefault(); // this will prevent from submitting the form.
...
See below code,
I want it to be allowed HasJobInProgress == False
$(document).ready(function () {
$("form").submit(function (e) {
e.preventDefault(); //prevent default form submit
$.ajax({
url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
data: { id: '@Model.ClientId' },
success: function (data) {
showMsg(data);
},
cache: false
});
});
});
$("#cancelButton").click(function () {
window.location = '@Url.Action("list", "default", new { clientId = Model.ClientId })';
});
$("[type=text]").focus(function () {
$(this).select();
});
function showMsg(hasCurrentJob) {
if (hasCurrentJob == "True") {
alert("The current clients has a job in progress. No changes can be saved until current job completes");
return false;
} else {
$("form").unbind('submit').submit();
}
}