Loading.......
Loading...

How to create AI assistant using PHP and Ajax

Posted on 6th December, 2025
OPENAI API PHP AI ASSISTANT PHP OPENAI CHATBOT AJAX CHAT INTERFACE ASYNCHRONOUS AI CHAT PHP CURL OPENAI PHP AJAX LIVE CHAT CHATGPT API INTEGRATION PHP GPT-4 PHP APPLICATION SERVER-SIDE AI PROCESSING PHP
Creating an AI assistant using PHP and Ajax with the OpenAI API involves setting up a frontend interface to capture user input, sending that input asynchronously to a PHP backend, and having the PHP script securely interact with the OpenAI API to receive and return the AI's response.

Using the official or community-maintained OpenAI PHP client library is highly recommended over raw cURL for a more structured and manageable approach.

Architectural Overview

This architecture follows the client-server model with an asynchronous communication layer:

Frontend (HTML/JavaScript/AJAX): Provides the user interface (a chat box or input form) and uses AJAX to send the user's message to the PHP script without refreshing the page.

Backend (PHP): Receives the AJAX request, makes a secure HTTP request to the OpenAI API (typically to the Chat Completions endpoint), handles the response, and sends it back to the frontend.

OpenAI API: Processes the request using a language model (e.g., GPT-4o, GPT-3.5-turbo, gpt-5-nano) and returns a generated response.

Step-by-Step Implementation

1. Frontend Setup (HTML, CSS, JavaScript/AJAX)

Create an HTML file (e.g., index.html) with a text area for the user's prompt and a display area for the assistant's reply.

HTML Structure:
HTML Code:

<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):
This script listens for a button click, retrieves the user's input, and sends it via an AJAX POST request to your PHP backend file (e.g., api_handler.php).

JavaScript Code:

$('#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)
Create a PHP file (e.g., api_handler.php) to handle the AJAX request, communicate with OpenAI, and return the response. You should use a PHP client library (like openai-php/client) and Composer for dependency management.

A. Install Composer and PHP Client
  1. Initialize your project: composer init
  2. Install the OpenAI PHP client: composer require openai-php/client
  3. Install a library for environment variables (for security): composer require vlucas/phpdotenv

B. Implement api_handler.php

The PHP script will:

  1. Load your securely stored API Key from a .env file (never hardcode it!).
  2. Receive the prompt from the AJAX POST data.
  3. Instantiate the OpenAI client.
  4. Make a Chat Completion API call.
  5. Extract the generated text.
  6. Send a JSON response back to the frontend.

PHP Code

<?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
API Key Security: NEVER expose your OpenAI API key in your client-side JavaScript or your PHP code directly. Use environment variables and load them securely on the server side as shown above (using vlucas/phpdotenv).

Input Validation: Sanitize and validate all user input ($userPrompt) before sending it to the API to prevent potential security issues and abuse.

Error Handling: Implement robust try-catch blocks in PHP to gracefully handle API errors (like rate limits, invalid keys, or network failures) and return helpful error messages to the frontend.

Rate Limiting: On the PHP side, consider implementing your own server-side rate limiting to prevent individual users from racking up excessive API costs.

To see the script in action, please click on the Live Demo button below

CLICK HERE to demo another version using an API from Google AI Studio / GEMINI API KEY

You can click on the download button to download the updated version

Do not hesitate to support our work if this is of use to you by clicking on the donate button below.

Thank You!
The Vasplus Team.
Post Comment
Press Enter to send
No comment yet.

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.

Please Wait....
Please Wait...