I have this button making an ajax call using a click event. My goal is to make it so that the text inside the button changes from “submit” to “loading…” when I make that ajax call. The problem is that for some reason I can’t change the text (or even hide the button) inside of the anonymous function I stick in the .click() method until after all the code is executed. Or at least there is no noticeable effect until the ajax call is completed and instead just sticks in the active state of the button.
I turned async: false in my $.ajax call which is making it take a while to complete everything in the click event. I think I need it this way though for reasons I could go into if necessary. The reason I bring this up is because the solution I’m looking for should change the text before the ajax call in a synchronous fashion.
Here’s a simplified version of the jQuery I’m using:
$('a').click(function(){
$(this).text('loading');//changing text BEFORE the ajax call
$.ajax({
type: 'POST',
url: 'http://www.jsfiddle.net/',
data: {foo: 'bar'},
async: false
});
$(this).text('Send Request');
});
Here’s a jFiddle showing exactly what I mean.
Can I do it this way or do I need to approach this differently?
EDIT:
I finally got what you were talking about. Here’s what you can do to have the text change before the ajax starts. Use setTimeout then use the success function to set it back
http://jsfiddle.net/uJzzn/11/