How to create AI assistant using PHP and Ajax
Architectural Overview
Step-by-Step Implementation
1. Frontend Setup (HTML, CSS, JavaScript/AJAX)
HTML Structure:
<div id="chat-container">
<div id="messages"></div>
<input type="text" id="user-input" placeholder="Ask the assistant...">
<button id="send-btn">Send</button>
</div>
JavaScript/AJAX (using jQuery for simplicity):
$('#send-btn').on('click', function() {
var userMessage = $('#user-input').val();
if (userMessage.trim() === '') return;
// Display user message
$('#messages').append('<p><strong>You:</strong> ' + userMessage + '</p>');
$('#user-input').val('');
$.ajax({
url: 'api_handler.php',
type: 'POST',
data: { prompt: userMessage },
dataType: 'json',
beforeSend: function() {
// Show a loading indicator
$('#messages').append('<p id="loading">Assistant is typing...</p>');
},
success: function(response) {
// Remove loading indicator
$('#loading').remove();
if (response.error) {
$('#messages').append('<p style="color:red;">Error: ' + response.error + '</p>');
} else {
// Display assistant response
var assistantText = response.response_text;
$('#messages').append('<p><strong>Assistant:</strong> ' + assistantText + '</p>');
}
},
error: function() {
$('#loading').remove();
$('#messages').append('<p style="color:red;">An unexpected network error occurred.</p>');
}
});
});2. Backend PHP (API Interaction)
- Initialize your project: composer init
- Install the OpenAI PHP client: composer require openai-php/client
- Install a library for environment variables (for security): composer require vlucas/phpdotenv
- Load your securely stored API Key from a .env file (never hardcode it!).
- Receive the prompt from the AJAX POST data.
- Instantiate the OpenAI client.
- Make a Chat Completion API call.
- Extract the generated text.
- Send a JSON response back to the frontend.
<?php
// api_handler.php
header('Content-Type: application/json');
require 'vendor/autoload.php';
use Dotenv\Dotenv;
use OpenAI\Client;
// 1. Load Environment Variables (API Key)
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();
$apiKey = $_ENV['OPENAI_API_KEY'] ?? getenv('OPENAI_API_KEY');
if (!$apiKey) {
echo json_encode(['error' => 'API Key not configured.']);
exit;
}
// 2. Check for POST Data
if (!isset($_POST['prompt']) || empty($_POST['prompt'])) {
echo json_encode(['error' => 'No prompt received.']);
exit;
}
$userPrompt = $_POST['prompt'];
try {
// 3. Instantiate the OpenAI Client
$client = OpenAI::client($apiKey);
// 4. Make the Chat Completion API Call
$response = $client->chat()->create([
'model' => 'gpt-3.5-turbo', // Or 'gpt-4o' for advanced capabilities
'messages' => [
// Define the assistant's personality/role (System Message)
['role' => 'system', 'content' => 'You are a helpful and witty AI assistant.'],
// The user's current message
['role' => 'user', 'content' => $userPrompt],
],
]);
// 5. Extract the Generated Text
$assistantText = $response->choices[0]->message->content ?? 'Sorry, I could not generate a response.';
// **Note on Conversation History:** For a true *assistant*, you would need to store
// and pass the history of messages (both user and assistant) in the 'messages' array
// to maintain context in subsequent requests.
// 6. Send JSON Response
echo json_encode([
'success' => true,
'response_text' => $assistantText,
'model_used' => $response->model
]);
} catch (\Exception $e) {
// Handle API errors
http_response_code(500);
echo json_encode(['error' => 'API Request Failed: ' . $e->getMessage()]);
}
?>
3. Security and Best Practices
Screen Shots
Click on a photo below to scroll through the screen shots of the application!
Submit your Job or Project Today!
We can help you turn your idea into reality, take over your existing project, or extend your current development team.
Submit your idea job or project below and we will follow up with you shortly.
OUR OBJECTIVE
Our objective is to reach a place where our services will be highly regarded by businesses from various industrial domains for building their innovative busines solutions with our cutting-edge technological expertise, interactive designs and uncompromised quality.
OUR MISSION
We aspire to help businesses ranging from startups to enterprises, who reach out to us with their requirements, in achieving great lengths, expanding their reach, upscaling their products, and generate a large user-base with our outstanding and cost-effective services.
