Value loses content as soon as it exits ajax

Asked

Viewed 150 times

1

When I try to take value out of ajax, it loses 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>

3 answers

2

An AJAX request is an asynchronous process. What this means is that it doesn’t necessarily occur in the same synchronous sequence of execution of your code, which is going from top to bottom going through 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 yet been executed, and this value has not been set, even if you do this instruction below the AJAX call.

I recommend you take a look at Promises that are one of the ways to work with these situations in Javascript. And in AJAX to better understand what is happening there.

1


Yeah, that’s because alert(nomeResponsavel); is executed before the return of the ajax request, anything you wanted to do with that value must be within the success or completed of the obj that you move to the function $.ajax(), 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>

  • Actually, I wanted to take this ajax value and send it to another ajax, only it sends.

  • I even put the full code of the page. I wanted to take the value I get from an ajax and send to another ajax

  • Using this example you can put the new upload inside the function fazer_o_suposto_com_este_valor, who currently has only Alert but can process whatever you want there... Place a new order including @Gabrielfalieri

  • thanks my dear, gave it right

  • @Gabrielfalieri nothing. I’m glad you solved

  • Dude, you have to, when sending, as if it were a post, just fill out the cross-Omain form?

  • 'Cause there’s a captcha in this form that I’m sending the information, and the captcha is feeding me

Show 2 more comments

0

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

Deprecation warning: A jqXHR.Success(), jqXHR.error() jqXHR.complete()return calls are removed from jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), 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: http://api.jquery.com/jquery.ajax/

Browser other questions tagged

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