Unable to call the same variable outside of Function

Asked

Viewed 1,168 times

6

I’m having trouble calling my variable pt1 outside the function(data) and within the function getImageItem.
Whereas the function(data) is inside the function getImageItem.

function getImageItem() {
    var item = "";
    jQuery.ajax({

        url: "pegaPortifolio.php/?id=1", //?id="+idUltimo,
        dataType: "json", //Tipo de Retorno
        success: function(data) {
            var pt1 = "";
            var i = 1;
            var ultimo_id = 0;
            var size = 0,
                key;
            for (key in data) {
                if (data.hasOwnProperty(key)) size++; //cod para contar o tamanho do array multidimensional

            } //size , variavel com o tamamho do array

            for (i = 0; i < size; i++) { //monta o html para exibir os dados
                pt1 += '<div class="element-item ' + data[i].menu + '" data-category="transition"><div style="padding:2.5px;"><div style="border: 1px solid #AAAAAA;"><a href="#portfolioModal54" class="portfolio-link" data-toggle="modal"><img src="' + data[i].imageM + '" alt="project 2"><div class="fundo-port"><h1>"' + data[i].tipo + '"</h1><h2>"' + data[i].nome + '"</h2></div></a></div></div></div>';
            }
        }
    });
    //alert(pt1);
    item = pt1; //NÂO PEGA A VARIAVEL
    return item;
}

Part I want the variable to be called is in item = pt1; //NÂO PEGA A VARIAVEL.

  • 1

    Declare the variable in the scope of the getImageItem method

  • 1

    javascript.. I’ll try Vinicius

  • 1

    @Vinícius is not certain, and pt1 is not existing in Function(date)

2 answers

14


You got two problems here:

#1: you are setting the variable within a function, and so it is not accessible in the scope outside of that function.

#2: the ajax is asynchronous and return item will be run (and function closed) before ajax returns its value.

About #1:

Look at this example with your problem:

function bar() {
  var foo = 10;
}
bar();
console.log(foo); // dá erro porque "foo" não existe nesse escopo

How can you fix:

var foo;

function bar() {
  foo = 10;
}
console.log(foo); // undefined
bar();
console.log(foo); // 10

About #2:

The second problem is that ajax is asynchronous. That means the code after this piece jQuery.ajax() is run before of the code that is closed within the callback, that will only run when there is server response. (example of another question with the same problem)

In case of the second problem you have to put the code that needs the ajax data, within of that callback, or call another function from within the callback, passed the variable in the arguments.

So how do I fix?

Suggestion:

function getImageItem(callback) {
    var item = "";
    jQuery.ajax({
        url: "pegaPortifolio.php/?id=1", //?id="+idUltimo,
        dataType: "json", //Tipo de Retorno
        success: function(data) {
            var pt1 = '';
            var ultimo_id = 0,
                size = 0,
                key;
            for (key in data) {
                if (data.hasOwnProperty(key)) size++; //cod para contar o tamanho do array multidimensional
            } //size , variavel com o tamamho do array
            for (var i = 0; i < size; i++) { //monta o html para exibir os dados
                pt1 += '<div class="element-item ' + data[i].menu + '" data-category="transition"><div style="padding:2.5px;"><div style="border: 1px solid #AAAAAA;"><a href="#portfolioModal54" class="portfolio-link" data-toggle="modal"><img src="' + data[i].imageM + '" alt="project 2"><div class="fundo-port"><h1>"' + data[i].tipo + '"</h1><h2>"' + data[i].nome + '"</h2></div></a></div></div></div>';
            }
            callback(pt1); // <- aqui envias de volta para a callback da chamada da função
        }
    });
}

And that’s how you can call it:

getImageItem(function(dados){
    alert(dados);
});
  • 1

    excellent response.

1

What happens, @kaiquemix, is that the execution of ajax by default is asynchronous, that is, it will execute the alert(pt1) before the ajax request ends.

A possible solution would be:

function getImageItem() {
    var item = "";
    jQuery.ajax({

        url: "pegaPortifolio.php/?id=1", //?id="+idUltimo,
        dataType: "json", //Tipo de Retorno
        async : false,
        success: function(data) {

            var i = 1;
            var ultimo_id = 0;
            var size = 0,
                key;
            for (key in data) {
                if (data.hasOwnProperty(key)) size++; //cod para contar o tamanho do array multidimensional

            } //size , variavel com o tamamho do array

            for (i = 0; i < size; i++) { //monta o html para exibir os dados
                item += '<div class="element-item ' + data[i].menu + '" data-category="transition"><div style="padding:2.5px;"><div style="border: 1px solid #AAAAAA;"><a href="#portfolioModal54" class="portfolio-link" data-toggle="modal"><img src="' + data[i].imageM + '" alt="project 2"><div class="fundo-port"><h1>"' + data[i].tipo + '"</h1><h2>"' + data[i].nome + '"</h2></div></a></div></div></div>';
            }
        }
    });

    return item;
}

Note that the variable item continues to be created before the ajax execution, however, within the function success, instead of assigning value to variable pt1, attribute directly to the variable item.

The 'async:false' parameter has also been included, making this request ajax sincrona, that is, all the code that is after the ajax request will only be executed after the end of the request.

  • 1

    async : false, is a bad idea. I don’t give -1 because somewhere in time jQuery created this option but the modern versions of jQuery no longer have it.

  • Hello Hiago... well that worked in the copy part, however it breaks the plug of the Isotope to exchange with the menus and I only repeated the ulimo block of the database but I want to appear the others that are not appearing without pressing loads more.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.