Make large-scale textContent exchanges with Javascript

Asked

Viewed 122 times

2

I have a page on which I want each event to be changed the textContent of a <h1>, one <p> and a <img>.

I thought of php includes or Json. I don’t know.

(It’s a lot of content, so I thought about Json)

  • 1

    What do you call "event"? Keyboard events, mouse, etc, or is it something else? By chance you mean "when X happens in the browser, you search for more content on the server via Ajax, in JSON format"?

  • 1

    @mgibsonbr No, it’s a click event. It is a page that demonstrates 6 products and has a submenu to change each of the 6, so I want to keep the structure of the page and only change the title paragraph and demonstration image

  • 1

    Yeah, so it’s a typical Ajax use case anyway. If you’ve never used Ajax, I suggest you deal with it. You can do jQuery (easier) or with pure Javascript (nothing from another world, just a little bit more laborious). I will outline the steps in an answer (with jQuery, so it doesn’t get too long), if you have any more specific questions please edit the question with the relevant details.

  • @mgibsonbr It’s just that I don’t know jQuery yet. I’m seeking to get full on pure js. It would be nice if I could do m JS. And another question: are you sure it’s Ajax? Why? And yet if I want to put a smooth page transition?

  • 1

    If you want an overview of the process, it will be much more concise in jQuery than in pure JS. If someone is willing to answer you in the format you expect, so much the better, what me What I can do is give additional references. As for Ajax, you have two alternatives: 1) render the whole page again (i.e. change the whole page at each event); 2) search only for the data that has changed using Javascript and insert this data in its correct location. This item 2 - which seems to me to be exactly where you’re trying to get - is what we call "Ajax" (asynchronous javascript and xml/json/etc).

  • 1

    P.S. I know it’s "against the website label" to answer with jQuery a question just about Javascript, and I apologize for that, but in my understanding this question is "at a high level", it’s not about how to perform step X on JS, and yes which ones steps have to be carried out.

  • @mgibsonbr of good dps I pass to JS

Show 3 more comments

1 answer

2


If you are generating a page with PHP, where the click on an element (or some other action) should fetch other results on the server, the first thing to do is specify what should be sought. I usually do this through attributes data-, but you can do it in other ways if you want:

<ul id="itens"><li>item 1</li><li>item 2</li><li>item 3</li></ul>
<a href="#" id="mais" data-mais="42">Mais itens</a>

Then you intercept the event, find out the relevant parameters for your query, and make an Ajax request to fetch that content (in this case in JSON, but it could be XML or other):

$("#mais").click(function(e) {
    e.preventDefault();
    var pagina = $(this).data("mais");
    $.getJSON('/buscar/mais/itens.php', { pagina:pagina }, function(dados) {
        // Aqui, "dados" já foi convertido de JSON (texto) para objetos javascript comuns
    });
});

Your server should then receive the /buscar/mais/itens.php?pagina=42 and return the data in JSON format. I have no practical experience with PHP, but I know you can do this using some library or simply inserting PHP variables into a text file in JSON format (remember to use mimetype correct):

php items.

{
    "pagina":<?= $pagina ?>,
    "proximaPagina":<?= $pagina + 1 ?>,
    "itens":[
        <?php
            ... (iterar sobre os itens e inserir, no formato JSON)
        ?>
    ]
}

Once received the data, all you need to do is update the page elements with the data received via Ajax. In my example above, it would be something like:

    $.getJSON('/buscar/mais/itens.php', { pagina:pagina }, function(dados) {
        for ( var i = 0 ; i < dados.itens.length ; i++ ) {
            $("#itens li").eq(i).html(dados.itens[i].valor);
        }
        $("#mais").data("mais", dados.proximaPagina);
    });

In your example, you would have to select the elements that interest you and exchange the relevant part (at h1 and in the p you exchange the innerHTML, in the img you exchange the src and perhaps also the title and the alt).

References to perform the above steps in pure Javascript:

  • Selecting an element using document.querySelector or - in older browsers - document.getElementById or other related methods;

    • The querySelector receives a syntax very similar to the one used by jQuery, it is worth using if it is a possibility.
  • Multiple elements are selected using document.querySelectorAll or document.getElementsByTagName, etc.;

  • One assigns a Handler link or button through property onclick. Other components accept handlers different (you spoke on a submenu, right? would be a select or something else?);

  • In that question shows how to make an Ajax request with pure Javascript;

  • The getJSON jQuery already converts JSON to Javascript objects for you, but if you do Ajax by hand you also have to do this conversion manually. This is done the way:

    var dados = JSON.parse(respostaDoAjax_emTexto);
    
  • The method .data of jQuery corresponds more or less to consult an attribute data- of the element in the DOM. That is:

    var pagina = $(elemento).data("mais");
    

    It’s kind of the same thing:

    var pagina = parseInt(elemento.getAttribute("data-mais"), 10);
    
  • Given an element (obtained by the methods described above), you take your children through the attribute children. So you can iterate on them.

Browser other questions tagged

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