1

I'm trying to use ajax to do some validations. Its calling a method from my MVC3 controller but its return true whether the controller returns true or false. The alert always is displayed.

ClientChoices/HasJobInProgress

 public Boolean HasJobInProgress(int clientId)
        {
            return false;
            //return _proxy.GetJobInProgress(clientId);
        }

Jquery.Ajax

 $("#saveButton").click(function() {
        var hasCurrentJob =  
            $.ajax({
            url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
            data: { id: @Model.ClientId },
            success: function(data){
                return data;
            }
            });
        if (hasCurrentJob) {
            alert("The current clients has a job in progress. No changes can be saved until current job completes");
        } 
    });

SOLUTION

$("#saveButton").click(function() {
            $.ajax({
            url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
            data: { id: '@Model.ClientId' },
            success: function(data){
                showMsg(data);
            },
            cache: false
        });
    });

    function showMsg(hasCurrentJob) {
          if (hasCurrentJob.toString()=="True") {
               alert("The current clients has a job in progress. No changes can be saved until current job completes");
          } 
    }
Antarr Byrd
  • 24,863
  • 33
  • 100
  • 188

1 Answers1

3

AJAX calls are async and your return data will not set the value of hasCurrentJob and it is a return to the success callback. See below on how you can show alert based on data.

    $("#saveButton").click(function() {
        //var hasCurrentJob
            $.ajax({
            url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
            data: { id: @Model.ClientId },
            success: function(data){
                showMsg(data);
            }
            });

    });

    function showMsg(hasCurrentJob) {
          if (hasCurrentJob === 'true') {
               alert("The current clients has a job in progress. No changes can be saved until current job completes");
          } 
    }
Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134