Building a Real-Time Chat Application Using Pusher

Date Posted: February 22, 2015, 1:41 pm


824b1c56-87f0-11e1-9712-8f15a4b24539

Demo Download

WebSockets is an advanced technology that makes it possible to open an interactive communication session between the user’s browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply. In this tutorial we are going to create a simple chat application using Pusher. Pusher is a simple hosted API for quickly, easily and securely adding realtime bi-directional functionality via WebSockets to web and mobile apps, or any other Internet connected device.

Browser Support

Old browsers do not support WebSockets, you need latest browser that supports HTML5 WebSocket features, Please see caniuse.com to find-out all WebSocket supported browsers.

Scripts we need for our Chat Application:

  • jQuery
  • Pusher
  • Bootstrap JS and CSS (For the UI)
  • Bootbox (For our alert box)
  • Custom Styles

Create a Pusher Account

Step 1. Create an account at www.pusher.com
Step 2. Login to your pusher account then create an App, name it anything you want.
Step 3. After you have successfully created your app – the following will be generated: app_id, key, and secret.
Step 4. Go over the codes in this tutorial and replace the following: ‘your_app_id’, ‘your_app_key’, ‘your_app_secret’ with your app_id, key, and secret.
Step 5. Test the chat application in your server or local machine. Use 2 different browsers for the testing.


The Tutorial

Include the following code in the header part of your file.

1
2
3
4
5
6
7
8
9
10
11
12
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" type="text/javascript" ></script>
<script src="//js.pusher.com/2.2/pusher.min.js" type="text/javascript" type="text/javascript" ></script>   
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js" type="text/javascript" ></script>  
<script src="//cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.3.0/bootbox.min.js" type="text/javascript" ></script>

<link rel="stylesheet" type="text/css" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
<style = "text/css">
<!--       
.messages_display {height: 300px; overflow: auto;}     
.messages_display .message_item {padding: 0; margin: 0; }      
.bg-danger {padding: 10px;} -->
</style>

Create the chat form:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<div class = "container">      
    <div class = "col-md-6 chat_box">                      
        <div class = "form-control messages_display"></div>        
        <br />                     
        <div class = "form-group">             
            <label>Name</label>            
            <input type = "text" class = "input_name form-control" placeholder = "Name" />         
        </div>                     
        <div class = "form-group">             
            <label>Message</label>             
            <textarea class = "input_message form-control" placeholder = "Message"></textarea>         
        </div>                     
        <div class = "form-group input_send_holder">               
            <input type = "submit" value = "Send" class = "btn btn-primary input_send" />          
        </div>                 
    </div> 
</div>

Client Side script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<script type="text/javascript">        
// Enter your own Pusher App key
var pusher = new Pusher('your_app_key');
// Enter a unique channel you wish your users to be subscribed in.
var channel = pusher.subscribe('test_channel');
channel.bind('my_event', function(data) {
    // Add the new message to the container
    $('.messages_display').append('<p class = "message_item">' + data.message + '</p>');
    // Display the send button
    $('.input_send_holder').html('<input type = "submit" value = "Send" class = "btn btn-primary input_send" />');
    // Scroll to the bottom of the container when a new message becomes available
    $(".messages_display").scrollTop($(".messages_display")[0].scrollHeight);
});

// AJAX request
function ajaxCall(ajax_url, ajax_data) {
    $.ajax({
        type: "POST",
        url: ajax_url,
        dataType: "json",
        data: ajax_data,
        success: function(response, textStatus, jqXHR) {
            console.log(jqXHR.responseText);
        },
        error: function(msg) {}
    });
}

// Trigger for the Enter key when clicked.
$.fn.enterKey = function(fnc) {
    return this.each(function() {
        $(this).keypress(function(ev) {
            var keycode = (ev.keyCode ? ev.keyCode : ev.which);
            if (keycode == '13') {
                fnc.call(this, ev);
            }
        });
    });
}

// Send the Message
$('body').on('click', '.chat_box .input_send', function(e) {
    e.preventDefault();
   
    var message = $('.chat_box .input_message').val();
    var name = $('.chat_box .input_name').val();
   
    // Validate Name field
    if (name === '') {
        bootbox.alert('<br /><p class = "bg-danger">Please enter a Name.</p>');
   
    } else if (message !== '') {
        // Define ajax data
        var chat_message = {
            name: $('.chat_box .input_name').val(),
            message: '<strong>' + $('.chat_box .input_name').val() + '</strong>: ' + message
        }
        // Send the message to the server
        ajaxCall('message_relay.php', chat_message);
       
        // Clear the message input field
        $('.chat_box .input_message').val('');
        // Show a loading image while sending
        $('.input_send_holder').html('<input type = "submit" value = "Send" class = "btn btn-primary" disabled /> &nbsp;<img src = "loading.gif" />');
    }
});

// Send the message when enter key is clicked
$('.chat_box .input_message').enterKey(function(e) {
    e.preventDefault();
    $('.chat_box .input_send').click();
});
</script>

Server Side Script (message_relay.php):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
require('lib/Pusher.php');

// Change the following with your app details:
// Create your own pusher account @ www.pusher.com
$app_id = 'your_app_id'; // App ID
$app_key = 'your_app_key'; // App Key
$app_secret = 'your_app_secret'; // App Secret
$pusher = new Pusher($app_key, $app_secret, $app_id);

// Check the receive message
if(isset($_POST['message']) && !empty($_POST['message'])) {    
    $data['message'] = $_POST['message'];  
   
    // Return the received message
    if($pusher->trigger('test_channel', 'my_event', $data)) {              
        echo 'success';        
    } else {       
        echo 'error';  
    }
}

About author


Carl Victor Fontanos

A fine gentleman specializing in front-end and back-end development with extensive experience building high performance web applications that keeps users engaged and help businesses grow.

 
Hire Me