Posting data using ajax and showing a progress loader.

DRou

Active Member
Joined
Oct 19, 2014
Messages
84
Reaction score
0
Good day, I am using Asp.Net Mvc 4 in combination with KnockoutJs for a website.

I have created a section to manage users and then added a busy indicator so that the user doesn't think nothing is happening as it takes a few seconds to save.

I've since learned that the browser will freeze the ui while posting data in a synchronized fashion, meaning that the gif that I am trying to display on my modal form does not display until the post is successful.

I then changed the async property to true ("async: true") which sure enough showed the progress loader....however now I am struggling with notifying whether the process was successful or not because when using "async: true" then the
javascript immediately jumps into the "error: " part without waiting for the server to finish saving.

Here is my javascript file that does the posting:
Code:
var urlPath = window.location.pathname;

function UserViewModel() {
    $("#divProcessing").show(); //show the loader from here
    var self = this;
    self.username = ko.observable("");

    self.password = ko.observable("");
    self.emailaddress = ko.observable("");
    self.saveUser = function () {

        if (self.username() != "") {
            $.ajax({
                url: '/Home/CreateUser',
                type: 'post',
                async: false,
                data: ko.toJSON(
                    {
                        UserName: self.username(),
                        Password: self.password(),
                        Email: self.emailaddress()
                    }
                    ),
                contentType: 'application/json',
                success: function(data) {
                    alert(data);
                },
                error: function (data) {
                    alert(data);
                }
            });
        }
    } 
}
var parent = document.getElementById('userpanel');
ko.applyBindings(UserViewModel,parent);

How do I trap whether the post was successful and wait for it? (I will look at alternatives if suggested)
Thanks
 
This is JQuery's ajax() function that KnockoutJS is using.

Async defaults to true. Running XMLHttpRequest synchronously is not the normal approach. In fact, you shouldn't be calling it Ajax ;)

The Success and Error functions you have declared as part of the ajax() function's settings are callback functions. When Async is true, then you can think of the Web browser running the XMLHttpRequest object in its own thread. These functions will get called when the XMLHttpRequest object completes the job.

If the Error function is getting called, then your backend is returning an error. The Error function can take three arguments:
Code:
error
Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )

Check out http://api.jquery.com/jquery.ajax/ for more details.

Add in the extra parameters and console.log() them out to your Javascript console to see why you're getting an error. You should also add in some extra console.log() lines to differentiate between your success function and the error function.

You can also use the Web Browser's Developer Tools to add breakpoints inside each function and debug the results of the ajax() call that way. Don't use alert() for debugging, rather use console.log.
 
Use promises.

There was this dog. It would run all the time and was very fast. It's owners loved how fast this dog could run. But, one day it broke a leg. So the owners took the dog to the vet and asked them to fix the dog so that it could run fast again. The vet said "I will make the dog run fast again!" Instead of putting the dog's leg into a cast, the vet attached a rocket to the dog's back and sent the dog home happy in a job well done.*

Likewise, Promises would solve the problem at hand, but don't actually help the OP.


Fake story to illustrate a point. This vet does not exist so don't ask me for contact details because you want a rocket attached to your dog.
 
Last edited:
There was this dog. It would run all the time and was very fast. It's owners loved how fast this dog could run. But, one day it broke a leg. So the owners took the dog to the vet and asked them to fix the dog so that it could run fast again. The vet said "I will make the dog run fast again!" Instead of putting the dog's leg into a cast, the vet attached a rocket to the dog's back and sent the dog home happy in a job well done.*

Likewise, Promises would solve the problem at hand, but don't actually help the OP.


Fake story to illustrate a point. This vet does not exist so don't ask me for contact details because you want a rocket attached to your dog.

You do know the success and error are promises right?
 
What you're saying is that you told the OP to do what he was already doing.

Well clearly he has a problem with the request being processed. If its immediately jumping to error, its not the javascript but the post url itself.
 
Well clearly he has a problem with the request being processed. If its immediately jumping to error, its not the javascript but the post url itself.

It only jumps to the error section if the async is set to true, but if async is set to false then the "success" part
gets executed.
The backend code works regardless of async state.

I will debug as per post #3
 
Ok, turns out the fix was this, I had to remove the text in bold:
Code:
                    <input id="btnSaveUser" data-bind="click: saveUser()" [B]type="submit"[/B] class="btn btn-success" value="Save" />
                                    <span  style="display: none;font-size:13px" id="divProcessing">
Adding user, please wait... <img src="/Images/ajax-loader-small.gif">

Now the loader is spinning and I can move on to the next feature.
Thx for the help guys.
 
Top
Sign up to the MyBroadband newsletter
X