php CodeIgnitor dynamic content passing to Views

I am working on a model to generate responses for the selected AImodels and send them to views at the end simultaneously as you can see in my process method below.

<?php

namespace AppControllers;

use AppModelsExamModel;
use AppModelsVendorModel;
use AppModelsExamTopicModel;
use AppModelsCertificationModel;
use AppModelsAIResponseModel;
use ReactPromisePromise;

class OptionController extends BaseController
{
    public function index()
    {
        // Display the form view
        return view('options_form');
    }
public function process()
{
    $db = ConfigDatabase::connect();

    $examModel = new ExamModel();
    $examTopicModel = new ExamTopicModel();
    $certificationModel = new CertificationModel();
    $vendorModel = new VendorModel();
    $responseModel = new AIResponseModel();

    // Get form inputs
    $exam_codes_raw = $this->request->getPost('examCodes'); // The raw input string of exam codes
    $aiModels = $this->request->getPost('aiModel'); // Array of selected AI models
    $prompt_template = $this->request->getPost('prompt'); // User-provided prompt
    $project_name = $this->request->getPost('projectName'); // User-provided project name

    // Ensure $exam_codes_raw is treated as a string
    if (is_array($exam_codes_raw)) {
        $exam_codes_raw = implode("n", $exam_codes_raw); // Convert array to string
    }

    // Split the raw exam codes string into an array
    $exam_codes = preg_split('/[rn,]+/', trim($exam_codes_raw));

    $responses = [];
    $insertedId = null; // Initialize variable to avoid "undefined variable" errors

    // Determine if headings should be applied based on keywords in the prompt template
    $keywords = ['information', 'info', 'article', 'articles', 'post', 'something', 'tell', 'tell me', 'artical', 'arrticle', 'poost', 'say', 'illuminate', 'shed'];
    $applyHeadings = false;
    foreach ($keywords as $keyword) {
        if (stripos($prompt_template, $keyword) !== false) {
            $applyHeadings = true;
            break;
        }
    }

    // Loop through each exam code
    foreach ($exam_codes as $exam_code) {
        // Trim any extra whitespace for each exam code
        $exam_code = trim($exam_code);

        // Fetch exam details from the database
        $exam = $examModel->where('exam_code', $exam_code)->first();
        if ($exam === null) {    
            $responses[$exam_code] = [
                'error' => 'Could not find data for exam code ' . $exam_code,
                'model' => []
            ];
            continue;
        }

        $certification = $certificationModel->find($exam['certification_ids']);
        if ($certification === null) {
            $responses[$exam_code] = [
                'error' => 'Could not find certification data for exam code ' . $exam_code,
                'model' => []
            ];
            continue;
        }

        $vendor = $vendorModel->find($exam['vendor_id']);
        if ($vendor === null) {
            $responses[$exam_code] = [
                'error' => 'Could not find vendor data for exam code ' . $exam_code,
                'model' => []
            ];
            continue;
        }

        $topics = $examTopicModel->where('exam_code', $exam_code)->findAll();
        $topicsSections = array_map(function($topic) {
            return $topic['description'];
        }, $topics);

        // Process the prompt
        $parsed_prompt = $this->processPrompt(
            $exam_code,
            $prompt_template,
            $exam['name'],
            $exam['exam_shortname'],
            $certification['detail_name'],
            $certification['cert_shortname'],
            $vendor['name'],
            $topicsSections // Pass the array of topics
        );

        // Check if there was an error in processing the prompt
        if (strpos($parsed_prompt, 'Error:') !== false) {
            // Handle the error by skipping the AI generation for this exam code
            $responses[$exam_code] = [
                'error' => $parsed_prompt,
                'model' => []
            ];
        }

        // Call the respective AI models for the parsed prompt
        foreach ($aiModels as $aiModel) {
            $response = '';
            $modelName = ucfirst($aiModel); // Example: 'openai' becomes 'OpenAI'
            try {
                switch ($aiModel) {
                    // Handle AI model requests as needed
                    case 'openai-gpt-3.5-Turbo':
                        $apiKey = '';
                        $response = $this->generateTextOpenAI($parsed_prompt, $apiKey);
                        break;
                    case 'cohere':
                        $apiKey = '';
                        $response = $this->generateTextCohere($parsed_prompt, $apiKey, $exam_code);
                        break;
                    case 'claude-3-Opus':
                        $apiKey = '';
                        $response = $this->generateTextClaudeOpus($parsed_prompt, $apiKey);
                        break;
                    case 'openai-gpt-4o-mini':
                        $apiKey = '';
                        $response = $this->generateTextOpenAIGPT4omini($parsed_prompt, $apiKey);
                        break;
                    case 'claude-3-Haiku':
                        $apiKey = '';
                        $response = $this->(generateTextClaudeHaiku$parsed_prompt, $apiKey);
                        break;
                    case 'claude-3.5-Sonnet':
                        $apiKey = '';
                        $response = $this->generateTextClaudeSonnet($parsed_prompt, $apiKey);
                        break;
                    case 'openai-gpt-4-turbo':
                        $apiKey = '';
                        $response = $this->generateTextOpenAIGPT4turbo($parsed_prompt, $apiKey);
                        break;
                }

                $responses[$exam_code]['model'][$aiModel] = $response;

                // Store the AI model name and its response
                $responseDatetime = date('Y-m-d H:i:s'); // Current date and time

                // Insert data into the table
                $builder = $db->table('responses');

                // Prepare the data to insert
                $data = [
                    'ai_model' => $modelName,
                    'created_at' => $responseDatetime,
                    'prompt' => $parsed_prompt, // Store the actual parsed prompt
                    'response' => $response, // Store the AI generated response
                    'project_name' => $project_name, // Store the project name
                ];
                $builder->insert($data);
                $insertedId = $db->insertID();

            } catch (Exception $e) {
                // Display error message if something goes wrong
                $responses[$exam_code]['model'][$modelName] = "Error: " . $e->getMessage();
            }
        }
    }

    return view('response_view', [
        'insertedId' => $insertedId,
        'responses' => $responses
    ]);
}

The response is being sent to the views as whole. I have to wait for all my responses to be completed then appear on the views all at once.

**

The problem is I want the dynamic responses on my views. The moment an
AiModel that was selected is done with generation it should appear on
the views instead of waiting for all of them.

**

Below is my views code:

    <body>
<div class="container">
<div class="wrapper">
        <!-- Sidebar  -->
        <nav id="sidebar">
            <div class="sidebar-header">
                <h3>AI Prompt Model</h3>
            </div>
            <ul class="list-unstyled components">
                <li class="active">
                    <ul class="collapse list-unstyled" id="homeSubmenu">
                        <li>
                            <a onclick="window.location.href='<?= base_url('dashboard'); ?>'">Go to Dashboard</a>
                        </li>
                        <li>
                            <a onclick="window.location.href='<?= base_url('homepage'); ?>'">Go to Home Page</a>
                        </li>
                    </ul>
                </li>
            </ul>
            </nav>
    <div class="main-content">
        <h1>AI Model Responses</h1>
        <div class="exam-section">
            <button id="compareButton">Compare Selected</button>
            <table>
                <thead>
                <tr>
                    <th>Select</th>
                    <th>Exam Code</th>
                    <th>AI Model</th>
                    <th>Response</th>
                    <th>Action</th> <!-- Add this column -->
                </tr>
                </thead>
                <tbody>
                <?php
                $exam_responses = [];

                foreach ($responses as $exam_code => $data):
                    if (isset($data['model']) && !empty($data['model'])):
                        foreach ($data['model'] as $model => $response):
                            $normalized_model = strtolower($model);

                            if (!isset($exam_responses[$exam_code])) {
                                $exam_responses[$exam_code] = [];
                            }

                            // Ensure the response is a string
                            if (is_array($response)) {
                                // If response is an array, assume it's the first item in the array
                                $response = isset($response['response']) ? $response['response'] : '';
                            }

                            $response = preg_replace('/**(.+?)**/', '<strong>$1</strong>', $response);
                            $response = preg_replace('/^#### (.+)$/m', '<h4>$1</h4>', $response);
                            $response = preg_replace('/^### (.+)$/m', '<h3>$1</h3>', $response);
                            $response = preg_replace('/^## (.+)$/m', '<h2>$1</h2>', $response);
                            if (!isset($exam_responses[$exam_code][$normalized_model])) {
                                $exam_responses[$exam_code][$normalized_model] = $response;
                            }
                        endforeach;
                    endif;
                endforeach;
                ?>

                <?php foreach ($exam_responses as $exam_code => $models):
                    foreach ($models as $model => $response):
                        $decoded_response = is_string($response) ? htmlspecialchars_decode($response) : '';
                        ?>
                        <tr>
                            <td>
                                <input type="checkbox" class="response-checkbox"
                                       data-exam-code="<?= htmlspecialchars($exam_code) ?>"
                                       data-response="<?= htmlspecialchars($decoded_response) ?>"
                                       data-model="<?= htmlspecialchars(ucwords($model)) ?>">
                            </td>
                            <td><?= htmlspecialchars($exam_code) ?></td>
                            <td><?= htmlspecialchars(ucwords($model)) ?></td>
                            <td>
                                <button class="response-btn" onclick="toggleResponse(this)">View Response</button>
                                <div class="response-box"><?= htmlspecialchars_decode($decoded_response) ?></div>
                            </td>
                            <td>
                                <button class="delete-btn" data-id="<?= htmlspecialchars($insertedId) ?>"
                                        onclick="deleteRow(this)">Delete
                                </button>
                            </td>
                        </tr>
                    <?php
                    endforeach;
                endforeach;
                ?>
                </tbody>
            </table>
        </div>
        <a href="<?= base_url('optioncontroller'); ?>">Go back</a>
    </div>
</div>

<!-- Copy Notification -->
<div class="copy-notification" id="copyNotification">Response copied to clipboard</div>

<!-- Compare Modal -->
<div id="compareModal" class="modal">
    <div class="modal-content">
        <h2>Compare Responses</h2>
        <div id="compareResults"></div>
    </div>
</div>

Any help would be appreciated!

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật