how to create a global variable and store values in an ajax request [duplicated]

0

How can I save the value of my AJAX response in this variable as the code shows but it does not work for me

var resp = "";
var UpdateComponent = function(){
        var rute__ =  "http://localhost/comunity/foro/getPostCurrent/",
            loc = window.location,
            index = loc.pathname.indexOf("ost/"),
            pathName = loc.pathname.substring(index+4, loc.pathname.length );
            var resp = ""; 
            $.ajax({
                url:rute__,
                type:"POST",
                data:{rute:pathName},

                success:function(data){
                    var parse = "";
                    if(data != ""){
                        parse = JSON.parse(data);
                        resp = "como estan";

                    }
                }
            });
        return resp;    


    };
    
asked by Code tutoriales 13.12.2017 в 21:10
source

1 answer

0

You are defining resp in two places, outside the function and inside. But well what you have is an error of not knowing how the scope of javascript works, create the variable outside var resp = "" , then in the success of the ajax request, assign the value that you want, and after the function is executed is that resp will have a value, simplified example:

var resp = ""
function Mia(){
 $.ajax({
....
success:function(data){ resp = data.texto    }
 })
}

//resp = ""
//ejecuto la función
Mia()
// aquí resp = el valor de data.texto que se le dio en el success
    
answered by 13.12.2017 в 21:18