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);
}
?>