0

I am making simple php webChat and using MySQL database. MY comunication is based on AJAX requests where, when someone post message, it will be saved.

function sendData(){

var textData = $('#chatText').val();
console.log(textData);
$.ajax({
        type:'POST',
        url:'saveMessage.php',
        data: {
                message:textData
        },
        dataType: 'text',
        success: function(data){
                $('#sendInfo').html(data);
        },
        error: function(/*jqXHR, exception"*/ts){
                $('#sendInfo').html("Error send" + ts.responseText);
        }       
});

} Messages are loaded from database by another request, where there is set a timer which is sending request on server every 1 second.

    $( document ).ready(function(){
    setInterval(check, 1000);


});

function check(){

    $.ajax({
        type:'GET',
        url:'checkMessages.php',
        dataType:'json',
        success: function(result){
            //$("#messageBox").append(result);

            for(var i in result){
                $("#messageBox").append(result[i].email + ": " + result[i].mesgVal + "<br>");
            }
        },
        error: function(/*jqXHR, exception"*/ts){
                $('#sendInfo').html("Error check " + ts.responseText);
            }   
    });
}

This method is bad because of number of reqests from clients to server. I have searched for better solutions and I found webSockets(WS). My problem is that I am using webHosking and I only found LOCAL HOST tutorials. For example this.

So I am asking if there is a way to make It with WS on webHosting or there is better/ simplier way to do this client/ server comunication.

tprieboj
  • 1,680
  • 6
  • 31
  • 54
  • You could socket.io to set a constant between your frontend and your backend. You will find more informations on how to implements it in PHP at this link http://stackoverflow.com/questions/6398887/using-php-with-socket-io – Yvonnick FRIN Feb 01 '16 at 16:35

1 Answers1

0

If you need to stick with PHP, then I would advise using long polling. It's a nicer and more effective solution than the current one.

You can find a nice example of long polling in PHP here.

Zsolt Rácz
  • 103
  • 1
  • 6