Update a div with ajax jquery

8

Hello! I have this code, yes, I make many errors in the code, I'm new using AJAX and Javascript .

var turno_actual = 0;

function desplegarAlerta() {
  $(document).ready(function() {
    var refreshId = setInterval(function() {
      $('#turno').load('./ajax/sisben.php');
    }, 1000 );
  })

function refrescaTurno() {
  $.ajax({
    url: "prueba1.php",
    dataType:'json'
  }).done(function(response) {
    if(response.turno != turno_actual) {
      turno_actual = response.turno;
      desplegarAlerta();
    }
    window.setTimeout(refrescaTurno, 2000);
  });
}

refrescaTurno();

Well, the idea is to update div every time there is a change in db , but I could make an alert using swal and it works.

photo:

var turno_actual = 0;
function desplegarAlerta() {
  swal({
    title: "siguiente turno : " + turno_actual,
    text: "Se envio correctamente",
    icon: "success",
    button: true
  });
}


function refrescaTurno() {
  $.ajax({
    url: "prueba1.php",
    dataType:'json'
  }).done(function(response) {
    if(response.turno != turno_actual) {
      turno_actual = response.turno;
      desplegarAlerta();
    }
    window.setTimeout(refrescaTurno, 2000);
  });
}

refrescaTurno();

But when trying to do it with only the div that is on the page, with the code I left above it does not show me the number.

The code I am using to work for me at the moment is this:

$(document).ready(function() {
  var refreshId =  setInterval(function() {
    $('#turno-sisben').load('./vistas/ajax/sisben.php');
    $('#turno-familia').load('./vistas/ajax/familias_en_accion.php');
    $('#turno-salud').load('./vistas/ajax/salud.php');
    $('#turno-despacho').load('./vistas/ajax/despacho.php');
    $('#turno-adulto').load('./vistas/ajax/adulto_mayor.php');
  }, 1000 );
})

but overload when many requests are used at the same time since every second is updated

    
asked by German Alzate 21.08.2018 в 17:06
source

1 answer

4

There is a way to do it, in addition to setinterval + ajax or wesockets that is using server-sent event (the documentation in Spanish is incomplete), the idea is similar to websockets but only from server to client, not bidirectional. Here is an example taken from here , but modifying the server to repeat an operation:

Client:

var source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
    //hacer algo con el mensaje del servidor, que esta en event.data.
};   

Server:

    <?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

do {
//SELECT * FROM .....
//Y el echo de la query aca. 

  sleep(5);
  //usamos el while para mantener la conexión
} while(true);

?>
    
answered by 21.08.2018 в 18:01