it goes to the fetch part and instantly throws back the error
index.php file:
<?php
session_start();
use GuzzleHttpClient;
require 'vendor/autoload.php';
header('Content-Type: application/json');
$apiKey = 'API_KEY';
$model = 'gpt-3.5-turbo';
$endpoint = 'https://api.openai.com/v1/chat/completions';
$userMessage = trim($_POST['message']);
if (!isset($_SESSION['chat_history'])) {
$_SESSION['chat_history'] = [];
}
if (!empty($userMessage)) {
$_SESSION['chat_history'][] = ['role' => 'user', 'content' => $userMessage];
}
$_SESSION['chat_history'] = array_filter($_SESSION['chat_history'], function($message) {
return !empty($message['content']);
});
$client = new Client();
try {
$response = $client->post($endpoint, [
'headers' => [
'Authorization' => 'Bearer ' . $apiKey,
'Content-Type' => 'application/json',
],
'json' => [
'model' => $model,
'messages' => $_SESSION['chat_history'],
'max_tokens' => 50,
],
]);
$body = $response->getBody();
$data = json_decode($body, true);
if (isset($data['choices'][0]['message']['content'])) {
$botMessage = $data['choices'][0]['message']['content'];
$_SESSION['chat_history'][] = ['role' => 'assistant', 'content' => $botMessage];
echo json_encode(['message' => $botMessage]);
} else {
echo json_encode(['error' => 'No response from ChatGPT']);
}
} catch (Exception $e) {
echo json_encode(['error' => $e->getMessage()]);
}
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
?>
script.js file:
document.getElementById('chatForm').addEventListener('submit', function (e) {
e.preventDefault();
const userMessage = document.getElementById('userMessage').value;
const chatHistory = document.getElementById('chatHistory');
chatHistory.innerHTML += `<p><strong>User: </strong> ${userMessage}</p>`;
document.getElementById('userMessage').value = '';
fetch('index.php', { // fetching
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: 'message=' + encodeURIComponent(userMessage)
})
.then(response => response.json())
.then(data => {
if (data.message) {
chatHistory.innerHTML += `<p><strong>Bot:</strong> ${data.message}</p>`;
console.log("Gone!")
} else {
chatHistory.innerHTML += `<p><strong>Error:</strong> ${data.error}</p>`;
}
chatHistory.scrollTop = chatHistory.scrollHeight;
})
.catch(error => {
chatHistory.innerHTML += `<p>Error: ${error.message}</p>`;
chatHistory.scrollTop = chatHistory.scrollHeight;
});
});
So, when i send a message from html, i am getting this error:
Error: Unexpected token ‘<‘, ”
i tried to log “Hello” to the console to get where i’m getting error but it is not working after fetch
I tried to remove <> tags from JS file but it didn’t work
New contributor
Software Engineer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
6