-1

I'm sending ajax request on my BeginForm's onBegin function and I want to stop next steps when data.success is false.

But returning false, from success method not returning it from onBegin. How to make this asynchronous thing work? I want to stop all the cycle in onBegin function if data.success is false.

function onBegin() {
        $("#spMessage").html("Processing...");
        $.ajax({
            url: '@Url.Action("test")',
            type: "POST"
            success: function (data) {
                if (!data.success) {
                    alert("Sorry!");
                    /*Here I want to return false not from success function, but from OnBegin function*/
                    return false;
                }
            }
        });
    }
Gab
  • 471
  • 3
  • 10
  • 25

1 Answers1

2

You will loose all power of asynchronous requests, but you can specify that your AJAX request must be made synchronously by adding the option async : false

function onBegin() {
        $("#spMessage").html("Processing...");
        $.ajax({
            url: '@Url.Action("test")',
            type: "POST",
            async : false,
            success: function (data) {
                if (!data.success) {
                    alert("Sorry!");
                    //onBegin function will return false
                    return false; 
                }
                else
                {
                    //onBegin function will return true
                    return true; 
                }
            }
        });
    }
sdespont
  • 13,915
  • 9
  • 56
  • 97
  • 1
    isnt it `async`, its a typo! – krishwader Jun 23 '13 at 14:52
  • @sdespont So, if I assign the ajax call in a `var request = $.ajax()...` and then `console.log(request)` should not I see `true` or `false`? – lbrahim Apr 18 '14 at 06:22
  • @Md.lbrahim In that case, even if the ajax call is asynchronous, the ´var request´ will be an ajax object, so you will see the entire methods and properties of the object in the console. More info https://api.jquery.com/jQuery.ajax/ – sdespont Apr 18 '14 at 08:15
  • @sdespont Will `onBegin` actually return a `Boolean`? I have made a test here jsfiddle.net/ibrahimislam/6gA85/ Please comment on this. – lbrahim Apr 18 '14 at 08:43