Not being able to call the same variable out of function

5

I'm not able to call my variable pt1 out of function(data) and within function getImageItem . Being function(data) is within 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 item = pt1; //NÂO PEGA A VARIAVEL .

    
asked by anonymous 07.01.2016 / 16:41

2 answers

10

You have two issues here:

# 1: You are defining the variable within a function, so it is not accessible in scope outside that function.

# 2: ajax is asynchronous and return item will be run (and the function is 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 solve:

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. This means that the code after this piece jQuery.ajax() is run before of the code that is defined within callback , which will only run when there is response from the server. ( example of another question with the same problem )

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

So how do I solve it?

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 so you can call it like this:

getImageItem(function(dados){
    alert(dados);
});
    
07.01.2016 / 17:20
0

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

One 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 is still being created before running ajax, but within function success , instead of assigning value to variable pt1 , I assign directly to variable item . p>

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

    
07.01.2016 / 17:43