sprocket12
sprocket12

Reputation: 5488

Text of anchor tag does not change using javascript

I execute an ajax function that takes 3 seconds + so in this time I would like the text of the a link (code below, and 1 in image) to change to "Please wait...". I tried the JavaScript code below but what happens is the text does not change and the function executes as normal. Please if someone could point out my mistake.

HTML :

<a id="emailGarageList" href="javascript:EmailGarageList(347)">Email Garage List...</a>

Screenshot :

enter image description here

Javascript :

function EmailGarageList(fId) {
    $('#emailGarageList').text('Please wait...');
    $.ajax({
        type: "POST",
        url: "Default.aspx/EmailGarageList",
        data: "{'fId':" + fId + ",'userId':" + userId + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            alert("Garage List Emailed!");
        },
        error: function () {
            alert("Error :(");
        }
    });
    $('#emailGarageList').text('Email Garage List...');
};

Upvotes: 0

Views: 702

Answers (4)

jbabey
jbabey

Reputation: 46647

I think you are looking for the beforeSend callback:

$.ajax({
    // other stuff ...
    beforeSend: function () {
        $('#emailGarageList').text('Please wait...');
    }
});

Upvotes: 0

Matthew Darnell
Matthew Darnell

Reputation: 4588

My guess is that jQuery Mobile (which I assume you are using), is modifying the DOM sso your selector cannot find $('#emailGarageList') the way you think it is.

Upvotes: 0

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

Move $('#emailGarageList').text('Email Garage List...'); inside $.ajax call back function. $.ajax is an async call and your text below is updated right away before completing the ajax call.

function EmailGarageList(fId) {
    $('#emailGarageList').text('Please wait...');
    $.ajax({
        type: "POST",
        url: "Default.aspx/EmailGarageList",
        data: "{'fId':" + fId + ",'userId':" + userId + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            alert("Garage List Emailed!");
            $('#emailGarageList').text('Email Garage List...');
        },
        error: function () {
            alert("Error :(");
        }
    });    
};

Upvotes: 3

idrumgood
idrumgood

Reputation: 4924

put the $('#emailGarageList').text('Email Garage List...'); inside your success function. Otherwise it changes, then changes right back.

Upvotes: 4

Related Questions