1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Live Chat with PHP and AJAX

Discussion in 'Programming' started by Web_Dev_Chris, Sep 23, 2019.

  1. #1
    Hey guys,

    Btw it’s meant to say live chat in the title.

    I was trying to accomplish a live chat with an idea that I had. But I couldn’t seem to get it working.

    My idea was to have a form with a text area and submit button and to send the data thru AJAX to a PHP script that then writes to a text document. With Ajax retrieve the data back onto the page. All this happening in one function. I had an enter listener on the submit button and on the enter key for the input.

    My first problem was that I accomplished just this but the page was only updating for me as the JavaScript only updated the page I was on when I run the function thru the enter or submit button. If other people where on the website the chat would be broken.

    It got me thinking I need a script on the page that checks every second and pulls the data in. I tried this thru Ajax to update the console every second thru and Ajax script to pull the contents of the text file and then tried updating the text file thru the form and see if the text updates live thru the console but it wouldn’t update. Even though the php writes to the text file and the text changed it was still pulling in the old data. Maybe it saved the initial data in a variable.

    How can I accomplish this or what is the best way. My brains are busting at the moment.

    Thanks


    Chris
     
    Web_Dev_Chris, Sep 23, 2019 IP
  2. sarahk

    sarahk iTamer Staff

    Messages:
    28,494
    Likes Received:
    4,457
    Best Answers:
    123
    Trophy Points:
    665
    #2
    You need two scripts:
    1. submitting the new text entered by the user
    2. a sleeper that wakes up (every second) and calls the server for new content. This script will send down a counter or timestamp and will only refresh the chat window if the number returned is greater than the number used in the last refresh - just in case one gets held up and comes back after a later refresh. That assumes a full refresh, if you want it to be incremental then you'll need to work out how to handle delayed scripts.
     
    sarahk, Sep 23, 2019 IP
  3. Web_Dev_Chris

    Web_Dev_Chris Well-Known Member

    Messages:
    222
    Likes Received:
    12
    Best Answers:
    1
    Trophy Points:
    105
    #3
    The number method interests me.

    So the AJAX Sleeper script has a counter and the chat file also has a counter in it. Let’s say they both start on 0. Every second the AJAX checks if the chat file counter is greater than its own. If it is, pull the chat data into the page and increment it’s own counter by one, if the chat counter is not greater than do nothing.

    When the user submits a message. The message writes to the file and increments the counter value by one. Now when the AJAX script rechecks it will pull the chat data into the screen.

    Does this sound right?

    This is a great concept and I’m quite new to all this so these posts are very helpful. Thanks.
     
    Web_Dev_Chris, Sep 23, 2019 IP
  4. sarahk

    sarahk iTamer Staff

    Messages:
    28,494
    Likes Received:
    4,457
    Best Answers:
    123
    Trophy Points:
    665
    #4
    Nope, #1 is send only, it may trigger a refresh of the chat contents but it doesn't do it.

    #2 requests data for a refresh.

    To see this happening in practice look a datatables.net with ajax.
    upload_2019-9-24_15-12-43.png
    Datatables automatically puts a search field at the top of the table.
    When I enter text into that search field (key up) a request for search results is sent to the server with a number - 1, 2, 3, 4, 5
    Because I may be able to type faster than the search results can be displayed the results are returned with the number. That way if I type in 'sarah' and #4 result comes back before #3 it knows not to load #3.

    Your refresh code will essentially emulate that.
     
    sarahk, Sep 23, 2019 IP
  5. ketting00

    ketting00 Well-Known Member

    Messages:
    772
    Likes Received:
    27
    Best Answers:
    3
    Trophy Points:
    128
    #5
    What are you trying to do isn't the right method. You can't get new messages displayed without refreshing the page or part of it. Do it with time interval or a lot of clicking and your website will crash eventually. And you said you write message onto the document. That method is slow as hell.

    There are a lot easier ways to do live chat and you don't need PHP at all. All you need is the right tools like something called node.js. Only if you need to store data on to the database that you would need PHP, but I don't think SQL database is the right choice for the job.

    If you want browser to browser communication you can just use webRTC. Here's where to begin: https://github.com/mdn/samples-server/tree/master/s/webrtc-simple-datachannel

    But I recommend you stick to node.js. It's much simpler and there are a lot more online resources available.

    Good luck.
     
    ketting00, Sep 24, 2019 IP
  6. Web_Dev_Chris

    Web_Dev_Chris Well-Known Member

    Messages:
    222
    Likes Received:
    12
    Best Answers:
    1
    Trophy Points:
    105
    #6
    There is a lot of things about PHP that interest me such as WordPress so I am currently learning PHP and this is just a side project that I'm trying to get my head around. I'm not really developing a stand alone chat website. I'll have a look at this method as well. Thanks.
     
    Web_Dev_Chris, Sep 24, 2019 IP
  7. qwikad.com

    qwikad.com Illustrious Member Affiliate Manager

    Messages:
    7,151
    Likes Received:
    1,656
    Best Answers:
    29
    Trophy Points:
    475
    #7
    qwikad.com, Sep 24, 2019 IP
  8. Web_Dev_Chris

    Web_Dev_Chris Well-Known Member

    Messages:
    222
    Likes Received:
    12
    Best Answers:
    1
    Trophy Points:
    105
    #8
    Hi Sarah,

    Do you know if there is a resource online that explains this in more detail? I’m purely interested in the refresh script.

    If anyone code an example with Vanilla JavaScript that would really helpful. I do not like Jquery and do not use it but can still ready it to some extent.

    Thanks

    Regards
    Chris
     
    Web_Dev_Chris, Sep 25, 2019 IP
  9. sarahk

    sarahk iTamer Staff

    Messages:
    28,494
    Likes Received:
    4,457
    Best Answers:
    123
    Trophy Points:
    665
    #9
    sarahk, Sep 26, 2019 IP
  10. Web_Dev_Chris

    Web_Dev_Chris Well-Known Member

    Messages:
    222
    Likes Received:
    12
    Best Answers:
    1
    Trophy Points:
    105
    #10
    Thanks. The time stamp is to avoid the browser from caching the request?
     
    Web_Dev_Chris, Sep 30, 2019 IP
  11. JEET

    JEET Notable Member

    Messages:
    3,825
    Likes Received:
    502
    Best Answers:
    19
    Trophy Points:
    265
    #11
    I have this working on one of my website.
    I am not using Ajax to load new chat, but a iframe reload instead.
    However, you can as easily use ajax.

    The problem with your ajax not refreshing is probably because same URL is being called again and again, with no new parameters, so browser is resending cached data each time.
    Add a random string as a querystring to your URL which ajax calls.

    var ajaxURL= "mydomain/newChat.php?r=" + Math.random();

    This will avoid browser caching and call will access the php script each time.

    2 scripts will be needed, one to read new messages, other to add new messages to the file.

    Also, do not hit your server every 1 second, browser itself will crash.
    I believe 30 seconds to 60 seconds is good enough refresh time.
     
    JEET, Oct 28, 2019 IP
  12. Harry H

    Harry H Greenhorn

    Messages:
    27
    Likes Received:
    8
    Best Answers:
    2
    Trophy Points:
    23
    #12
    All this sleeping the thread and constantly checking things will degrade browser performance and possibly run up larger data bills for users. WebSockets were designed for this specific scenario and have two way communication. Unfortunately it's a fair bit of extra reading to get it working correctly. If you do it that way though it should be a lot more robust. There is a PHP library for the server side part of websockets called ratchet.
     
    Harry H, Nov 1, 2019 IP
    sarahk likes this.
  13. Web_Dev_Chris

    Web_Dev_Chris Well-Known Member

    Messages:
    222
    Likes Received:
    12
    Best Answers:
    1
    Trophy Points:
    105
    #13
    Thanks. I'll have a look at that library.

    Regards,
    Chris
     
    Web_Dev_Chris, Nov 1, 2019 IP
  14. VideoWhisper.com

    VideoWhisper.com Well-Known Member

    Messages:
    330
    Likes Received:
    6
    Best Answers:
    2
    Trophy Points:
    113
    Digital Goods:
    2
    #14
    Suggestion: Use MySQL for handling the data instead of flat files, to be able to correctly handle higher volume & simultaneous requests.
    AJAX is fine for regular traffic, with some optimizations, if server side data management is robust.
    WSS can be used to scale next, but AJAX is easier to implement on most hosts and platforms, including the popular WordPress platform.

    In example this videochat app https://paidvideochat.com/html5-videochat/ uses a combination of WSS, WebRTC and AJAX.
    WSS is used for signaling WebRTC video streaming trough a Wowza SE (because already available) and AJAX for secondary functionality like chat, web server signaling on WP platform.
    Additionally, there is communication between streaming server and web server for the streaming part (authorize streams, monitor sessions), aggregated for all streams (few requests in total). Chat and rare interactions are handled by AJAX as a secondary feature, main being live video streaming.
    We consider adding WSS interaction options for clients with large projects that may be able to add higher project complexity with an extra node server.
     
    VideoWhisper.com, Nov 23, 2019 IP
  15. scu8a

    scu8a Greenhorn

    Messages:
    81
    Likes Received:
    20
    Best Answers:
    0
    Trophy Points:
    15
    #15
    Who remembers that wonderful <layer> tag? I remember developing a live chat system for Netscape 4x, and that was back in 2000 or so. I got it to work, but it was a hack job. I used a button to call a function that changed the source of a blank gif. The only thing that changed was the querystring of the image src property. Whenever the src property of the image object was changed, the browser would send the server a GET HTTP request. I appended the user's text message onto the image's URL as a querystring and sent it off to the server. The server would add the text and user ID into a database table, and a setInterval timer on the client-side would update every x milliseconds, grabbing the chat records from the database and inserting them into a textarea box.

    Nowadays, you whipper-snappers have AJAX at your fingertips, which makes things easy. In fact, to build a chatroom using Javascript here in 2020 wouldn't present a challenge. That's the downside to the evolution of the tools we have access to for web dev. Stuff you used to hack together using such a limited scripting language at the time really refined your creative problem solving skills.

    These days, you could build a chatroom in 20 minutes and be done. That includes the server-side database work. The challenge is diminished entirely to a simple task. It's easy to become bored and complacent when there's no challenge to motivate you.
     
    scu8a, Jan 11, 2020 IP
    JEET likes this.
  16. JEET

    JEET Notable Member

    Messages:
    3,825
    Likes Received:
    502
    Best Answers:
    19
    Trophy Points:
    265
    #16
    @scu8a
    That is a nice little trick, sending message in a querystring using an image.
     
    JEET, Jan 11, 2020 IP
    scu8a likes this.
  17. scu8a

    scu8a Greenhorn

    Messages:
    81
    Likes Received:
    20
    Best Answers:
    0
    Trophy Points:
    15
    #17
    Looking back, I think it's a wonder that I ever conjured up such a contraption... and to make it function, too? Maybe I was taking shrooms or something... Either way, thanks for the compliment, @JEET :)
     
    scu8a, Jan 11, 2020 IP
    JEET likes this.
  18. JEET

    JEET Notable Member

    Messages:
    3,825
    Likes Received:
    502
    Best Answers:
    19
    Trophy Points:
    265
    #18
    Oh please don't mention it @scu8a
    Its our pleasure.
    I consider us semi-new coders fortunate that we can learn from experiences of experienced coders like yourself!

    If someone would have told me to send a text input to server, without having the technology of AJAX GET/POST and without refreshing the page, I would have scratched my head for GOD knows how long...

    The more I am thinking about it, the more I am realizing the brilliance behind that trick.
     
    Last edited: Jan 11, 2020
    JEET, Jan 11, 2020 IP
  19. NetStar

    NetStar Notable Member

    Messages:
    2,471
    Likes Received:
    541
    Best Answers:
    21
    Trophy Points:
    245
    #19
    This is a little older but PHP isn't the right language for a live chat.. It's better to use Node.js if you can.
     
    NetStar, Mar 15, 2020 IP
  20. Harry H

    Harry H Greenhorn

    Messages:
    27
    Likes Received:
    8
    Best Answers:
    2
    Trophy Points:
    23
    #20
    There is no such thing as a right language. PHP is usable on a wide variety of servers and if you need that flexibility node.js won't work for you. You didn't say why node.js is supposedly better. Did you find a library that already handles 90% of it for you? I'm not a PHP fanboy by any means and I mostly use node.js because it's generally more productive. But anything you can do in node.js pretty much you can do in PHP. If your entire project is currently already in PHP, switching to node.js is just a maintenance nightmare.
     
    Harry H, Mar 22, 2020 IP