Pregunta

Recently, I've made a chat box using PHP. There's no problem, but it is not very convenient as I need to manually refresh the page to check for the new message.

I'm trying to find a way so that the chat box will automatically check for new message and it will show new message.

However, what can I do? Could I

  1. Use <iframe> for the chat box and find a way to refresh the iframe only;
  2. Use javascript to check the SQL Database (it is not safe, discussed in another question, but is possible)
  3. Use ajax - I don't know anything about it, so I cannot do so.

Which of the above way is the most suitable one (and if possible, the easiest one)?

¿Fue útil?

Solución

Ajax is going to be your best option, but believe me, it's not so bad.

I hate to turn this into a tutorial, but here's a general outline.

  1. Create a php file that gets the messages, if any, and prints them somehow. Maybe some list items? echo "<li>$message</li>"

  2. Create a jquery interval that checks for messages every set seconds.

  3. Have your interval call a function with code like this:

    $.get( "get_messages.php", function( data ) { //data contains the file's output
    
     $( "#messages-box" ).append( data );//insert the new messages into a div in your html
    
    });
    

That's really all there is to it!

Otros consejos

Ajax is just a component of javascript. To create a chat box with php and javascript, the simplest solution is using setInterval function to refresh the chatbox

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top