Skip to content

Forum in maintenance, we will back soon 🙂

Indepth on AI tools
 
Notifications
Clear all

Indepth on AI tools

28 Posts
4 Users
10 Reactions
104 Views
(@google-ericvictorchinedu)
Posts: 16
Eminent Member
Topic starter
 

@ssadvisor Thank You Sir.

 

 
Posted : 09/13/2024 2:13 am
(@google-ericvictorchinedu)
Posts: 16
Eminent Member
Topic starter
 

@husein @admin I keep getting the error of origin: 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I have imputed this code snippet in my backend like you instructed in your awesome course, however, i keep getting the same error.

// 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 

P.S. I am hosting WordPress locally.

 
Posted : 09/13/2024 2:17 am
(@husein)
Posts: 529
Member Moderator
 

@google-ericvictorchinedu Since you're using a local wordpress site no need to add the CORS policy lines of code. If you later on wanted to deploy it online then add them, but for the time being remove the CORS section in your code and it should work.

 
Posted : 09/14/2024 7:07 am
Hasan Aboul Hasan
(@admin)
Posts: 1252
Member Admin
 

@google-ericvictorchinedu 

did you test the endpoint first without UI?

 
Posted : 09/14/2024 9:02 am
(@google-ericvictorchinedu)
Posts: 16
Eminent Member
Topic starter
 

@admin Yes, I tested the endpoint first without UI.

 
Posted : 09/14/2024 5:23 pm
(@google-ericvictorchinedu)
Posts: 16
Eminent Member
Topic starter
 
Complain pic 1

This is the output, just '0'.

@husein I removed the CORS policy lines of code, 

@admin When i tried it with Visual Studio (Thunder Client), it worked fine

Please what should i do?

 
Posted : 09/14/2024 5:27 pm
(@husein)
Posts: 529
Member Moderator
 

@google-ericvictorchinedu Since it worked fine in the Thunder client then, the problem is with the UI code. Can you please attach both codes so that I can see what the problem is from my end?

 
Posted : 09/15/2024 7:22 am
(@google-ericvictorchinedu)
Posts: 16
Eminent Member
Topic starter
 

Here is the php code:

function openai_generate_text_basic() {    
 
 
    // Get the topic from the AJAX request
    $topic = $_POST['topic'];
    $usage = $_POST['usage'];
    $prompt = "As an expert copywriter specialized in hook generation, your task is to generate 3 hooks for the following topic: " . $topic . " for use in a: " . $usage . ". The output should be a list of hooks with the type.\n\nThe Hooks List:\n\n";
 
    // OpenAI API URL and key
    $api_url = 'https://api.openai.com/v1/chat/completions';
    $api_key = 'Y1pA1vMTX6h6sHHcIAmWqfdUxuegWOzAAkSeYpwIVbT3BlbkFJss63hwQ2myqVPDD4EhvgGogP80gSjWhAWsVScJ9B';  // 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-4',
        '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']) || !isset($data['choices'][0]['message']['content'])) {
            wp_send_json_error('API request failed. Response: ' . $body);
        } else {
            $content = $data['choices'][0]['message']['content'];
            wp_send_json($content);
        }
    }
 
    // Always die in functions echoing AJAX content
    wp_die();
}
 
add_action('wp_ajax_openai_generate_text_basic', 'openai_generate_text_basic');
add_action('wp_ajax_nopriv_openai_generate_text_basic', 'openai_generate_text_basic');
 
 
Posted : 09/15/2024 10:29 am
(@google-ericvictorchinedu)
Posts: 16
Eminent Member
Topic starter
 

Here is the CSS, HTML and JAVASCRIPT:

<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}

.container {
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
width: 400px;
}

h1 {
text-align: center;
color: #333;
}

.form-group {
margin-bottom: 20px;
}

label {
display: block;
margin-bottom: 5px;
color: #666;
}

input[type="text"], select, textarea {
width: 100%;
padding: 10px;
border-radius: 4px;
border: 1px solid #ddd;
box-sizing: border-box;
}

textarea {
height: 100px;
resize: vertical;
}

button {
width: 100%;
padding: 10px;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}

button:hover {
background-color: #0056b3;
}
</style>

<div class="container">
<h1>The Hook Generator</h1>
<div class="form-group">
<label for="topic">Enter Topic:</label>
<input type="text" id="topic" name="topic" placeholder="Enter your topic here">
</div>
<div class="form-group">
<label for="contextType">Select Context Type:</label>
<select id="contextType" name="contextType">
<option value="shortVideo">Short Video</option>
<option value="blogPost">Blog Post</option>
<option value="ad">Ad</option>
<!-- Add more options as needed -->
</select>
</div>
<button id="generateButton">Generate</button>
<br>
<br>
<div class="form-group">
<label for="result">Result:</label>
<textarea id="result" name="result" readonly></textarea>
</div>
</div>

<script>
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('http://ai-lawyer.local/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;
});
});
});
</script>

 
Posted : 09/15/2024 10:31 am
(@husein)
Posts: 529
Member Moderator
 

@google-ericvictorchinedu Please dont share your API key when you attach codes. And for next time, attach codes using the "Attach Files" button in the text editor.

 
Posted : 09/15/2024 11:48 am
(@husein)
Posts: 529
Member Moderator
 

@google-ericvictorchinedu In the frontend code ur calling the ''generate_hooks_basic' as action however it should be '

openai_generate_text_basic' So edit the line of code for it to be like this:

data.append('action', 'openai_generate_text_basic');
 
Posted : 09/15/2024 11:51 am
(@google-ericvictorchinedu)
Posts: 16
Eminent Member
Topic starter
 

@husein Duly Noted.
As for the API 🤣 Don't worry i omitted some letters.
Let me try out your suggestion.

Thank You.

This post was modified 2 months ago by Eric Victor Chinedu
 
Posted : 09/15/2024 1:20 pm
(@google-ericvictorchinedu)
Posts: 16
Eminent Member
Topic starter
 

@husein Wow! thank you so much.
it's working fine.

 
Posted : 09/15/2024 1:29 pm
Page 2 / 2
Share: