Here is an array in php

 $content = array('time' => $time, 'user' => $user, 'message' => $message); 

If the AJAX request for this page is successful, then in the file with php output

 print_r($content); 

AJAX:

 $(document).ready(function(){ $('#submit').click(function(){ var text = $('#text').val(); $.ajax({ type : 'POST', url : 'php/chat_script.php', data : { message:text }, success: function(arr) { arr = JSON.parse(arr); $('#time').html(arr.time); $('#user').html(arr.user); $('#message').html(arr.message); } }); }); }); 

For example, I need to output this into a HTML table like this: time at <td id="time"></td> , user at <td id="time"></td> and message at <td id="message"></td> How to do this?

The array has the form:

 Array ( [0] => Array ( [time] => 16:20:11 [user] => qwe [message] => qwe ) ) 
  • You do not need to print the results, but transfer it in the form of json, which, if successful, will be processed at the front - Vasil Bodnaruk
  • @ VasilBodnaruk yes I printed them to see what it looks like. Why send in json? - Mbmenes
  • You can’t transfer ajax with php as an array, and json is a string that can be transferred and then on the js side, can be converted back into an array, now I will write the code using jquery? - Vasil Bodnaruk
  • @ VasilBodnaruk yes, of course) - Mbmenes

1 answer 1

php:

 $content = array('time' => $time, 'user' => $user, 'message' => $message); echo json_encode($content); 

axajx

 success: function(arr) { arr = JSON.parse(arr); $('#time').html(arr.time); $('#user').html(arr.user); $('#message').html(arr.message); } 
  • I have js started after pressing a button and I don’t know why, but when I click on it, it seems to be displayed for a split second and disappears, and the page is updated and all fields are empty. - Mbmenes
  • @Mbmenes The function that works when a user clicks has only ajax request? - Vasil Bodnaruk
  • Added request code to the question. - Mbmenes