ajax - PHP trigger from webpage A to load content from database on webpage B

264

I am building a chat and all works fine.

When person A types a message in a textarea and clicks the SEND button of an HTML form, PHP sends it to the server.

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // collect textarea content
    // inserted (appended) to mySQL table.
    // collect chat content in mySQL table
    // display chat content in a <div> 
    }
?>

(I am not posting the PHP code because it's irrelevant to the problem)

Person B gets the message because of a javascript setInterval that triggers a function that grabs the chat content from the database via AJAX and then displays the chat content for person B in a div.

setInterval(refreshChat, 1000);
function refreshChat() {
    $.ajax({
        url: "http://eyesonpi.com/_/php/chat.php",
        type: "post",
        success: function(data) {
        $("#chatWindow").html(data);
        },
        error: function() {
        $("#chatWindow").prepend("Error");
        }
        });
    }

When I tried it on my iPhone, running IOS 10, the AJAX call fails. IOS 10 has a problem with AJAX. https://forums.developer.apple.com/thread/64526

I tried with plain Javascript (xmlHttpRequest) and with jQuery.

I tried the chat window of my hosting company from my iPhone and their chat works. I don't know where to begin with a workaround. How can person B get the message from person A without reloading the page? Any suggestions?

Thank you.

377

Answer

Solution:

You can try to use websockets for the chat. Or long pooling technology which allows connection to be persistent between server and client(browser or mobile app). if you choose websockets. Then you can try to use on server side: Workerman or Ratchet.Both, perfect do their job. All modern browsers natively support websocket, or you can use popular libraries like sockJS for cross-browser support.

273

Answer

Solution:

Try to replacesetInterval tosetTimeout behaviour, otherwise previous request will be killed if the next is submitted

setTimeout(refreshChat, 0);
function refreshChat() {
    $.ajax({
        url: "http://eyesonpi.com/_/php/chat.php",
        type: "post",
        success: function (data) {
            $("#chatWindow").html(data);
        },
        error: function () {
            $("#chatWindow").prepend("Error");
        }
    }).always(function () {
        setTimeout(refreshChat, 1000);
    });
}

People are also looking for solutions to the problem: php - Order posts by posts_id

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.