Search code examples
javascripttimerreturn-valueonloadauto-update

How to update individual element in javascript only depending on service response


I would like to update a value inside a row, I don't want to use OnReload because that uploads the whole script and it is depending of a timer ex: reload this every 5 seconds ... it is not what I want. Unless there is something modern that I could use for this purpose. Not sure, what could trigger this update and how to make this script? For example: if item.updatelabel.value is different from the service response then update item.updatelabel with new value

<script>
        fetch("http:myservice").then(res => res.json()).then(serviceResponse => {
            let newdoc = '';
            for (const item of serviceResponse) {
                newdoc += `
                    <div class="1">
                       <p id="name" class="title-text  ">${item.id}</p>
                      <h2 id="id" class="updatelabel-text">${item.updatelabel}</h2>(** This is the only thing to update)
                      <p class="small-text ">some fancy text</p>
                     </div>
                `
            }
            document.querySelector('.myclass').innerHTML = newdoc;
        })
    </script>

Solution

  • Call an ajax in certain intervals and , inside the call back of the ajax replace the text

    function fetchdata(){
     $.ajax({
      url: 'fetch.php',
      type: 'post',
      success: function(response){
       // Perform operation on the return value
        if($conditionsatisfy){
                document.querySelector('.myclass').innerHTML = newdoc;
    
      }
     });
    }
    
    $(document).ready(function(){
     setInterval(fetchdata,5000);
    });