Skip to content
site logo mobile

Forum in maintenance, we will back soon 🙂

Create Custom Tools...
 
Notifications
Clear all

Create Custom Tools on WordPress training module > Test Your Ajax Function Error

54 Posts
5 Users
12 Reactions
301 Views
(@wiscochris)
Posts: 28
Member
Topic starter
 

@ssadvisor when I deactivate the function as you suggested I still get the bad request error in VS code. here is the code (with xxx in place of the openai key)  it's the exact same as provided here: https://learnwithhasan.com/custom-code/generate-titles-with-openai/ per the instructions  with the exception of adding CORs header and updating the function name.

any further insights would be appreciated.

 

function openai_generate_text2 () {
    //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-xxxx';  // 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_text2');
add_action('wp_ajax_nopriv_openai_generate_text', 'openai_generate_text2');
 
Posted : 04/17/2024 10:52 am
SSAdvisor
(@ssadvisor)
Posts: 1087
Noble Member
 

@wiscochris I'm guessing that you need to change

add_action('wp_ajax_openai_generate_text', 'openai_generate_text2');
add_action('wp_ajax_nopriv_openai_generate_text', 'openai_generate_text2');

to

add_action('wp_ajax_openai_generate_text2', 'openai_generate_text2');
add_action('wp_ajax_nopriv_openai_generate_text2', 'openai_generate_text2');

try it and see if you get better results.

For reference see:

Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack

 
Posted : 04/17/2024 11:58 am
(@wiscochris)
Posts: 28
Member
Topic starter
 

@ssadvisor That was the issue. I should have thought to try that. thank you!!!! I will now continue on with the course 🙂

 
Posted : 04/17/2024 12:31 pm
Hasan Aboul Hasan
(@admin)
Posts: 1117
Member Admin
 

@wiscochris I see you are using "GET" 

you should use "POST" 

I tested and it worked, check here:

 
Posted : 04/18/2024 11:26 am
SSAdvisor
(@ssadvisor)
Posts: 1087
Noble Member
 

@admin where? I see POST in the $args.

Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack

 
Posted : 04/18/2024 1:28 pm
Hasan Aboul Hasan
(@admin)
Posts: 1117
Member Admin
 

@ssadvisor I mean here:

Screenshot 2024 04 19 164441
 
Posted : 04/19/2024 1:45 pm
SSAdvisor reacted
 KB
(@knightyknight2)
Posts: 10
Active Member
 
Hi everyone!
 
I was trying to work this out and I'm sure it is something simple.
 
The basic check worked but trying to connect to OpenAI and testing, I get 
 
image

Howerver I do have the key in.  What am I missing?  Thank you in advance!

 

Code:

 
function openai_generate_text() {
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
    if (!isset($_POST['topic']) || empty($_POST['topic'])) {
        wp_send_json_error('Topic is required.');
        wp_die();
    }
 
    $topic = sanitize_text_field($_POST['topic']);
    $prompt = "Generate 5 YouTube titles for a video about " . $topic;
 
    // OpenAI API URL and key (use environment variable for security)
    $api_url = 'https://api.openai.com/v1/chat/completions';
    $api_key = getenv('sk-proj-xxxxxxxxxxxxxxxxxxxxxx'); // Retrieve API key from environment variable
 
    if (!$api_key) {
        wp_send_json_error('API key is missing.');
        wp_die();
    }
 
    // Headers for the OpenAI API
    $headers = [
        'Content-Type' => 'application/json',
        'Authorization' => 'Bearer ' . $api_key
    ];
 
    // Body for the OpenAI API
    $body = [
        'model' => 'gpt-4-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("Request error: $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'][0]['message']['content'])) {
            $generated_text = $data['choices'][0]['message']['content'];
            wp_send_json_success(['text' => $generated_text]);
        } else {
            wp_send_json_error('Unexpected API response format');
        }
    }
 
    // 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');
 
 
Posted : 06/14/2024 6:45 pm
(@husein)
Posts: 356
Member Moderator
 

@knightyknight2 Try putting the API key without using the environmental variable addition maybe you did something wrong with the setup. And did you add credits to your API account?

 
Posted : 06/15/2024 11:50 am
Hasan Aboul Hasan
(@admin)
Posts: 1117
Member Admin
 

@knightyknight2 probably the problem in the getenv method, can you share

 
Posted : 06/15/2024 12:04 pm
 KB
(@knightyknight2)
Posts: 10
Active Member
 

@husein Thank you for your reply.  Yes I do have credits in the API account (about $10).

I'm still pretty new, how would I add the environmental variable?

 
Posted : 06/15/2024 12:27 pm
 KB
(@knightyknight2)
Posts: 10
Active Member
 

@admin Thank you for you reply and it's great to hear from you!

 

I'm still pretty new, how and what do I share? 

 
Posted : 06/15/2024 12:28 pm
Hasan Aboul Hasan
(@admin)
Posts: 1117
Member Admin
 

@knightyknight2 Thanks 🙂

why did you use the getenv method in your code, just enter the API key directly as string.

here:

$api_key = getenv('sk-proj-xxxxxxxxxxxxxxxxxxxxxx'); // Retrieve API key from environment variable

 

 
Posted : 06/15/2024 1:56 pm
 KB
(@knightyknight2)
Posts: 10
Active Member
 

@admin Welp!  That was it!  I used the string directly and it works.  

 

I used ChatGPT when I got an original error and used what it produced. 

 

Thanks so much!  Now back to the course!

 
Posted : 06/15/2024 5:07 pm
 KB
(@knightyknight2)
Posts: 10
Active Member
 

Ok.  I was trying not to ask, but have no idea what could be wrong.

 

I get the error: An error occurred: Cannot read properties of undefined (reading '0') when using the frontend UI.  When I test the function, it works (using Hasan's tool at https://labs.learnwithhasan.com/wp-saas/open-ai-generate-test.html).   

 

I copied the front end UI code and replaced the url with mine and also the ensured the name of the function was correct.  I still get this error.  Any ideas what's going on?

 
Posted : 06/21/2024 9:56 pm
Hasan Aboul Hasan
(@admin)
Posts: 1117
Member Admin
 

@knightyknight2, why are you trying not to ask?!!

can you share the link of the tool please

 
Posted : 06/22/2024 8:24 am
Page 3 / 4
Share: