I transfer data from DB Ajax to the Html page

var auto_refresh = setInterval( function(){ $.ajax({ url: "test.php" , type:'GET', //dataType: "json", cache: false, success:function(data){ $('#olm').html(data); console.log(data); } }); }, 15000); 

Php

  $sql = "SELECT * FROM `work`"; $result = $mysqli->query($sql); // В цикле перебираем все записи таблицы и выводим их while ($row = $result->fetch_assoc()) { echo 'TITLE: '.$row['work']."<br/>"; echo 'SOCIAL: '.$row['title']."<br/>"; echo 'TEXT: '.$row['text']."<br/>"; echo 'TIME: '.$row['time']."<br/>"; } 

In ol ol ID, everything is displayed in one block, Actually the question: In reality, it’s all scattered across different IDs, eg echo 'TITLE: '.$row['work']."<br/>"; Write to #olm, and the second line echo 'SOCIAL: '.$row['title']."<br/>"; let's say id olm2? Thank.

  • I think you'd better send the data in the form of json and it will be easier to parse it on the client - Sergey Petrashko

1 answer 1

for example, echo json_encode(['title'=>$row['work'],'social'=>$row['title'],'text'=>$row['text'],'time'=>$row['time']]);

on the client:

 var auto_refresh = setInterval( function() { $.ajax({ url: "test.php", type: 'GET', //dataType: "json", cache: false, success: function(data) { data = JSON.parse(data); $('#olm').html('TITLE:' + data.work + '<br/>'); $('#olm2').html('SOCIAL:' + data.title + '<br/>'); console.log(data); } }); }, 15000); 

this is done so that, for example, to create a complex data object for sending to the client on the server, and on the client to receive them and use at least the way you want ... (that is, get not just html, but some entities and apply them to logic on the client and the output of the data most often in such situations is formed on the client)

  • Sergey, I will try to thank you) - Join Jexon
  • data = JSON.parse (data); swears at a syntax error, the answer comes to the console - Join Jexon
  • comment it out and see what is displayed in consoe.log - Sergey Petrashko
  • comes json response from server - Join Jexon
  • {"title": "1", "social": "Youtube", "text": "www.yrtyrsh", "time": "14:19:21"} - Join Jexon