Value loses content as soon as it leaves ajax

1

When I try to get the value out of ajax, it loses its value, because?

    var url = window.location;
var id = url.toString().split("=")[1];
var nomeResponsavel = "",nomeEmpresa = "" ,emailEmpresa,telefone,site,rua,numero, bairro,estado,cidade,cep;

$.ajax({
    type: 'POST',
    url: 'load-data.php?id='+id,
    dataType: 'text',
    success: function(data) {
        msg = data;
        var values = $.parseJSON(msg);
        nomeEmpresa = values[0].razao_social;
        emailEmpresa = values[0].email_comercial;
        telefone = values[0].tel_comercial;
        site = values[0].siteweb;
        rua = values[0].end_logradouro;
        numero = values[0].end_numero;
        bairro = values[0].end_bairro;
        estado = values[0].end_eatado;
        cidade = values[0].end_cidade;
        cep = values[0].end_cep;
        nomeResponsavel = values[0].nome;


    },
    error:function(e){
        console.log(e)
    }
});
alert(nomeResponsavel);

Total Page Code

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

<head>



    <?php
    require_once("cabecalho.php");
    ?>
</head>
</html>
<body>
<!-- /. WRAPPER  -->
<!-- SCRIPTS -AT THE BOTOM TO REDUCE THE LOAD TIME-->
<!-- JQUERY SCRIPTS -->
<script src="assets/js/jquery-1.10.2.js"></script>
<!-- BOOTSTRAP SCRIPTS -->
<script src="assets/js/bootstrap.min.js"></script>
<!-- METISMENU SCRIPTS -->
<script src="assets/js/jquery.metisMenu.js"></script>
<!-- CUSTOM SCRIPTS -->
<script src="assets/js/custom.js"></script>

<script type="text/javascript">


    var url = window.location;
    var id = url.toString().split("=")[1];
    var nomeResponsavel = "",nomeEmpresa = "",emailEmpresa,telefone,site,rua,numero, bairro,estado,cidade,cep;


    $.ajax({
        type: 'POST',
        url: 'load-data.php?id='+id,
        dataType: 'text',
        success: function(data) {
            msg = data;
            var values = $.parseJSON(msg);
            nomeEmpresa = values[0].razao_social;
            emailEmpresa = values[0].email_comercial;
            telefone = values[0].tel_comercial;
            site = values[0].siteweb;
            rua = values[0].end_logradouro;
            numero = values[0].end_numero;
            bairro = values[0].end_bairro;
            estado = values[0].end_eatado;
            cidade = values[0].end_cidade;
            cep = values[0].end_cep;
            nomeResponsavel = values[0].nome;


        },
        error:function(e){
            console.log(e)
        }
    });



    var myUrl = encodeURIComponent("http://ecoprintq.com/index.php/partnerApplication/create");
    var dados = "User_full_name:"+nomeEmpresa+"&User_institution:sssss"
    $.ajax({
        url: "webproxy.php?url=" + myUrl,
        data: dados,
        crossDomain:true,
        type: "GET",
        timeout: 30000,
        dataType: "text", // "xml", "json"

        success: function(data) {
            //window.location.href = "webproxy.php?url=" + myUrl + "&" + dados;
        },
        error: function(jqXHR, textStatus, ex) {
            alert(textStatus + "," + ex + "," + jqXHR.responseText);
        }
    });


</script>

    
asked by anonymous 15.12.2016 / 17:37

3 answers

1

Yes, this is because alert(nomeResponsavel); is executed before the return of the ajax request, anything you want to do with that value must be inside the success or completed of the obj that you pass to the $.ajax() function, You can do this:

function fazer_o_suposto_com_este_valor(responsavel) {
    alert(responsavel);
}
...
$.ajax({
    type: 'POST',
    url: 'load-data.php?id='+id,
    dataType: 'text',
    success: function(data) {
        ....
        nomeResponsavel = values[0].nome;            
    },
    error:function(e){
        console.log(e);
        nomeResponsavel = 'Não há, ocorreu um erro';
    },
    complete: function() {
        fazer_o_suposto_com_este_valor(nomeResponsavel);
    }
});

Example:

function fazer_o_suposto_com_este_valor(responsavel) {
  alert(responsavel);
}
$.ajax({
  type: 'GET',
  url: 'https://hacker-news.firebaseio.com/v0/maxitem.json',
  success: function(data) {
    nomeResponsavel = data;            
  },
  error:function(e){
    nomeResponsavel = 'Não há, ocorreu um erro';
  },
  complete: function() {
    fazer_o_suposto_com_este_valor(nomeResponsavel);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
15.12.2016 / 17:47
2

An AJAX request is an asynchronous process. What this means is that it does not necessarily occur in the same synchronous execution sequence of your code, which is going up and down the code.

So when you try to access the value of the variable that is set by AJAX, it is very likely that the request has not been executed yet, and that value has not been set, even though you do this statement below the AJAX call. p>

I recommend you check out Promises that are one of ways to work with these situations in Javascript. And AJAX to better understand what's going on there.

    
15.12.2016 / 17:45
0

Check the version of jQuery you are using before using success or error .

  

Warning Deprecation: A jqXHR.success (), jqXHR.error (), and   jqXHR.complete () callbacks are removed from   jQuery 3.0. You can use jqXHR.done (), jqXHR.fail (), and,   jqXHR.always () instead.

var url = window.location;
var id = url.toString().split("=")[1];
var nomeResponsavel = "",nomeEmpresa = "" ,emailEmpresa,telefone,site,rua,numero, bairro,estado,cidade,cep;

$.ajax({
    type: 'POST',
    url: 'load-data.php?id='+id,
    dataType: 'text' 
})
.done( function( data ) {
    msg = data;
    var values = $.parseJSON(msg);
    nomeEmpresa = values[0].razao_social;
    emailEmpresa = values[0].email_comercial;
    telefone = values[0].tel_comercial;
    site = values[0].siteweb;
    rua = values[0].end_logradouro;
    numero = values[0].end_numero;
    bairro = values[0].end_bairro;
    estado = values[0].end_eatado;
    cidade = values[0].end_cidade;
    cep = values[0].end_cep;
    nomeResponsavel = values[0].nome;
    alert(nomeResponsavel);
})
.fail( function( e ) {
    console.log(e)
});

Reference: link

    
15.12.2016 / 17:56