-2

I'm kind of a newbie at PHP. I made a messaging system, but you have to manually update the iFrame with the messages. How can I make this iFrame update when a new message is received?

jadenPete
  • 143
  • 3
  • 11
  • 2
    Why not use AJAX to get the new messages? – chris85 Dec 22 '15 at 02:37
  • I'm not very familiar with AJAX. How could I do this? – jadenPete Dec 22 '15 at 02:39
  • infinite loop to server-side... I hope you have a good hosting package. If you want something to remove a lot of stress from server requests you might want to look into using web sockets as that will make one request and once a change to the database is made it will reply rather then requesting all the data every so many seconds. – NewToJS Dec 22 '15 at 02:40
  • 1
    With AJAX you can make requests from the current window to a PHP(or other server side language) script and get the response. You can do it on a set interval and update the DOM with new messages it returns. Here's one untested example, http://code.tutsplus.com/tutorials/how-to-create-a-simple-web-based-chat-application--net-5931 – chris85 Dec 22 '15 at 02:40
  • Yeah I have a free hosting package xD Might wanna ditch the infinite loop idea.... – jadenPete Dec 22 '15 at 02:42
  • Thanks for the example. I'll look into both of your guys' ideas :) – jadenPete Dec 22 '15 at 02:44
  • Step 5 seems like what I need. – jadenPete Dec 22 '15 at 02:49

2 Answers2

1

If you're looking to regularly poll the server once the page has been loaded, you'll need to use javascript to regularly send a request to the server without reloading the page (which is what AJAX is used for).

If you could make a php messages that returns all the messages created after a certain timeframe, you could send the request using javascript.

If you're using jQuery on the client, it would look something like this (check http://api.jquery.com/jquery.ajax/ for more detail):

var timestamp = Date.now();
setInterval(function() {
  $.ajax("/newmessage?timestamp=" + timestamp, {
    success: function(data) {
      //Do something with the new messages here
      $("#messages").append("<div id='message'>" + data.message + "</div>";
    }
  });
}, 10000);
// Runs interval every 10000 milliseconds

It's also possible to use plain javascript, but the code would be a bit different.

If you've got control on the server, there are other options for messaging as well, using websockets, which keeps a connection open and passes messages back and forth (http://www.websocket.org/echo.html).

0

Thanks everybody! Here's what I did (I borrowed it from http://code.tutsplus.com/tutorials/how-to-create-a-simple-web-based-chat-application--net-5931, suggested by chris85:

<script>setInterval(function(){document.getElementById("messages").src += "";}, 2000);</script>
jadenPete
  • 143
  • 3
  • 11