Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get my jQuery to not execute the <a href> until after a successful ajax post?

I am trying to update the database and send the users browser to a different page with one click.

The Html looks like this:

<a id='updateLiveProgress' style='width:118px;' href='~link~'>Click here</a>

The Javascript looks like this:

        $("#updateLiveProgress").live("click", function(e){

            var ajaxlink = "~ajaxlink~"
            $.post(ajaxlink, function(data, e){
                return true;
            });

        });

When the user clicks the link, it's supposed to update the database through the ajax link and then the page that is returned will be dependent on the ajax database updates. The problem is that it seems that the page loads before the ajax finishes updating the database. I'm trying to pass the click event throught to the ajax using e to prevent the link from executing until after the ajax call finishes, but it doesn't seem to be working.

Is there a better way for me to accomplsh this?

like image 714
quakkels Avatar asked Apr 18 '11 17:04

quakkels


People also ask

How do I make jQuery wait for an AJAX call to finish before it returns?

click( function(){ $. ajax({ url: $(this). attr('href'), type: 'GET', cache: false, timeout: 30000, error: function(){ return true; }, success: function(msg){ if (parseFloat(msg)){ return false; } else { return true; } } }); }); jquery.

How check AJAX request is successful jQuery?

$. ajax({ url: "page. php", data: stuff, success: function(response){ console. log("success"); } });

How do you write if condition in AJAX success?

ajax({ url: $(this). attr('href'), type: $(this). attr('method'), dataType: 'json', success: function (data) { //PROBLEM HERE ********** if(data. success == 'true' ){ alert('true'); } else { alert('false') }; ;} });


1 Answers

Try doing this:

    $("#updateLiveProgress").live("click", function(e){
        e.preventDefault();
        var href = this.href;
        var ajaxlink = "~ajaxlink~"
        $.post(ajaxlink, function(data, e){
            window.location = href;
        });
        return false;
    });

As of jQuery 1.7 do this (using .on instead of .live):

    $("#updateLiveProgress").on("click", function(e){
        e.preventDefault();
        var href = this.href;
        var ajaxlink = "~ajaxlink~"
        $.post(ajaxlink, function(data, e){
            window.location = href;
        });
        return false;
    });
like image 53
Naftali Avatar answered Nov 04 '22 07:11

Naftali