Forum in maintenance, we will back soon 🙂
Create Custom Tools on WordPress training module > Test Your Ajax Function Error
Hi,
I have an issue and hoping for help.
I am on the module https://learnwithhasan.com/lessons/create-a-sample-tool/ which is "Create Custom Tools on WordPress".
I am on the step "Step 1: Create The Basic Backend Function".
Using the "Code Snippets" wp plugin I have added the provided function/code ( https://learnwithhasan.com/custom-code/basic-php-snippet-to-generate-titles/) as selected "Code Type: PHP Snippet" as instructed at the 48 second mark in the video. Here are my settings https://app.screencast.com/YbHz5Lwrc2W0u?conversation=5ghl4Jvb4WwO9imZHqagTw Â
I then go to the "Get Basic tester front end code" https://learnwithhasan.com/custom-code/test-basic-ajax-wordpress-function-frontend/ and enter my url which is https://www.ai.myleadhero.com/ and I get "There was an error. Make sure the URL and function name are correct and your function is set up properly." see image of that error here: https://app.screencast.com/w2diGBjKJovqz  . I have confirmed that the url and function name are correct per the error prompt.
Can you please tell me what I might be doing wrong?
Thanks much!
@wiscochris Add the following CORS headers to your PHP snippet:
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
It will look something like that in your code:
That worked. Thank you very much! 🙂
When I move on to the next step where we test the openai_generate_text here: https://labs.learnwithhasan.com/wp-saas/open-ai-generate-test.html
I get...Â
https://app.screencast.com/HTO4U9IThEvi5 Â
I'm not seeing the result that Hasan shares in the video. Can you please advise?
Alos, to add to the last post. When I get to this step: https://learnwithhasan.com/lessons/create-a-sample-tool/ > "Step 2: Creating the UI"Â
https://www.ai.myleadhero.com/youtube-title-generator/ I get this error :(. Advice on that too would be appreciated.
@wiscochris The error you're getting is probably from openai telling you to recharge your balance. Check your balance and buy extra credits to continue testing. Check the pricing here.
Posted by: @wiscochrisAlos, to add to the last post. When I get to this step: https://learnwithhasan.com/lessons/create-a-sample-tool/ > "Step 2: Creating the UI"Â
https://www.ai.myleadhero.com/youtube-title-generator/ I get this error :(. Advice on that too would be appreciated.
What's this interesting site name?
Â
Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack
@wiscochris Just as a tip, always check if your backend function is working perfectly by testing it without the UI, you can use online services to do that, I myself use the thunder client VS code extension.
@husein thanks for that tip. I do though have credit so thats not the issue. That message was from the wp backend/hasan's code. https://app.screencast.com/4xNt6ZzVVCX6y
@ssadvisor good call out. I updated the url from the one in Hasan's html code. https://app.screencast.com/hubiSseqrKVXU .
Unfortunately I am now getting a new error:Â https://app.screencast.com/ACkBVML6PRWQ9 Â
any further advice/guidace would be appreciated.
@wiscochris now you need to look at the backend code. The API call is returning nothing back.
Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack
@ssadvisor thanks. So when you say "look at the backend code" can you provide me with a little more clarity on what that meands. When I check this https://labs.learnwithhasan.com/wp-saas/open-ai-generate-test.html I get a message that indicates that I not mycred credits exist. https://app.screencast.com/ADGREV09Tn93A .
the php snippet is below (noting that I have confirmed that the API kep is correct - but it's not included below).
and the snippet settings are: https://app.screencast.com/lIiLviimZ14h1 Â
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 // HASSAN check for balance $user_id = get_current_user_id(); $balance = mycred_get_users_balance($user_id); if ($balance < 5) { wp_send_json("NO_BALANCE"); } // Get the topic from the AJAX request $prompt = $_POST['prompt']; // OpenAI API URL and key $api_url = 'https://api.openai.com/v1/chat/completions'; $api_key = 'sk-xxxxxxxxxxxxxxxxxxxxxxxxx; // 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 { mycred_subtract("Tool name", $user_id, 5, 'Point deduction for using tool name', time()); //HASSAN 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');
@wiscochris Ohhh, I thought the "no balance" referred to OpenAI's API. Try running the code, without this part:
if ($balance < 5) {
wp_send_json("NO_BALANCE");
}
If it works then readd the code above to your backed function and try editing your own credits from the user settings and give yourself credits manually. This should do it.
@husein thanks but actually both the users have 5000 points each. Â Please see the last posts for the most current errors.
@wiscochris Yeah, i just checked them, and the error you're getting is because the user's credit balance is less than 5, as you can see in this piece of the code:
if ($balance < 5) { wp_send_json("NO_BALANCE"); }
It states that if the user has less than 5 credits, it should print "no_balance," and that's what you're getting. However, since, as you said, both users have 5000 points, it's weird that it is also printing.
Did you try removing the if statement, running the code, and seeing if it works normally?