Reputation: 19
I'm using validation thing on button click event with jQuery Ajax. This method shows an alert message if return value is 1, else return true and go to button method. That validation and alert showing thing and block button method is working fine. If not want to do anything and return true to hit the button method is not working.
This is my jQuery ajax method.
$(function () {
$('#customerSubmit').on('click', function (event) {
debugger;
event.preventDefault();
var title = $('#Title').val();
var firstName = $('#FirstName').val();
var phoneNo1 = $('#PhoneNo1').val();
var Email = $('#Email').val();
var address1 = $('#AddressLine1').val();
$.ajax({
type: 'POST',
url: '/Customer/IsExistCustomer',
data: { FirstName: firstName, Title: title, PhoneNo1: phoneNo1, AddressLine1: address1, Email: Email },
success: function (data) {
if (data == 1) {
alert('This Customer Already Exist');
return false;
}
else {
return true;
}
}
});
});
});
Please help me to sort out this,
Thanks.
Upvotes: 0
Views: 49
Reputation: 32831
A few issues in your code:
IMHO, You should intercept the 'submit' event handler, preventDefault(), and do an ajax call to submit your form, and handle the errors to give some kind of feedback to the user.
If you absolutely want to do two requests to the server instead of one (one to check, and one to submit), you can do a second ajax call in the 'success' handler:
$.ajax({
type: 'POST',
url: '/Customer/IsExistCustomer',
data: { FirstName: firstName, Title: title, PhoneNo1: phoneNo1, AddressLine1: address1, Email: Email },
success: function (data) {
if (data !== 1) {
$.ajax({
type: $(form).attr("method"),
url: $(form).attr("action"),
data: $(form).serialize(),
success: function (data) {
}
});
}
}
});
Upvotes: 0
Reputation: 382434
You can't synchronously return from an asynchronous action.
Here's a good QA on the general problem : How do I return the response from an asynchronous call?
For your specific problem, you should use a button instead of a submit element and do the action (submit the form) in the callback :
$(function () {
$('#customerSubmit').on('click', function (event) {
var form = this.form; // <- depends on your DOM
var title = $('#Title').val();
var firstName = $('#FirstName').val();
var phoneNo1 = $('#PhoneNo1').val();
var Email = $('#Email').val();
var address1 = $('#AddressLine1').val();
$.ajax({
type: 'POST',
url: '/Customer/IsExistCustomer',
data: { FirstName: firstName, Title: title, PhoneNo1: phoneNo1, AddressLine1: address1, Email: Email },
success: function (data) {
if (data == 1) {
alert('This Customer Already Exist');
}
else {
form.submit(); // <- now submit the form
}
}
});
});
});
Upvotes: 1