Replacing ajax in a content call without refreshing the page

Asked

Viewed 364 times

0

I am developing a Dashboard for learning, until I came to the question of loading the content inside a div without the page update, searching I found a way using ajax and jquery. I went a little deeper and found a content saying that it is not a good practice to use ajax to load content.

at this link: http://wbruno.com.br/opiniao/parem-de-usar-ajax-eu-imploro/

I would like to know if this content is really correct and using ajax for these purposes is not correct, if it is not how to replace it

1 answer

3


First, let’s clarify basically what it is Ajax.

Ajax is an acronym for Asynchronous Javascript + XML according to the MDN Web Docs. Being more "short and thick", ajax is used to request the server in the background, that is, without the need for a new rendering (update) of the current page.

The article you read is very good but I believe it is a little exaggerated. I don’t think you should "abhor" the use of ajax, especially when it meets your needs and those of the client. And in this article, the author addresses the use exaggerated of ajax requests which surely is a valid weighting.

I believe that the ideal thing for you is to learn how this type of request works with the "pure" javascript and after getting through each line, analyze how it is using a library, which in this case is the Jquery.

// Exemplo de requisição GET sem biblioteca
var ajax = new XMLHttpRequest(); // XMLHttpRequest é uma API Javascript para criar requisições AJAX

// Define o tipo de requisição e a URL
ajax.open("GET", "https://api.myjson.com/bins/p3d8t");

// Envia a requisição
ajax.send();

// Cria um evento para receber o retorno.
ajax.onreadystatechange = function() {

  // Caso a propriedade readState seja 4 e o status seja 200, requisição foi um sucesso
  if (ajax.readyState == 4 && ajax.status == 200) {

    var data = ajax.responseText; // Obter o texto da resposta fornecida pelo servidor

    // Retorno do Ajax
    console.log(data);
  }
}

The explanations for each method and properties that were used for the request can be found in the method documentation Xmlhttprequest.

Now see the same AJAX request made above but using the Jquery library.

$.get('https://api.myjson.com/bins/p3d8t', function(data) {
  console.log(data);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

This is one of the main advantages of using libraries during development. After understanding how it works, choose the best option to solve your problem.

Browser other questions tagged

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