Reputation: 4995
I have an Ajax function triggered by a button click like this:
$.ajax({
type: "POST",
dataType: 'json',
url: "DBDeleteList.php",
data: {listID: listID},
success: refreshMenus($(this))
});
The PHP file executes successfully and the database is updated.
The refreshMenus() is called and I call a .load() to re-fresh the menus to reflect the updated Database, however the load functions seems to load the content to soon (before the database update has been registered).
Basically what happens is is that if when I load the content from the page via Jquery .load it doesn't refresh. If I refresh the page manually (e.g. f5) the database is updated and it displays the menu correctly.
Here is the refreshMenus():
function refreshMenus( list ) {
list.parents('li').remove();
$('#sortableLoader').load(window.location.href + ' #sortableMenu');
}
The Div ID sortableMenu is updating, it's just updating too early I suppose.
Upvotes: 1
Views: 75
Reputation: 2665
try changing the refreshMenus($(this))
to refreshMenus($('#listid'))
(using the correct accessor for your list you want to refresh, of course :)
the problem you're having is that the $(this)
element you're passing to refreshMenus
is not the list element you want to update (or the triggering button, for that matter), it's the xhr (ajax) object, so the refreshMenus method isn't getting the element it needs to update.
also, what Cabloo said is good advice -
success:function(){ refreshMenus($('#listid')); }
Upvotes: 0
Reputation: 4752
I think you should be using
success:function(){ refreshMenus($(this)); }
If I'm correct, what's actually happening is $.ajax is taking the result of refreshMenus($(this))
as its callback function (it may even throw an error if you look at console). That means that refreshMenus($(this))
is actually called before the AJAX even starts. Also, you'll want to either use jQuery's context
or do as some of the other answers mentioned and variabalize the $(this)
.
Upvotes: 0
Reputation: 146191
Your refreshMenus($(this));
is being called immediately before the completion of ajax and keep $(this)
into a variable outside of ajax function. So try this
var el = $(this);
$.ajax({
type: "POST",
dataType: 'json',
url: "DBDeleteList.php",
data: { listID: listID }
success: function(){
refreshMenus(el);
}
});
Upvotes: 2
Reputation: 318182
Use the complete handler (always) instead of success (done), and add a timeout if it's neccessary, but it should'nt be as the serverside should be finished by the time the callback is called :
var elem = $(this);
$.ajax({
type: "POST",
dataType: 'json',
url: "DBDeleteList.php",
data: { listID: listID }
}).always(function() {
setTimeout(function() {
refreshMenus(elem); //`this` will be out of scope
}, 300); //or whatever you need
});
Upvotes: 0