views:

41

answers:

3

hey, i am using the following function,

$.ajax({
    type: 'POST',
    url: "/User/SaveMyDetailsSettings",
    data: mySettings.MyDetailsForm.serialize(),
    success: function (data) {
        alert("callback");
        alert(data);
        if (data == "Success") {
            window.location = "User/MySettings";
        }
        else if (data == "Failed") {
            alert("Sorry!! Failed to submit your settings");
        }
    }
});

and this is added on the click event of a button( which is a simple link), but the problem here is that it does'nt wait for the response and it directly, calls the success function. Please help!!

A: 

hey, i just found the answer, if you return a false from the click even of the button then that problem wont occur. But, here button was not a conventional HTML submit, button, it was a hyperlink,only

Akshat Goel
A: 

Returning false from the click event should prevent any of the default actions from happening. But it doesn't make sense that it affects the ajax call.

Have you used the developer tools in your browser (firefox - firebug, ie - f12, chrome - resources tab, donno others) to either add a breakpoint, or monitor the ajax call?

halkeye
yes...i tried..all ajax request is working fully..fine....!!
Akshat Goel
+1  A: 

You have 2 options for this, you found one of them :)

You can either return false, like you have:

$("a").click(function() {
  //do stuff
  return false;
});

This stops the event dead in its tracks, it won't bubble, won't continue to do anything. Or...you can have it bubble, do everything it normally does, and just not follow the link using event.preventDefault(), like this:

$("a").click(function(e) { //e is the argument to the function!
  //do stuff
  e.preventDefault();
});

This is one of several event methods, can't describe it better than the API does:

Description: If this method is called, the default action of the event will not be triggered.

For example, clicked anchors will not take the browser to a new URL. We can use event.isDefaultPrevented() to determine if this method has been called by an event handler that was triggered by this event.

This is the better route if there may be other event handlers bound, or if there may be .live() event handlers, etc...with return false, they wouldn't execute, with this they would.

Nick Craver