How to make a function fire after the entire document is loaded?

2

Currently I get a count of rows through a small query and I send this result to my main page that is created in asp.net

Currently I'm doing it in these ways and none of them have worked for me.

Form 1

  <script type="text/javascript">

      $(document).ready(function () {
          var lbltext = document.getElementById('lblPlanta').innerHTML;
          alert(lbltext);

      });

  </script>

Form 2

  <script type="text/javascript">

      $(document).ready(function () {
          var lbltext = document.getElementById('lblPlanta').textContent;
          alert(lbltext);

      });

  </script>

Form 3

  <script type="text/javascript">

      $(document).ready(function () {
          value = $("#lblPlanta").text();  
          alert(value);

      });

  </script>

Form 4

  <script type="text/javascript">

      $(document).ready(function () {
          value = $("#lblPlanta").val();  
          alert(value);

      });

  </script>

Form 5

  <script type="text/javascript">

      $(document).ready(function () {
          var lbltext = document.getElementById('lblPlanta').value;
          alert(lbltext);

      });

  </script>

This is how the Label is created. (In the code the label is above the script)

<label id="lblPlanta"></label>

Initially the label is empty because it is filled automatically, with the result that returns from the database. This result is printed in that label and if it is printed but the problem is that I can not obtain it to assign it to a variable.

Assignment of information to the tag

function getPlantas() {
    block();
    $.ajax({
        url: "../../../pagina/configuracion/empresa/confEmpresa.aspx/getPlanta",
        dataType: "json",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            $("#lblPlanta").html(data.d);

            $.unblockUI();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $.unblockUI();
        }
    });
}
  

Update

Apparently my problem is that I try to obtain a value before it is loaded through the document.ready, so I replaced it with the following method:

  $(window).load(function () {
      value = $("#lblPlanta").text(); 
      alert(value);
  });

But I still keep the alert blank, someone could mention me some way to make my method run after everything is loaded.

    
asked by David 24.01.2017 в 17:03
source

4 answers

1

AJAX calls are not deterministic in terms of the time it may take to obtain the result of the request. Most of the time this will be returned almost instantly, but is not possible to control that, the server that attends the request may be congested and take longer than usual to respond and you can not know in advance.

That's why the way is not to subscribe to the window.onload or the dom.ready , since most likely the code that makes the AJAX call is start executing just in response to one of these two events, and therefore it will still be a while since the previous events were launched and get the response from the server and place the result in the element #lblPlanta .

A correct solution is already proposed @Naos and is to subscribe to a personalized event about the element #lblPlanta that reads its value, and launch this event from the end of the success method that performs the AJAX request.

function onLblPlantaChange () {
    var lblPlantaValue = $('#lblPlanta').text();
    alert(lblPlantaValue);
}

// Me subscribo al evento change sobre el elemento
// y le asigno una función manejadora.
// En este caso que lea el valor desde el elemento
$('#lblPlanta').on('change', onLblPlantaChange);

$.ajax({
    url: 'http://httpbin.org/get?d=Orquidea',
    success: function (data) {
        // Fijo el valor en el evento
        // y lanzo el evento para que sea leido por
        // la función manejadora.
        $('#lblPlanta')
            .text(data.args.d)
            .trigger('change')
        ;

    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div id="lblPlanta">Valor Original</div>

I hope this clarifies the problem a bit.

Good luck and greetings!

    
answered by 27.01.2017 в 17:03
0

You can do it with the same function you assign:

var texto = $("#lblPlanta").html();

But you can not use it in a

$(document).ready(...

since that code is executed when loading the page and at that moment you still do not have the value loaded. You will have to obtain it at the time you need it.

    
answered by 24.01.2017 в 17:17
0

Declares a global variable

var planta;

Assign it to the getPlantas function

success: function (data) {
    $("#lblPlanta").html(data.d);
    planta =  data.d;      
    $.unblockUI();
},

Once you've done that you can use the variable plant and get its value

    
answered by 24.01.2017 в 17:17
0

Based on your question and the comments you have made and other users have commented, you can be listening in your document when the content of x elemento is changed, example:

$(document).ready(function(){
  
  $(document).on('contentchanged', '#miElemento', function()   {
    // El contenido del elemento #miElemento a sido cambiado
    console.log($('#miElemento').html());
  })

  $('#btn').click(function(){
    if($('#miElemento').html() == 'Valor'){
      $('#miElemento').html('Prueba')
    }else{
      $('#miElemento').html('Valor')
    }
    
    $('#miElemento').trigger('contentchanged')
  })
  
})
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<label type="text" id="miElemento">Valor</label>
<button type="button" id="btn">Cambiar valor</button>

So, in order for your code to work, you can simply add this before your function and a line inside it as follows:

$(document).ready(function(){

    $(document).on('contentchanged', '#lblPlanta', function()   {
        // El contenido del elemento #lblPlanta a sido cambiado
        console.log($('#lblPlanta').html());
    })

    function getPlantas() {
        block();
        $.ajax({
            url: "../../../pagina/configuracion/empresa/confEmpresa.aspx/getPlanta",
            dataType: "json",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                $("#lblPlanta").html(data.d);
                $("#lblPlanta").trigger('contentchanged'); // "Gatillamos"  el cambio al pedazo de código anterior
                $.unblockUI();
            }, 
            error: function (XMLHttpRequest, textStatus, errorThrown){
                $.unblockUI();
            }
        });
    }

    getPlantas();

})
    
answered by 24.01.2017 в 17:56