I have a list of projects where when the thumb of a project is clicked, the script loads the images related to the project.
$('.project-grid').on('click', 'a', function (event) {
event.preventDefault();
var $this = $(this);
var id_projeto = $this.data('projeto');
pega_imagens(id_projeto);
});
The last line calls the following function:
function pega_imagens(id_projeto){
var id_projeto = id_projeto;
$.ajax({
type: 'POST',
data: ({ id_projeto: id_projeto }),
dataType: 'json',
url: 'php/imagens.php',
success: function (data) {
var toAppend = '';
toAppend += '<div class="gutter-sizer"></div><div class="grid-sizer"></div>';
for (var i = 0; i < data.length; i++) {
toAppend += '<img class="item" src="img/' + data[i].imagem + '" width="' + data[i].largura + '" height="' + data[i].altura + '" />';
}
$('#project-expander-images-'+id_projeto).append(toAppend);
alturaTotal = $('#project-expander-images-'+id_projeto).height();
},
error: function (data) {
console.log('erro' + data);
}
});
}
My question is this: how do I use the alturaTotal
variable outside the pega_imagens
function? I know I should use a callback
function, but I do not know how to include it in the code.
UPDATE
I made some adjustments to the code, putting all the actions that were in success
into the callback function:
function pega_imagens(id_projeto, callback){
var id_projeto = id_projeto;
$.ajax({
type: 'POST',
data: ({ id_projeto: id_projeto }),
dataType: 'json',
url: 'php/imagens.php',
success: function(data){
foo(data, id_projeto);
},
error: function (data) {
console.log('erro' + data);
}
});
}
function foo(data, id_projeto){
var toAppend = '';
toAppend += '<div class="gutter-sizer"></div><div class="grid-sizer"></div>';
for (var i = 0; i < data.length; i++) {
toAppend += '<img class="item" src="img/' + data[i].imagem + '" width="' + data[i].largura + '" height="' + data[i].altura + '" />';
}
$('#project-expander-images-'+id_projeto).append(toAppend);
alturaTotal = $('#project-expander-images-'+id_projeto).height();
console.log(alturaTotal);
}
But the value returned by the alturaTotal
is incorrect.