Reputation: 12047
I have the code below that grabs some html from an AJAX request and then hides one row of a table and shows another, but even though the var
that I create to hold the html (quick_edit_html) is available after the AJAX function has run (tested by putting it in an alert box), Firebug tells me that it does not exist when I try and use it in the next function (which is not running until the AJAX request is done).
Any ideas on where I'm going wrong?
/** Run the AJAX request to grab the qucik edit html */
var load_quick_edit = jQuery.post(MyAjax.ajaxurl, data, function(response){
var quick_edit_html = response;
});
/** Display the correct quick edit row */
load_quick_edit.done(function(){
/** Hide the row that is to be edited */
jQuery('tr#display-'+slug).hide();
/** Show the quick edit row that the user has requested */
jQuery('tr#quick-edit-'+slug).show();
jQuery('tr#quick-edit-'+slug).html(quick_edit_html);
});
Thanks.
Upvotes: 1
Views: 249
Reputation: 61802
It's not available because it's out of scope. Declare it outside the post()
:
var quick_edit_html;
/** Run the AJAX request to grab the qucik edit html */
var load_quick_edit = jQuery.post(MyAjax.ajaxurl, data, function(response){
quick_edit_html = response;
});
/** Display the correct quick edit row */
load_quick_edit.done(function(){
/** Hide the row that is to be edited */
jQuery('tr#display-'+slug).hide();
/** Show the quick edit row that the user has requested */
jQuery('tr#quick-edit-'+slug).show();
jQuery('tr#quick-edit-'+slug).html(quick_edit_html);
});
Upvotes: 2
Reputation: 1214
quick_edit_html should have gone out of scope at that point in time.. You can try either storing it in global scope or prototype scope (with the this keyword)
Upvotes: 1
Reputation: 5140
Your var is declared within the anonymous ajax callback function. This scopes the var to that function meaning it can't be accessed from anywhere else.
Simply declare the var outside your functions.
var quick_edit_html;
/** Run the AJAX request to grab the qucik edit html */
var load_quick_edit = jQuery.post(MyAjax.ajaxurl, data, function(response){
quick_edit_html = response;
});
/** Display the correct quick edit row */
load_quick_edit.done(function(){
/** Hide the row that is to be edited */
jQuery('tr#display-'+slug).hide();
/** Show the quick edit row that the user has requested */
jQuery('tr#quick-edit-'+slug).show();
jQuery('tr#quick-edit-'+slug).html(quick_edit_html);
});
Upvotes: 2