skip to Main Content

I have a JavaScript code that fetches data from a PHP script, which in turn communicates with the OpenAI API. The API response is successfully logged in the console in JSON format, but when I try to access a specific property from the JSON data, I’m getting undefined.

I’ve confirmed that the API response structure is correct and the property exists.


API Response: {
  "id": "cmpl-8w4TMcnqixeHnrlYCmkhqQaQIQWqi",
  "object": "text_completion",
  "created": 1708850908,
  "model": "gpt-3.5-turbo-instruct",
  "choices": [
    {
      "text": "nApple is a multinational technology company based in Cupertino, California. It designs and manufactures consumer electronics, computer software, and online services. Some of its most popular products include the iPhone, iPad, Mac computers, and Apple Watch. The company was founded in 1976 by Steve Jobs, Steve Wozniak, and Ronald Wayne and has grown to become one of the largest and most influential companies in the world. It is known for its innovative and user-friendly products and has a strong brand following.",
      "index": 0,
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 4,
    "completion_tokens": 101,
    "total_tokens": 105
  }
}

Here’s my JavaScript Code:

document.addEventListener('DOMContentLoaded', function() {
    
 const loader = document.getElementById("svg-loader");
 const loaderFull = document.getElementById("loader");
 const submitBtn = document.getElementById("submitBtn");
 const submitText = document.getElementById("btnText");
 const quizContainer = document.getElementById("quiz-container");
 const shareBtn = document.getElementById("shareBtn");
 const imageContainer = document.getElementById("image-generator");
 

document.getElementById('submitBtn').addEventListener('click', () => {
      quizContainer.classList.add("hidden");
      loaderFull.classList.remove("hidden");
      submitAnswers();
});

function submitAnswers() {

   const prompt = `what is apple?`;
    
    fetch('api/request.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `prompt=${encodeURIComponent(prompt)}`,
    })
    .then(response => response.text())
    .then(data => {
        console.log('Parsed JSON Data:', JSON.parse(data));
        const jsonData = JSON.parse(data);

            if (data) {
                console.log('API Response:', jsonData);
                
                const resultContainer = document.getElementById('result-container');
                resultContainer.innerHTML = `<p>${jsonData.choices[0].text}</p>`;

        } else {
            console.error('Error: Invalid API response structure');
        }
    })
    .catch(error => {
        console.error('Error:', error);
    })
    .finally(() => {
         loaderFull.classList.add("hidden");
        imageContainer.classList.remove("hidden");
        setTimeout(() => {
           shareBtn.classList.remove("hidden");
        }, 1000);
        
    });
}

});

no matter which property i am trying to access i am getting undefined.

this is my php code if helps:

<?php

require __DIR__ . '/vendor/autoload.php';

use OrhanerdayOpenAiOpenAi;

$open_ai = new OpenAi('my_api_key');

$prompt = $_POST['prompt'];
header('Content-Type: application/json');

try {
    $complete = $open_ai->completion([
        'model' => 'gpt-3.5-turbo-instruct',
        'prompt' => $prompt,
        'temperature' => 0.9,
        'max_tokens' => 150,
        'frequency_penalty' => 0,
        'presence_penalty' => 0.6,
    ]);

    // Access the text from the first choice without decoding
    $generatedText = $complete;

    // Check for JSON encoding errors
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('JSON encoding error: ' . json_last_error_msg());
    }

    echo json_encode($generatedText);
} catch (Exception $e) {
    echo json_encode(['error' => $e->getMessage()]);
}
?>

2

Answers


  1. Chosen as BEST ANSWER

    ok figured it out the problem was in php code this line of code

    echo json_encode($generatedText);

    i removed the json_encode and just echo the generatedText and it worked.


  2. Try replacing this line .then(response => response.text()) with following code –

    .then(response => response.json())
    

    This converts response into JSON format. You were converting into text, hence you were getting undefined.

    Also, no need to use JSON.parse as you have already converted the response into json.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search