Sending SMS using Twilio API and jQuery

Loading

Sending SMS Using Twilio API and jQuery – A Complete Guide

Sending SMS programmatically has become an essential feature for various applications, such as two-factor authentication (2FA), order confirmations, notifications, and reminders. One of the most popular services for sending SMS is Twilio, which provides a reliable API to integrate SMS functionality into web applications.

In this guide, we will cover everything you need to know about sending SMS using Twilio API and jQuery, from setting up Twilio to implementing jQuery-based SMS sending.


Table of Contents

  1. Introduction to Twilio SMS API
  2. Why Use Twilio for SMS Messaging?
  3. Creating a Twilio Account and Getting API Credentials
  4. Setting Up a Twilio SMS Service
  5. Integrating Twilio API with jQuery
  6. Building a Simple Web App to Send SMS
  7. Handling SMS Responses and Errors
  8. Using Twilio for OTP Verification
  9. Securing API Calls for SMS
  10. Best Practices for SMS Integration
  11. Conclusion

1. Introduction to Twilio SMS API

The Twilio API allows developers to send SMS and make calls programmatically. It provides various SDKs, but in this guide, we will use Twilio’s REST API with jQuery and AJAX to send SMS messages from a web application.

βœ… Features of Twilio SMS API:

  • Send SMS to any mobile number worldwide 🌎
  • Support for long messages and MMS
  • Delivery tracking with webhooks
  • Two-way messaging (receive replies)
  • Phone number verification (OTP)
  • Affordable pricing with free trial credits

2. Why Use Twilio for SMS Messaging?

πŸ”Ή Reliability – Used by thousands of businesses for secure messaging
πŸ”Ή Scalability – Handles high volumes of messages efficiently
πŸ”Ή Simple API – Easy-to-use REST API for developers
πŸ”Ή Global Coverage – Supports 180+ countries
πŸ”Ή Security – Secure communication with encrypted messages


3. Creating a Twilio Account and Getting API Credentials

Step 1: Sign Up for a Twilio Account

  1. Go to Twilio Sign Up.
  2. Create an account and verify your email & phone number.
  3. Log in to Twilio Console.

Step 2: Get Your Twilio API Credentials

  1. Navigate to Dashboard β†’ Account Info
  2. Copy the Account SID and Auth Token
  3. Buy or use a free Twilio phone number

πŸ”Ή Example Credentials (DO NOT use in production)

Account SID: ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Auth Token: 1a2b3c4d5e6f7g8h9i0j
Twilio Phone Number: +1234567890

4. Setting Up a Twilio SMS Service

Twilio requires an API endpoint to send SMS. We will create a Node.js backend that interacts with Twilio, and a jQuery frontend to trigger SMS sending.


5. Integrating Twilio API with jQuery

Since jQuery cannot directly call Twilio’s API (due to security restrictions), we need a server-side script to handle SMS requests.

Step 1: Install Twilio SDK for Node.js

npm install express twilio body-parser cors dotenv

Step 2: Create a Backend Script (Node.js + Express)

Create a file server.js and add the following code:

require('dotenv').config();
const express = require('express');
const twilio = require('twilio');
const cors = require('cors');
const bodyParser = require('body-parser');

const app = express();
app.use(cors());
app.use(bodyParser.json());

const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = new twilio(accountSid, authToken);

app.post('/send-sms', (req, res) => {
    const { to, message } = req.body;

    client.messages.create({
        body: message,
        from: process.env.TWILIO_PHONE_NUMBER,
        to: to
    }).then(message => {
        res.status(200).json({ success: true, messageId: message.sid });
    }).catch(error => {
        res.status(500).json({ success: false, error: error.message });
    });
});

app.listen(3000, () => console.log("Server running on port 3000"));

πŸ”Ή Environment Variables (.env)

TWILIO_ACCOUNT_SID=ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
TWILIO_AUTH_TOKEN=1a2b3c4d5e6f7g8h9i0j
TWILIO_PHONE_NUMBER=+1234567890

6. Building a Simple Web App to Send SMS

Now, let’s create a jQuery-based frontend to send SMS.

Step 3: Create an HTML Form

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Send SMS with Twilio</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <h2>Send an SMS</h2>
    <input type="text" id="phoneNumber" placeholder="Enter Phone Number">
    <textarea id="message" placeholder="Enter Message"></textarea>
    <button id="sendSms">Send SMS</button>
    <p id="response"></p>

    <script>
        $("#sendSms").click(function() {
            var to = $("#phoneNumber").val();
            var message = $("#message").val();

            $.ajax({
                url: "http://localhost:3000/send-sms",
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify({ to: to, message: message }),
                success: function(response) {
                    $("#response").text("Message Sent! ID: " + response.messageId);
                },
                error: function(error) {
                    $("#response").text("Error: " + error.responseJSON.error);
                }
            });
        });
    </script>
</body>
</html>

7. Handling SMS Responses and Errors

Twilio provides status callbacks for SMS messages. You can track whether a message was delivered, failed, or pending.

client.messages.create({
    body: "Test message",
    from: process.env.TWILIO_PHONE_NUMBER,
    to: "+1234567890",
    statusCallback: "http://yourserver.com/sms-status"
});

8. Using Twilio for OTP Verification

Step 1: Generate OTP

const otp = Math.floor(100000 + Math.random() * 900000);

Step 2: Send OTP via Twilio

client.messages.create({
    body: `Your OTP is: ${otp}`,
    from: process.env.TWILIO_PHONE_NUMBER,
    to: "+1234567890"
});

9. Securing API Calls for SMS

πŸ” Best security practices:
βœ… Use environment variables for credentials
βœ… Rate-limit SMS requests
βœ… Implement user authentication


10. Best Practices for SMS Integration

πŸ”Ή Verify phone numbers before sending
πŸ”Ή Limit message frequency to avoid spam
πŸ”Ή Use country-specific compliance (e.g., DND lists)
πŸ”Ή Track message delivery using webhooks


In this guide, we successfully:
βœ… Set up a Twilio account and API credentials
βœ… Built a Node.js server to send SMS
βœ… Created a jQuery frontend for sending messages
βœ… Implemented OTP verification with Twilio

Now, you can integrate Twilio SMS API into your applications

Leave a Reply

Your email address will not be published. Required fields are marked *