0

I'm developing a wordpress plugin and have an ajax call that definitely fetches the correct data (in this case a response from GPT API) but whenever it gets returned it always gets picked up by the error handler, with an error message appended to it. The error is a 'page not found (404)' displaying HTML mark-up.

Why, if the data is collected OK, is it always being received as an error and what is the solution?

I have the following ajax call:

        <script>
            function myAiAnnaFunction(question, answer, post_id) {                
              jQuery.ajax({
                type: "POST",
                url: "<?php echo plugins_url( 'includes/aiAnna/ask_ai-anna.php', dirname( __FILE__ ) ); ?>",
                dataType: "json",
                data: {"question" : question, "answer" : answer},
                
                success: function(data) {
                    if (data == null){
                    response = "Oh no, aiAnna was not able to fetch a response. Do not worry though as your credit has not been reduced! Please try again!";
                    }
                    else {
                    response = data.trim();
                    alert(response);
                    }
                    
                    var answerOutput = document.getElementById("feedback_box_" + post_id);
                    answerOutput.value = response;
                    
                },
                error: function (request, status, error) {
                    console.log(error);
                    console.log(request.responseText);
                }
                }); 
            }
        </script>

And here is the PHP file it calls:

<?php

$path = preg_replace('/wp-content(?!.*wp-content).*/','',__DIR__);
require($path.'wp-load.php');

function ask_ai_anna($question, $answer) {
    $ch = curl_init();

    $url = 'https://api.openai.com/v1/chat/completions';

    $api_key = 'sk-*********************************';

    $post_fields = array(
        "model" => "gpt-3.5-turbo",
        "messages" => array(
            array(
                "role" => "system",
                "content" => "You are a helpful assistant!"
            ),
            array(
                "role" => "user",
                "content" => $question
            )
        )
    );
    //"max_tokens" => 500,
    //"temperature" => 0.8
    
    $header  = [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $api_key
    ];

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_fields));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error: ' . curl_error($ch);
    }
    curl_close($ch);

    $response = json_decode($result);
    
    $response = $response->choices[0]->message->content;

    return $response;
}
  
if(isset($_POST['question']))
{
    $question = $_POST['question'];
    $answer = $_POST['answer'];
    $dataReturn = ask_ai_anna($question, $answer);
    
    echo json_encode($dataReturn);
}
?>
sw123456
  • 3,339
  • 1
  • 24
  • 42
  • 1
    This is not the way you should handle AJAX in WordPress to begin with. You should not be making a request directly to your plugin's PHP script here. How to do it properly: https://codex.wordpress.org/AJAX_in_Plugins, https://stackoverflow.com/q/43557755/1427878 – CBroe Mar 07 '23 at 07:32
  • Is this the reason I had to enable direct php access on my server? So, I see that I need to use the wordpress core Ajax hooks. Thanks. I will rewrite. But I still don't understand why the Ajax call correctly runs the PHP function, which in turn gets the API response from OpenAi, and does return the response but along with a 404 page not found message, which is then handled by the ajax error handler. Any ideas why? Or ideas on how to troubleshoot? – sw123456 Mar 07 '23 at 07:37
  • Is the 404 from your WordPress, or from the ChatGPT API? – CBroe Mar 07 '23 at 07:41
  • Wordpress I believe as the correct chat response is in the console error log that shows after the ajax error function is run client side. – sw123456 Mar 07 '23 at 07:47
  • 1
    The error might go away when you rewrite it to the proper way, so I'd start with that. – CBroe Mar 07 '23 at 07:52

0 Answers0