Reputation: 189
I initialized first the variables for the selectors outside to minized the codes and then create a function using it. Its fine when I used the uninitialized selector but when I used the variables its not working anymore.
Heres my code:
var modalId = 'myModal',
baseModal = $('#' + modalId),
modalTitle = $('#' + modalId + ' .modal-title'),
modalContent = $('#' + modalId + ' .modal-body');
function modalCont(title, content){
modalTitle.html('');
modalContent.html('');
modalTitle.append( title );
modalContent.append( content );
baseModal.modal();
}
$(document).ready(function(){
$(document).on('click', '.option', function(e){
e.preventDefault();
var id = $(this).parents('ul').data('id'),
process = $(this).data('process');
var data = {
id : id,
process : process
}
$.ajax({
type: "POST",
url: "/ajax",
cache: false,
dataType: 'json',
data: data,
success: function( msg ) {
[Working]
/*
$('#' + modalId + ' .modal-title').html('');
$('#' + modalId + ' .modal-body').html('');
$('#' + modalId + ' .modal-title').append( 'Current User' );
$('#' + modalId + ' .modal-body').append( msg.html );
$('#' + modalId).modal();
*/
[Not Working]
modalCont('Current User', msg.html);
},
error: function( response ) {
console.log( response );
}
});
});
});
And if you have some good implementation techniques regarding with ajax please let me know. Because currently I will be working with many ajax request.
Upvotes: 0
Views: 648
Reputation: 715
I recommend you use the latest version of jQuery.ajax() look at http://api.jquery.com/jQuery.ajax/, To prepare your code for jQuery.ajax() eventual change, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead. Explained in the previous URL. In your code the problem may be that there are no elements in the DOM when applying the selectors, you need check that baseModal not empty.
var modalId = 'myModal',
baseModal = $('#' + modalId),
console.log('baseModal = ',baseModal);
modalTitle = $('#' + modalId + ' .modal-title'),
console.log('modalTitle = ',modalTitle );
modalContent = $('#' + modalId + ' .modal-body');
console.log('modalContent = ', modalContent);
Regards.
Upvotes: 3
Reputation: 2802
Do the elements referred to in the selectors already exist when baseModal etc. are initialized? If not, baseModal etc. will be empty, and they don't become magically filled later. You would need to execute the selectors again, as the working code indeed does.
Upvotes: 1