Forum in maintenance, we will back soon 🙂
Youtube Title Generator from course gives error
Hello @Hasan, first of all I really appreciate your amazing work in simplifying these techniques on building our own Web Tools.
I have run into an error where the UI is not fetching the results. However, the functions seem to be alright as I have tested it using your tool. Can you please advise?
@appanna-m Did you add the CORS headings? Please show us your php and javascript codes
@husein Yes I did add the CORS headers to the php. Not sure of which Javascript code you're talking about.
function openai_generate_text() {
// Add CORS headers
header('Access-Control-Allow-Origin: *'); // Allows all origins
header('Access-Control-Allow-Methods: GET, POST, OPTIONS'); // Specifies the allowed methods
header('Access-Control-Allow-Headers: Content-Type, Authorization'); // Specifies the allowed headers
// Get the topic from the AJAX request
$topic = $_POST['topic'];
$prompt = "Generate 5 youtube titles for a video about " . $topic;
// OpenAI API URL and key
$api_url = 'https://api.openai.com/v1/chat/completions';
$api_key = 'sk-redacted'; // Replace with your actual OpenAI API key
// Headers for the OpenAI API
$headers = [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $api_key
];
// Body for the OpenAI API
$body = [
'model' => 'gpt-3.5-turbo',
'messages' => [['role' => 'user', 'content' => $prompt]],
'temperature' => 0.7
];
// Args for the WordPress HTTP API
$args = [
'method' => 'POST',
'headers' => $headers,
'body' => json_encode($body),
'timeout' => 120
];
// Send the request
$response = wp_remote_request($api_url, $args);
// Handle the response
if (is_wp_error($response)) {
$error_message = $response->get_error_message();
wp_send_json_error("Something went wrong: $error_message");
} else {
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
if (json_last_error() !== JSON_ERROR_NONE) {
wp_send_json_error('Invalid JSON in API response');
} elseif (!isset($data['choices'])) {
wp_send_json_error('API request failed. Response: ' . $body);
} else {
wp_send_json_success($data);
}
}
// Always die in functions echoing AJAX content
wp_die();
}
add_action('wp_ajax_openai_generate_text', 'openai_generate_text');
add_action('wp_ajax_nopriv_openai_generate_text', 'openai_generate_text');
This is the HTML code for the UI:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>YouTube Title Generator</title>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Roboto', sans-serif;
text-align: center;
padding: 20px;
background-color: #f4f4f4;
}
#text-generation-tool {
max-width: 600px;
margin: 0 auto;
background-color: #fff;
padding: 20px;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
#topic, #generate-button, #result, #copy-button {
width: 100%;
padding: 10px;
margin: 10px 0;
border-radius: 5px;
border: 1px solid #ddd;
font-size: 16px;
}
#generate-button, #copy-button {
color: #fff;
background-color: #007bff;
cursor: pointer;
border: none;
}
#generate-button:hover, #copy-button:hover {
background-color: #0056b3;
}
.hidden {
display: none;
}
.loader {
border: 5px solid #f3f3f3;
border-top: 5px solid #3498db;
border-radius: 50%;
width: 30px;
height: 30px;
animation: spin 1s linear infinite;
margin: 10px auto;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
</head>
<body>
<div id="text-generation-tool">
<header>
<h1>YouTube Title Generator</h1>
</header>
<main>
<input type="text" id="topic" placeholder="Your Topic...">
<button id="generate-button">Generate Titles!</button>
<div id="result-container" class="hidden">
<textarea rows='10' id="result" readonly></textarea>
<button id="copy-button">Copy</button>
</div>
</main>
<div id="loading" class="loader hidden"></div>
</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
const generateButton = document.getElementById('generate-button');
const copyButton = document.getElementById('copy-button');
const topicInput = document.getElementById('topic');
const resultContainer = document.getElementById('result-container');
const resultTextarea = document.getElementById('result');
const loading = document.getElementById('loading');
generateButton.addEventListener('click', async (e) => {
e.preventDefault();
generateButton.disabled = true;
loading.classList.remove('hidden');
try {
const formData = new FormData();
formData.append('action', 'openai_generate_text');
formData.append('topic', topicInput.value);
const response = await fetch('https://toolzset.com/wp-admin/admin-ajax.php', {
method: 'POST',
body: formData
});
const data = await response.json();
if (data.success) {
resultTextarea.value = data.data.choices[0].message.content;
} else {
resultTextarea.value = 'An error occurred: ' + data.data;
}
} catch (error) {
resultTextarea.value = 'An error occurred: ' + error.message;
} finally {
loading.classList.add('hidden');
resultContainer.classList.remove('hidden');
generateButton.disabled = false;
}
});
copyButton.addEventListener('click', () => {
resultTextarea.select();
document.execCommand('copy');
alert('Copied to clipboard!');
});
});
</script>
</body>
</html>
@appanna-m here is a code sharing tip. When sharing code use the Code icon (<>) above to insert the code. This preserves the indentation to make the code easier to read.
Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack
@appanna-m Your Javascript code is different from the one Hasan provides in the course. I'm not sure if that's the problem, but try replacing the javascript code with this:
document.addEventListener('DOMContentLoaded', function() { var generateButton = document.getElementById('generateButton'); var resultArea = document.getElementById('result'); var topicInput = document.getElementById('topic'); var usageSelect = document.getElementById('contextType'); generateButton.addEventListener('click', function() { var topic = topicInput.value; var usage = usageSelect.value; if (topic.trim() === '') { alert('Please enter a topic.'); return; } resultArea.value = 'Loading...'; var data = new FormData(); data.append('action', 'generate_hooks_basic'); data.append('topic', topic); data.append('usage', usage); fetch('https://settling-lacewing.10web.cloud/wp-admin/admin-ajax.php', { // Replace `ajaxurl` with the actual AJAX URL if necessary method: 'POST', body: data }) .then(response => response.json()) .then(data => { resultArea.value = data; }) .catch(error => { resultArea.value = 'An error occurred: ' + error; }); }); });
@husein I figured it out and it works now! Sorry for the trouble. I had actually not changed the website it points to, inside the html for the UI. It started working once I replaced it with my own website name.