0

I'm using an addEventListener click event to trigger a new GPT3 request which takes the latest database post as a prompt for text completion.

The data is sent to the database through a hidden html form, with the action of the form triggering a php script.

The newly generated text is then sent to the database, which becomes the prompt for the next GPT3 request etc etc...

The problem is the event only fires once, and I would like to be able to continue to generate new text within the loading page whilst the other data heavy files within the page loads.

<form name="GPT3commentForm" id="GPT3commentForm" display="none" action="/insert_GPT3.php" method="post" autocomplete="off">
<input type="hidden" name="GPT3_field1" id="GPT3Text"/></form>

<?php
    require_once './includes/Openai.php';
    $openai = New Openai();
    //Engine, prompt and max tokens - takes the last entry of the database array as the prompt
    $openai->request("davinci", end($stack), 100);
    $latestEntry = end($stack);
    $latestEntry = JSON_encode($latestEntry);
?>

<script>
var data = <?php echo json_encode($response, JSON_HEX_TAG); ?>; // Don't forget the extra semicolon!
//turn the string into an object
const dataObj = JSON.parse(data);
console.log(typeof dataObj);
//access only the text completion section...
console.log(dataObj.choices[0].text);
GPT3Array = [];
newData = [];
newDataObj = [];
currentGPT3Text = 0;
GPT3Array[currentGPT3Text] = dataObj.choices[0].text;
document.getElementById('GPT3Text').value = GPT3Array[currentGPT3Text];
const GPT3symbolSpan = document.createElement("span");
const GPT3link = document.createElement("a");
GPT3link.textContent = GPT3Array[currentGPT3Text];
GPT3symbolSpan.appendChild(GPT3link);
GPT3LoadingText.appendChild(GPT3symbolSpan);
document.getElementById('GPT3commentForm').submit();

var generateText = function (event) {
    currentGPT3Text += 1;
    <?php
        require_once './includes/Openai.php';
        $new_openai = New Openai();
        //Engine, prompt and max tokens - takes the last entry of the database array as the prompt
        $new_openai->request("davinci", end($stack), 100);
        $latestEntry = end($stack);
        $latestEntry = JSON_encode($latestEntry);
        //unset($new_openai);
        //unset($latestEntry);        
    ?>

    //make newData and newDataObj an array to make this work...
    newData[currentGPT3Text] = <?php echo json_encode($response, JSON_HEX_TAG); ?>;
    newDataObj[currentGPT3Text] = JSON.parse(newData[currentGPT3Text]);
    GPT3Array[currentGPT3Text] = newDataObj[currentGPT3Text].choices[0].text;
    document.getElementById('GPT3Text').value = GPT3Array[currentGPT3Text];
    document.getElementById('GPT3commentForm').submit();
    GPT3link.textContent = GPT3Array[currentGPT3Text];
    console.log(currentGPT3Text);
    console.log(GPT3Array[currentGPT3Text]);
}

// GPT3LoadingText.onclick = generateText;
document.getElementById('loading-screen').addEventListener('click', generateText, {once: false}); 
</script>

Here is a link to the site showing the issue: https://surfacecollider.net/ (Ignore the other errors in the dev console, they're relating to separate issues that I'm yet to sort out with GLTF loaders which resolve on load).

And here's the php linked to the form action:

<?php
$username = "************";
$password = "************";
$database = "************";

$mysqli = new mysqli("************", $username, $password, $database);

// Don't forget to properly escape your values before you send them to DB
// to prevent SQL injection attacks.

$GPT3_field2 = $mysqli->real_escape_string($_POST['GPT3_field1']);

$query = "INSERT INTO comments (comment)
            VALUES ('{$GPT3_field2}')";

$mysqli->query($query);
?>

<?php
$query = $mysqli->query("SELECT * FROM comments");

$query = "SELECT * FROM comments";

if ($result = $mysqli->query($query)) {
    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {
        $field1name = $row["comments"];
    }
    /* free result set */
    $result->free();
}?>

<?php
$username = "************";
$password = "************";
$database = "************";
$mysqli = new mysqli("***********", $username, $password, $database);
$query = "SELECT * FROM comments";
echo '<table border="0" cellspacing="2" cellpadding="2"> 
    <tr> 
        <td> <font face="Arial">Username</font> </td> 
        <td> <font face="Arial">GPT3_field1</font> </td> 
    </tr>';

if ($result = $mysqli->query($query)) {
    while ($row = $result->fetch_assoc()) {
        $field1name = $row["GPT3_field1"];
        echo '<tr> 
                <td>'.$field1name.'</td> 
            </tr>';
    }
    $result->free();
} 

$mysqli->close();?>

Any ideas why this is happening please?

  • For your info: **GPT3** = _Generative Pre-trained Transformer 3_ is an autoregressive language model that uses deep learning to produce human-like text. – KIKO Software Sep 18 '22 at 07:55
  • Your problem is not reproducible with the code in your question. See: [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). My best guess is that the AJAX call (?) deactivates the event listener somehow. It's also possible this code is far more messed up, [mixing PHP and Javascript without knowning the actual difference](https://stackoverflow.com/questions/5054171/php-and-javascript-what-is-the-difference). – KIKO Software Sep 18 '22 at 08:01

1 Answers1

1

Answering your question

Your addEventListener is firing as expected!

https://jsfiddle.net/Ldnv1oxs/1/

You can test that in your code by commenting out the code inside the generateText() function:

var generateText = function (event) {
    console.log('click');
//    currentGPT3Text += 1;
//    <?php
//        require_once './includes/Openai.php';
//        $new_openai = New Openai();
//        //Engine, prompt and max tokens - takes the last entry of the database array as the prompt
//        $new_openai->request("davinci", end($stack), 100);
//        $latestEntry = end($stack);
//        $latestEntry = JSON_encode($latestEntry);
//        //unset($new_openai);
//        //unset($latestEntry);        
//    ?>
//
//    //make newData and newDataObj an array to make this work...
//    newData[currentGPT3Text] = <?php echo json_encode($response, JSON_HEX_TAG); ?>;
//    newDataObj[currentGPT3Text] = JSON.parse(newData[currentGPT3Text]);
//    GPT3Array[currentGPT3Text] = newDataObj[currentGPT3Text].choices[0].text;
//    document.getElementById('GPT3Text').value = GPT3Array[currentGPT3Text];
//    document.getElementById('GPT3commentForm').submit();
//    GPT3link.textContent = GPT3Array[currentGPT3Text];
//    console.log(currentGPT3Text);
//    console.log(GPT3Array[currentGPT3Text]);
}

// GPT3LoadingText.onclick = generateText;
document.getElementById('loading-screen').addEventListener('click', generateText, {once: false});

A hint, how to find your remaining problem

JavaScript:

  1. echo or var_dump() what you get from your PHP code, check if the results are, what you expect from your PHP code.
  2. If your PHP is working as expected, then prepare an code snippet with the results from your PHP, hardcoded as example into your JavaScript code.
  3. Write a JavaScript question with this code snippet.

PHP:

  1. If your PHP code is not working as expected, prepare a code snippet, that provides us all we need to understand what's going on. Example: what is the value of $stack?

Just to clarify when and where, which part of your code is executed:

  1. Your running this code snippet inside a .php file. The PHP part is running on once on request time on the server.
  2. Then some HTML is send to the browser with embedded JavaScript.
  3. Your browser loads the page, the JavaScript will be executed and the Event will fire again and again.
  4. BUT the JavaScript will be executed with the same values from PHP since PHP is not executed in the Browser again, that would be impossible.

Example: <?php echo json_encode($response, JSON_HEX_TAG); ?>; will result in an string, written on the server into your HTML and not change in the browser.

I think, in the code that we can not see, your trying for send a form to PHP with some user input. Instead your should catch the form submit by JavaScirpt, sending the user input via Ajax to a second PHP endpoint, so that PHP can give you new results on every click.

  1. mypage.php loads and send a page to the browser with embedded JS
  2. User types in the browser, event triggers.
  3. generateText() gets executed on every click.
  4. inside generateText() you can make an Ajax request to an endpoint myapi.php, send the user input and get a result
nito
  • 1,157
  • 8
  • 21