Skip to content

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
601 Views
(@wiscochris)
Posts: 28
Member
Topic starter
 

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!

 
Posted : 04/06/2024 8:10 pm
(@husein)
Posts: 531
Member Moderator
 

@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:

Screenshot 2024 04 07 131311
 
Posted : 04/07/2024 10:13 am
(@wiscochris)
Posts: 28
Member
Topic starter
 

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?

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

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.

 
Posted : 04/07/2024 12:13 pm
(@husein)
Posts: 531
Member Moderator
 

@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 : 04/07/2024 12:55 pm
(@husein)
Posts: 531
Member Moderator
 

@wiscochris Whats the error you're getting in the UI?

 
Posted : 04/07/2024 12:55 pm
SSAdvisor
(@ssadvisor)
Posts: 1139
Noble Member
 

Posted by: @wiscochris

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.

What's this interesting site name?

image

 

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

 
Posted : 04/07/2024 12:56 pm
(@husein)
Posts: 531
Member Moderator
 

@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.

 
Posted : 04/07/2024 12:57 pm
(@wiscochris)
Posts: 28
Member
Topic starter
 

@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

 
Posted : 04/07/2024 1:48 pm
(@wiscochris)
Posts: 28
Member
Topic starter
 

@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.

 
Posted : 04/07/2024 1:51 pm
SSAdvisor
(@ssadvisor)
Posts: 1139
Noble Member
 

@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

 
Posted : 04/07/2024 8:51 pm
(@wiscochris)
Posts: 28
Member
Topic starter
 

@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');
 
Posted : 04/07/2024 9:06 pm
(@husein)
Posts: 531
Member Moderator
 

@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.

 
Posted : 04/07/2024 10:23 pm
(@wiscochris)
Posts: 28
Member
Topic starter
 

@husein thanks but actually both the users have 5000 points each.  Please see the last posts for the most current errors.

 
Posted : 04/07/2024 10:40 pm
(@husein)
Posts: 531
Member Moderator
 

@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?

 
Posted : 04/08/2024 3:22 am
Page 1 / 4
Share: