Question

Here's my scenario to help you people understand my problem.

  1. on my page i have onblur event attached to many input fields.

  2. onblur event calls server side method, Method1, to set a flag and return true/false

    function compute() {

    $('#processing').attr("value", true);

    $.ajax({
        url: '/Method1',
        type: 'POST',
        contentType: 'application/json;',
        data: JSON.stringify({ quantiter: 10}),
        success: function (data) {
            if (data == "true") {
               //set icon
                $('#processing').attr("value", false);
            }
        },
        error: function () {
    
        }
    });
    

    }

  3. on true, i update my UI, i insert a small icon to indicate the field has changed

The problem i am facing is that: after modifying an input, the user can click on save button which triggers a different server side method, Method2.

<a onclick="Sauvegarder()">Save</a>


function Sauvegarder() {        
    var newProcessor =  $('#processing').attr("value");
    ...cal Method 2
}

So, the onblur event calls the Method1 but it does not complete, and Method2 gets called before Method1 completes.

With this, the small icon is not set.

Aim: my aim is to get the result from the onblur event, set my icon then call Method2 when save button is clicked.

So far i have tried to declare a global js variable: processing. I set this var to true, when i call Method1, and on success, i set it to false.

When Save is clicked, i check the value of processing. If it is false, meaning Method 1 has completed, I call Method2. The problem with this solution is that, the value of js variable processing is checked only once and it may/may not be set yet.

What can be the other ways of doing this?

Was it helpful?

Solution

Use:

$.ajax({
    url: '/Method1',
    type: 'POST',
    async: false
    contentType: 'application/json;',
    data: JSON.stringify({ quantiter: 10}),
    success: function (data) {
        if (data == "true") {
           //set icon
            $('#processing').attr("value", false);
        }
    },
    error: function () {

    }
});

Set async : false for the AJAX call.

OTHER TIPS

Take a look at the jquery method .ajaxComplete(). Here is the link ajaxComplete

If you add async:false , then it will not become ajax call , it becomes synchronous call. But I must admit that that's an option too..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top