TBA
TBA

Reputation: 1187

MVC Ajax Call issue

In an MVC view I have,

a submit button where, I check for all the validation. If the validation is wrong I returns false. So that the form will not post.

However I was checking for a duplicate check using Ajax get method. It will return true if the value exists. Then I will return false for the button submit.

However in my case the ajax call is not returning anything. Or rather the process doesn't wait for the ajax to come back. Is there anyway can I achieve it.

My Code on button click

var isDraftValid = 0;
        if(checkAjax()==false)
        {
            isDraftValid++;
        }
        if(check2()==false)
        {
            isDraftValid++;
        }
        if(isDraftValid>0)
        {
          return false;
        }

CheckAjax Code:

var href = '@Url.Action("IsDuplicate", "Book")' + '/' + bTitleVal;
$.ajax({
    type: "get",
    url: href,
    dataType: "json",
    traditional: true,
    cache: false,
    contentType: 'application/json',
    //data: JSON.stringify({ bookTitle: bTitleVal }),
    data: {},
    success: function (returndata) {
        debugger;
        if (returndata == true) {
            return true;
        }
        else {
            return false;
        }
    },
    error: function (arg, data, value) {
    }
});

Upvotes: 0

Views: 450

Answers (4)

Yobac
Yobac

Reputation: 43

Maybe you could use a different call sequence like this :

dataOk = true;
if(!check2())
{
    dataOk = false;
}
if(dataOk))
{
    dataOk = checkAjax();
}
return dataOk;

Or maybe I did not understand your request ?

Regards

Upvotes: 0

user2587132
user2587132

Reputation:

on alerting only the 'returndata' you able to see "true" or "false"? ,try quoting them in your condition and give e.preventDefault a shot instead of return false

Upvotes: 1

Amit
Amit

Reputation: 15387

Try this

var href = '@Url.Action("IsDuplicate", "Book",new{bTitleVal=bTitleVal})' 

Upvotes: 1

karaxuna
karaxuna

Reputation: 26930

You ajax request is asynchronous, so you must do it with callbacks, or (not recommended) add async: false:

$.ajax({
    type: "get",
    url: href,
    async: false

One more detail, declare result variable in CheckAjax method and assign value to it when request completes and then return this variable.

Upvotes: 1

Related Questions