Forum in maintenance, we will back soon 🙂
Create Custom Tools on WordPress training module > Test Your Ajax Function Error
@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');
@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:
- https://developer.wordpress.org/reference/hooks/wp_ajax_action/
- https://developer.wordpress.org/reference/hooks/wp_ajax_nopriv_action/
Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack
@ssadvisor That was the issue. I should have thought to try that. thank you!!!! I will now continue on with the course 🙂
@wiscochris I see you are using "GET"Â
you should use "POST"Â
I tested and it worked, check here:
https://reqbin.com/02bi1a9c
@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
Howerver I do have the key in. What am I missing? Thank you in advance!
Â
Code:
@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?
@knightyknight2 probably the problem in the getenv method, can you share
@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
Â
@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!
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?