Execute method / function when loading page

1

There is no duplicate of this : How to execute a jquery script when loading a page

I have a function that lists a content in a div :

function listar() {
    alert("listar"); // alert para saber se está sendo chamado
    arquivo = "lista.php";
    $.ajax({
        url:arquivo,
        success: function (textStatus) {      
            $('#iddiv1').html(textStatus);
        }
    }); 
}

I tried to load this function next to the page, but it does not work:

$(document).ready(function(){
    listar();
});

Also, I would like while running method listar() , to hide div .

Example:

$('#iddiv1').hide();
$('#iddiv2').show();

I tried this way, but without success:

$('#iddiv1').load(function() {
    $('#iddiv1').hide();
    $('#iddiv2').show();
});
    
asked by anonymous 31.07.2018 / 15:21

1 answer

1

You're probably calling the $(document).ready(function(){ event before loading jQuery, and thus resulting in an error, because $(document).ready is a jQuery event.

In this case you have 2 alternatives:

Or call the $(document).ready(function(){ after the <script> that loads jQuery (after not saying right after .After anywhere, since it is after):

<script src="jquery.js"></script>
<script>
$(document).ready(function(){
    listar();
});
</script>

Or use the native JavaScript event anywhere in the code, before or after loading jQuery:

<script>
document.addEventListener("DOMContentLoaded", function(){
   listar();
});
</script>

The .load() method is used to load HTML content to an element (a div , for example), not to detect page load.

In this case you can execute the code after the Ajax return, in success: :

success: function (textStatus) {      
   $('#iddiv1').html(textStatus).hide();
   $('#iddiv2').show();
}
    
31.07.2018 / 15:44