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
- Introduction to Twilio SMS API
- Why Use Twilio for SMS Messaging?
- Creating a Twilio Account and Getting API Credentials
- Setting Up a Twilio SMS Service
- Integrating Twilio API with jQuery
- Building a Simple Web App to Send SMS
- Handling SMS Responses and Errors
- Using Twilio for OTP Verification
- Securing API Calls for SMS
- Best Practices for SMS Integration
- 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
- Go to Twilio Sign Up.
- Create an account and verify your email & phone number.
- Log in to Twilio Console.
Step 2: Get Your Twilio API Credentials
- Navigate to Dashboard β Account Info
- Copy the Account SID and Auth Token
- 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