How to submit a form and display the content from database to the Placeholder component in filament

I have a form, when i submit the form, it dispatches an event, which sends an external api request and then stores the response in the database. I have created an endpoint that can be used to check if the response has been stored in the database. I would like to use the Placeholder component to poll this endpoint, and display the content, without page refresh. See the image bellow. This is the form image

I am new to Filament, what is the possible solution to this?

How to make a custom function called whenever a method of the PDO class is invoked

I am attempting to hook into the functions within the PDO class.

I declared the zend_execute_internal function and hooked it by setting the address of my custom function, but in the code of New Relic or Datadog, it seems they use zend_hash_str_find_ptr to perform the operation within the PHP_MINIT_FUNCTION.

However, I couldn’t figure out exactly how they are hooking the functions. I’ve spent a month searching through a vast amount of materials, but none of the explanations worked as described.

How can I make my function execute first and then execute the original function?

Or is there a way to use symbols like in C..?

tried many approaches, but the most promising code was the one below. However, the result of zend_hash_str_find_ptr always returned NULL no matter where it was executed.

I want to create a feature that collects transactions performed by the user through PDO and displays them as statistics, unlike a custom class.

zend_class_entry *ce = zend_hash_str_find_ptr(CG(class_table), "PDO", sizeof("PDO")-1);
if (ce != NULL) {
    original = zend_hash_str_find_ptr(&ce->function_table, "exec", sizeof("exec")-1);

    if (original != NULL) {
        original_handler_pdo_exec = original->internal_function.handler;
        original->internal_function.handler = my_overwrite_pdo_exec;
    }
}

How to Pass Parameters to the handle() Function in Laravel Artisan Commands?

I am creating a custom Artisan command in Laravel, and I need to pass parameters to the handle() function. However, I’m not sure how to define and access these parameters when running the command.

Here’s what I have so far:

class UpdatePlacesImages extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:update-places-images';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Fetch places data(specially images) from Places API and save it in the goog_data field';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        /* We are updating google_data field by using two separate functions 
        1: updatePlacesImages()
            Updating ""google_data"" field using ""place_id"" for all places ""Expect Lounges"" because Lounges places
            are stored in table name ""lounges"" and DB name ""newairport"" while the remaining all places are 
            saved in table name ""places"" and DB name ""airport_remote  
            
        2: updateLoungesImages()
            Updating ""google_data"" field using ""place_id""  only for lounges place
        */

        $this->updatePlacesImages();
        $this->updateLoungesImages();
    }
}

What I Want:

1: I want to pass a parameter places or lounges.

Example:

1: php artisan app:update-places-images places

or

2: php artisan app:update-places-images lounges

Error: SyntaxError: Unexpected non-whitespace character after JSON at position 52 (line 1 column 53)

I’m experiencing a JSON parsing error with the message:

‘SyntaxError: Unexpected non-whitespace character after JSON at
position 52 (line 1 column 53)’.

Could you help me understand what might be causing this? I suspect there might be some unexpected characters or output before the JSON response.

this is my code:

function bayar() {
    const tagihan = <?php echo json_encode($tagihan_belum_dibayar[0] ?? null) ?>;
    
    if (!tagihan) {
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'Tidak ada tagihan yang perlu dibayar'
        });
        return;
    }

    Swal.fire({
        title: 'Memproses Pembayaran',
        text: 'Mohon tunggu...',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });

    fetch('./process_payment.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        },
        body: JSON.stringify({
            total_tagihan: parseFloat(tagihan.total_tagihan)
        })
    })
    .then(response => {
        // Pastikan response dalam format JSON
        const contentType = response.headers.get('content-type');
        if (!contentType || !contentType.includes('application/json')) {
            throw new Error('Bukan respon JSON');
        }
        return response.json();
    })
    .then(data => {
        Swal.close();
        if (data.status === 'success') {
            $('#orderIdInput').val(data.order_id);
            $('#jumlahPembayaranInput').val(new Intl.NumberFormat('id-ID', {
                style: 'currency',
                currency: 'IDR'
            }).format(data.total_bayar));
            
            $('#modalPembayaranBaru').modal('hide');
            $('#modalUploadBukti').modal('show');
        } else {
            throw new Error(data.message || 'Terjadi kesalahan');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        Swal.fire({
            icon: 'error',
            title: 'Gagal',
            text: error.message || 'Terjadi kesalahan dalam pemrosesan'
        });
    });
}

// Update form submission handler
document.getElementById('uploadBuktiForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    
    Swal.fire({
        title: 'Mengupload Bukti Pembayaran',
        text: 'Mohon tunggu...',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });

    fetch('', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        Swal.fire({
            icon: 'success',
            title: 'Berhasil',
            text: 'Bukti pembayaran berhasil diupload'
        }).then(() => {
            window.location.reload();
        });
    })
    .catch(error => {
        Swal.fire({
            icon: 'error',
            title: 'Gagal',
            text: 'Gagal mengupload bukti pembayaran'
        });
    });
});

Can you advise on how to troubleshoot this issue and ensure a clean JSON response?

“I tried to send a JSON request from the client-side using JavaScript’s fetch API to a PHP backend. I was expecting a clean JSON response that would be parsed without any errors.

Specifically:

  • I sent a POST request to process a payment

  • The server-side PHP script was supposed to generate a JSON response

  • Instead, I received this parsing error at position 52

What I expected was a response like:

{
  "status": "success",
  "order_id": "123456",
  "total_bayar": 500000
}

But the error suggests something unexpected is being sent before or within the JSON data.

I’ve already tried:

  • Checking server-side PHP for any extra output

  • Using ob_clean() to clear output buffer

  • Verifying Content-Type headers

  • Ensuring no error messages are printed

Could you help me identify what might be causing these unexpected characters?

How do I print multiple tickets on one sheet?

I am trying to print tickets for a concert.
At the moment I can print each ticket on a separate sheet of paper. But I would like to be able to print each ticket, with a small gap after each one, on as fewer pages as possible.

Here is the code I have:

    for($i = 0; $i < 5; $i++){
        $pdf->AddPage();

        // background
        $pdf->SetAlpha($alpha);
        $pdf->Image('../img/banners/'.$row['banner'], 10, 10, 0, 107);
        // draw border around image
        $pdf->SetAlpha(1);
        $pdf->Cell(0,107,'',1,1, 'C');

        // logo
        $pdf->Image('../img/logo/logo-trans-bg.png', 20, 20, 20, 20);

        // name
        $pdf->SetFont('Courier','I',12);
        $pdf->Text(105 - ($pdf->GetStringWidth($row['name']) / 2), 32, $row['name']);

        // price
        $pdf->SetFont('Courier','',12);
        $price1 = "£".$row['t1_price'];
        $pdf->Text(175 - ($pdf->GetStringWidth($price1) / 2), 32, $price1);

        // date
        $pdf->SetFont('Courier','B',12);
        $pdf->Text(155 - ($pdf->GetStringWidth($date) / 2), 105, $date);

        // web address
        $pdf->SetFont('Courier','BI',12);
        $pdf->Text(40 - ($pdf->GetStringWidth('dwhsociety.co.uk') / 2), 105, 'dwhsociety.co.uk');

        // concert title
        $pdf->SetFont('Courier','B',16);
        $pdf->Text(105 - ($pdf->GetStringWidth($row['title']) / 2), 60, $row['title']);

        // Adult
        if($row['type_1'] != '0'){
            $adult = "1 ticket ".$row['t1_label'];
            $pdf->SetFont('Courier','',12);
            $pdf->Text(105 - ($pdf->GetStringWidth($adult) / 2), 67, $adult);
        }
    
        // venue
        $pdf->SetFont('Courier','',12);
        $pdf->Text(105 - ($pdf->GetStringWidth($row['venue']) / 2), 77, $row['venue']);
    }

This of course creates a new page on every loop, which I don’t want.

Any help greatly appreciated.

Problem with the modal not appearing, only backdrop appears [closed]

I’m still a novice programmer. This is my modal; I’ve tried a lot of different approaches, but it simply shows the background. I tried manually on the console as well, but it didn’t work. This modal aim is to update the customer’s information.

<!-- Modal Edit Bahagian -->
            <div class="modal fade" id="modal-edit-bahagian" tabindex="-1" role="dialog">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                            <h4 class="modal-title">Edit Bahagian</h4>
                        </div>
                        <div class="modal-body">
                            <form id="formEditBahagian" method="post">
                                <input type="hidden" id="nama_pemohon" name="nama_pemohon">
                                
                                <div class="form-group">
                                    <label for="edit-kategori-permohon" style="font-weight: bold;">Kategori Pemohon</label>
                                    <select id="edit-kategori-permohon" name="edit-kategori-permohon" required="required" class="form-control">
                                        <option value="">- Sila Pilih -</option>
                                        <option value="Jabatan Negeri">Jabatan Negeri</option>
                                        <option value="Jabatan Persekutuan">Jabatan Perseketuan</option>
                                        <option value="Sekolah-sekolah">Sekolah-sekolah</option>
                                        <option value="Swasta">Swasta</option>
                                        <option value="NGO">NGO</option>
                                    </select>
                                </div>

                                <div class="form-group">
                                    <div class="row">
                                        <div class="col-md-6">                  
                                            <label for="edit-gelaran-ketua-jabatan">Gelaran Ketua Jabatan</label>                       
                                            <input class="form-control" type="text" id="edit-gelaran-ketua-jabatan" name="edit-gelaran-ketua-jabatan" required>
                                            <small id="edit-gelaranError" style="display:none; color:red;"></small>
                                        </div>
                                        <div class="col-md-6">                  
                                            <label for="edit-agensi">Agensi</label>                     
                                            <input class="form-control" type="text" id="edit-agensi" name="edit-agensi" required>
                                            <small id="edit-agensiError" style="display:none; color:red;"></small>
                                        </div>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <div class="row">
                                        <div class="col-md-6">                  
                                            <label for="edit-bahagian">Bahagian</label>                     
                                            <input class="form-control" type="text" id="edit-bahagian" name="edit-bahagian" required>
                                            <small id="edit-bahagianError" style="display:none; color:red;"></small>
                                        </div>
                                        <div class="col-md-6">                  
                                            <label for="edit-nama-ketua-jabatan">Nama Ketua Jabatan</label>                     
                                            <input class="form-control" type="text" id="edit-nama-ketua-jabatan" name="edit-nama-ketua-jabatan" required>
                                            <small id="edit-namaketuaError" style="display:none; color:red;"></small>
                                        </div>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label for="edit-alamat">Alamat Penuh</label>
                                    <textarea id="edit-alamat" name="edit-alamat" class="form-control" rows="3" required></textarea>
                                </div>

                                <div class="form-group">
                                    <label for="edit-nama-pemohon">Nama Pemohon</label>                     
                                    <input class="form-control" type="text" id="edit-nama-pemohon" name="edit-nama-pemohon" required>
                                    <small id="edit-namapemohonError" style="display:none; color:red;"></small>
                                </div>

                                <div class="form-group">
                                    <label for="edit-jawatan-pemohon">Jawatan Pemohon</label>                       
                                    <input class="form-control" type="text" id="edit-jawatan-pemohon" name="edit-jawatan-pemohon" required>
                                    <small id="edit-jawatanError" style="display:none; color:red;"></small>
                                </div>

                                <div class="form-group">
                                    <div class="row">
                                        <div class="col-md-6">                  
                                            <label for="edit-tel-pejabat">No. Telefon Pejabat</label>
                                            <small style="font-size:13px; color: blue; font-style: italic;">*(Format: 03-61365652)</small>
                                            <input class="form-control" type="tel" id="edit-tel-pejabat" name="edit-tel-pejabat" required>
                                            <small id="edit-telpejabatError" style="display:none; color:red;"></small>
                                        </div>
                                        <div class="col-md-6">                  
                                            <label for="edit-tel-pengguna">No. Telefon Bimbit</label>
                                            <small style="font-size:13px; color: blue; font-style: italic;">*(Format: 012-70442695)</small>
                                            <input class="form-control" type="tel" id="edit-tel-pengguna" name="edit-tel-pengguna" required>
                                            <small id="edit-telpengunaError" style="display:none; color:red;"></small>
                                        </div>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label for="edit-email">Email</label>
                                    <small style="font-size:13px; color: blue; font-style: italic;">*(Format: [email protected])</small>
                                    <input class="form-control" type="email" id="edit-email" name="edit-email" required>
                                    <small id="edit-emailError" style="display:none; color:red;"></small>
                                </div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Tutup</button>
                            <button type="submit" form="formEditBahagian" class="btn btn-primary">Simpan</button>
                        </div>
                    </div>
                </div>
            </div>

Below here is the javascript that makes the modal appears but it didn’t. Can you guys please check the problem here. I think the problem lies on how i did the javascript.

<script>
                        // Log out functionality
                        $("#sign-out").click(function() {
                            $.ajax({
                                url: "proc_files/proc-logout.php",
                                success: function(result) {
                                    window.location.href = '../../';
                                }
                            });
                        });

                        $(document).ready(function() {
                            
                            // Initialize DataTable
                            $('#tbl_bahagian_selenggara').DataTable();
                            
                            // Debug click handler
                            $(document).on('click', '[onclick^="papar_tindakan_edit_bahagian"]', function() {
                                console.log('Edit button clicked');
                            });
                        });

                        function papar_tindakan_edit_bahagian(nama_pemohon) {
                            console.log('Function called with nama_pemohon:', nama_pemohon);
                            
                            // First show the modal
                            $('#modal-edit-bahagian').modal({
                                backdrop: 'static',
                                keyboard: false,
                                show: true
                            });
                            
                            // Then fetch the data
                            $.ajax({
                                url: 'bahagian_details.php',
                                type: 'POST',
                                data: { nama_pemohon: nama_pemohon },
                                dataType: 'json',
                                success: function(data) {
                                    if (data.error) {
                                        alert('Error: ' + data.error);
                                        return;
                                    }
                                    
                                    // Populate the form fields
                                    $('#nama_pemohon').val(data.nama_pemohon);
                                    $('#edit-kategori-permohon').val(data.kategori_permohon);
                                    $('#edit-bahagian').val(data.bahagian);
                                    $('#edit-gelaran-ketua-jabatan').val(data.gelaran_ketua_jabatan);
                                    $('#edit-agensi').val(data.agensi);
                                    $('#edit-nama-ketua-jabatan').val(data.nama_ketua_jabatan);
                                    $('#edit-alamat').val(data.alamat_pengguna);
                                    $('#edit-nama-pemohon').val(data.nama_pemohon);
                                    $('#edit-nokp-pemohon').val(data.nokp_pemohon);
                                    $('#edit-jawatan-pemohon').val(data.jawatan_pemohon);
                                    $('#edit-tel-pejabat').val(data.tel_pejabat);
                                    $('#edit-tel-pengguna').val(data.tel_pengguna);
                                    $('#edit-no-faks').val(data.no_faks);
                                    $('#edit-email').val(data.email_pengguna);
                                },
                                error: function(xhr, status, error) {
                                    console.log('XHR:', xhr.responseText);
                                    console.log('Status:', status);
                                    console.log('Error:', error);
                                    alert('Error fetching details. Please check the console for more information.');
                                }
                            });
                        }

                        

                        function tambah_tempahan(x) {
                            $("#modal-tambah-tempahan").modal('show');
                        }

                        
                        // Form submission handling
                        document.getElementById('formTempahan').onsubmit = function(event) {
                            event.preventDefault();

                            // Reset all error messages
                            resetErrorMessage('gelaranError');
                            resetErrorMessage('agensiError');
                            resetErrorMessage('namaketuaError');
                            resetErrorMessage('namapermohonError');
                            resetErrorMessage('kataError');
                            resetErrorMessage('kpError');
                            resetErrorMessage('jawatanpemohonError');
                            resetErrorMessage('telbimbitError');
                            resetErrorMessage('telpejabatError');
                            resetErrorMessage('emailError');
                            resetErrorMessage('faksError');

                            let hasError = false;

                            // Password validation
                            const password = document.getElementById('kata-laluan').value;
                            const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*d)(?=.*[W_]).{12,20}$/;

                            if (!password || !passwordRegex.test(password)) {
                                showError('kataError', '*Katalaluan mesti mengandungi sekurang-kurangnya 1 huruf besar, 1 huruf kecil, 1 nombor, 1 simbol dan panjang 12-20 karakter!');
                                hasError = true;
                            }

                            // Validation for text-only fields (no numbers)
                            const textOnlyFields = [
                                { id: 'gelaran-ketua-jabatan', error: 'gelaranError', label: 'Gelaran Ketua Jabatan' },
                                { id: 'agensi', error: 'agensiError', label: 'Agensi' },
                                { id: 'nama-ketua-jabatan', error: 'namaketuaError', label: 'Nama Ketua Jabatan' },
                                { id: 'bahagian', error: 'bahagianError', label: 'Bahagian' }
                            ];

                            const textOnlyRegex = /^[a-zA-Zs-.'()]+$/;

                            textOnlyFields.forEach(field => {
                                const input = document.getElementById(field.id);
                                if (input) {
                                    const value = input.value.trim();
                                    if (!value || !textOnlyRegex.test(value)) {
                                        showError(field.error, `*${field.label} hanya boleh mengandungi huruf sahaja!`);
                                        hasError = true;
                                    }
                                }
                            });

                            // Kad Pengenalan validation
                            const nokppermohon = document.getElementById('no-nokp-permohon').value.trim();
                            const nokppermohonRegex = /^d{12}$/; // Ensure exactly 12 digits

                            if (!nokppermohon || !nokppermohonRegex.test(nokppermohon)) {
                                showError('kpError', '*Nombor kad pengenalan permohon hanya mengandungi angka dan 12 digit sahaja!');
                                hasError = true;
                            }

                            // Nama validation
                            const namapermohon = document.getElementById('nama-permohon').value;
                            const namapermohonRegex = /^[a-zA-Zs]*$/;

                            if (!namapermohon || !namapermohonRegex.test(namapermohon)) {
                                showError('namapermohonError', '*Nama permohon hanya boleh mengandungi huruf sahaja!');
                                hasError = true;
                            }

                            // Email validation
                            const email = document.getElementById('email').value;
                            const emailRegex = /^[^s@]+@[^s@]+.[^s@]+$/;

                            if (!email || !emailRegex.test(email)) {
                                showError('emailError', '*Format email yang dimasukkan adalah salah!');
                                hasError = true;
                            }

                            // Jawatan validation
                            const jawatanpermohon = document.getElementById('jawatan-permohon').value;
                            const jawatanpermohonRegex = /^[a-zA-Zs]*$/;

                            if (!jawatanpermohon || !jawatanpermohonRegex.test(jawatanpermohon)) {
                                showError('jawatanpemohonError', '*Jawatan hanya boleh mengandungi huruf sahaja!');
                                hasError = true;
                            }

                            // Phone number validation (Mobile)
                            const telefonbimbit = document.getElementById('no-telefonbim').value.trim();
                            const telefonbimbitRegex = /^d{3}-d{7}$/;

                            if (!telefonbimbit || !telefonbimbitRegex.test(telefonbimbit)) {
                                showError('telbimbitError', '*Format telefon bimbit tidak sah. Gunakan format: 012-7044269');
                                hasError = true;
                            }

                            // Phone number validation (Office)
                            const telefonpej = document.getElementById('no-telefonpej').value.trim();
                            const telefonpejRegex = /^d{3}-d{7}$/;

                            if (!telefonpej || !telefonpejRegex.test(telefonpej)) {
                                showError('telpejabatError', '*Format telefon pejabat tidak sah. Gunakan format: 012-7044269');
                                hasError = true;
                            }

                            // Faks validation
                            const nofaks = document.getElementById('no-faksimili').value.trim();
                            const nofaksRegex = /^d{2}-d{7}$/;

                            if (!nofaks || !nofaksRegex.test(nofaks)) {
                                showError('faksError', '*Format faksimili tidak sah. Gunakan format: 02-7044269');
                                hasError = true;
                            }

                            
                            // If validation passes, submit form via AJAX
                            if (!hasError) {
                                // Show confirmation modal
                                $('#pengesahan-simpan-tindakan-kosong-tarikh').modal('show');
                                
                                // Handle confirmation button click
                                $("#btnSetuju").off('click').on('click', function() {
                                    

                                    // Show loading overlay
                                    $.LoadingOverlay("show");

                                    // Get form data
                                    const formData = new FormData(document.getElementById('formTempahan'));

                                    // Submit form via AJAX
                                    $.ajax({
                                        url: 'Php-files-admin/insert_bahagian_pendaftaran.php',
                                        type: 'POST',
                                        data: formData,
                                        processData: false,
                                        contentType: false,
                                        dataType: 'json',
                                        success: function(response) {
                                            if (response.success) {
                                                // Hide confirmation modal
                                                $('#pengesahan-simpan-tindakan-kosong-tarikh').modal('hide');
                                                // Show success message
                                                $('#msg-berjaya').modal('show');
                                                // Close form modal
                                                $('#modal-tambah-tempahan').modal('hide');
                                                // Reload page after short delay
                                                setTimeout(function() {
                                                    location.reload();
                                                }, 1500);
                                            } else {
                                                // Hide confirmation modal
                                                $('#pengesahan-simpan-tindakan-kosong-tarikh').modal('hide');
                                                // Show error message
                                                $('#text-tidak-berjaya').text(response.message || 'Maklumat tidak berjaya disimpan.');
                                                $('#msg-tidak-berjaya').modal('show');
                                            }
                                        },
                                        error: function(xhr, status, error) {
                                            // Hide confirmation modal
                                            $('#pengesahan-simpan-tindakan-kosong-tarikh').modal('hide');
                                            // Show error message
                                            $('#text-tidak-berjaya').text('Error: ' + error);
                                            $('#msg-tidak-berjaya').modal('show');
                                        },
                                        complete: function() {
                                            // Hide loading overlay
                                            $.LoadingOverlay("hide");
                                        }
                                    });
                                });

                                // Handle cancel button click
                                $("#btnTidakSetuju").off('click').on('click', function() {
                                    $('#pengesahan-simpan-tindakan-kosong-tarikh').modal('hide');
                                });
                            }
                        };

                        // Character counter for textarea
                        const alamatTextarea = document.getElementById('alamat');
                        const charCount = document.getElementById('charCount');
                        const maxLength = 150;

                        alamatTextarea.addEventListener('input', function() {
                            const currentLength = this.value.length;
                            const remaining = maxLength - currentLength;

                            charCount.textContent = remaining + ' characters remaining'

                            if (remaining <= 0) {
                                this.value = this.value.substring(0, maxLength);
                                charCount.textContent = '0 characters remaining';
                            }
                        });

                        // Helper function to reset error messages
                        function resetErrorMessage(elementId) {
                            const element = document.getElementById(elementId);
                            element.textContent = '';
                            element.style.display = 'none';
                        }

                        // Helper function to display error messages
                        function showError(elementId, message) {
                            const element = document.getElementById(elementId);
                            element.textContent = message;
                            element.style.display = 'block';
                        }

                          // Get the input elements
                            const nokpInput = document.getElementById('no-nokp-permohon');
                            const idPenggunaInput = document.getElementById('id-pengguna');

                            // Add event listener for input changes
                            nokpInput.addEventListener('input', function() {
                            // Copy the value from nokp to id pengguna
                            idPenggunaInput.value = this.value;

                            // Disable the id pengguna input
                            idPenggunaInput.readOnly = true;
                            });

                            // Initialize on page load
                            window.addEventListener('load', function() {
                            // Disable the id pengguna input if nokp has a value
                            if (nokpInput.value) {
                                idPenggunaInput.value = nokpInput.value;
                                idPenggunaInput.readOnly = true;
                            }
                            });

                    </script>

And down here is the php files

<?php
session_start();
include 'security/connection.php'; 

header('Content-Type: application/json');

if (!isset($_POST['nama_pemohon'])) {
    echo json_encode(['error' => 'nama_pemohon is required']);
    exit;
}

$nama_pemohon = $_POST['nama_pemohon'];

// Add error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Check connection first
if (!$conn) {
    echo json_encode(['error' => 'Database connection failed: ' . mysqli_connect_error()]);
    exit;
}

// SQL query to select data
$sql = "SELECT 
    kategori_permohon, 
    bahagian, 
    gelaran_ketua_jabatan, 
    agensi, 
    nama_ketua_jabatan, 
    alamat_pengguna, 
    nama_pemohon, 
    nokp_pemohon, 
    jawatan_pemohon, 
    tel_pejabat, 
    tel_pengguna, 
    no_faks, 
    email_pengguna 
    FROM db_tempahan_pdi.daftar_pengguna 
    WHERE status_bahagian = '1' 
    AND nama_pemohon = ?";

// Use prepared statement
$stmt = mysqli_prepare($conn, $sql);
if (!$stmt) {
    echo json_encode(['error' => 'Query preparation failed: ' . mysqli_error($conn)]);
    exit;
}

// Bind parameters
mysqli_stmt_bind_param($stmt, "s", $nama_pemohon);

// Execute the statement
if (!mysqli_stmt_execute($stmt)) {
    echo json_encode(['error' => 'Query execution failed: ' . mysqli_stmt_error($stmt)]);
    exit;
}

// Get the result
$result = mysqli_stmt_get_result($stmt);
if (!$result) {
    echo json_encode(['error' => 'Failed to get result: ' . mysqli_error($conn)]);
    exit;
}

$row = mysqli_fetch_assoc($result);

if ($row) {
    echo json_encode($row);
} else {
    echo json_encode(['error' => 'No data found for nama_pemohon: ' . $nama_pemohon]);
}

mysqli_stmt_close($stmt);
mysqli_close($conn);
?>

Please help me on solving this issue

Laravel 5.5 Job Queue Not Working In Parallel Despite Having Many Workers

I’m using Laravel 5.5 with the database queue driver to manage jobs, and I have 5 workers running. However, I’ve noticed that the rate at which jobs are processed remains constant at 100 jobs per minute, regardless of the number of workers.

When I tested locally, I found that the workers are processing jobs sequentially. A worker only starts processing a new job once the current one is finished, which eliminates the advantage of having multiple workers.

Previously, I encountered a similar issue when jobs in a custom queue were being processed sequentially. Switching back to the default queue resolved the problem, allowing jobs to be processed in parallel. However, even with all jobs in the default queue now, they are still being processed sequentially.

ENV File

QUEUE_DRIVER = database

Supervisord

[program:laravel_queue]
process_name=%(program_name)s_%(process_num)02d
command=php artisan queue:work --delay=10 --tries=10 --timeout=300
directory=/var/www/html
stdout_logfile=/var/www/html/storage/logs/laravel-queue.log
logfile_maxbytes=0
logfile_backups=0
redirect_stderr=true
autostart=true
numprocs=5
autorestart=true
startretries=86400

Apache CGI dir problem when trying to combining with PHP

I’m rather a rookie to the website development, and I have decided to make a website just for fun.

It’s a windows system.

I downloaded MySQL and have tabels built already.

I downloaded Apache and PHP.

Command php -v returns correct version info in ‘CMD’.

Address ‘http:localhost’ in browser returns correct greeting page that says “It works!!”.

=======================================

Informations above should proof a working Apache and PHP installation.

=======================================

The Apache has been binded with port 127.0.0.1:9000. (checked with netstat -ano | findstr :9000 and telnet 127.0.0.1)

File ‘php.ini’ has beed modified with extensions:

extension=mysqli 
extension=pdo_mysql

File ‘httpd.conf’ has modifications below:

LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so

<FilesMatch .php$>
    SetHandler "proxy:fcgi://127.0.0.1:9000"
</FilesMatch>

A test php file named ‘test.php’ that contains

<?php 
phpinfo(); 
?>

was put in folder ‘htdocs’.

But after I ran php-cgi.exe -b 127.0.0.1:9000 and httpd.exe in different CMD windows and input ‘localhost/test.php’ in my browser, I got error below:

Proxy Error
The proxy server could not handle the request
Reason: DNS lookup failure for: 127.0.0.1:9000d:

I assume the problem is the d: in the end, so that it cannot find the correct path to ‘test.php’

Did someone meet with this kind of problem before or know what is going on?

I would really appreciate your help, thank you !! ;).

How to display percentages (not raw numbers) in a Doughnut chart using Chart.js and PHP?

I’m working on a project where I need to generate a Doughnut chart displaying the percentage distribution of different emotions based on data stored in a CSV file. I’m using PHP to parse the CSV and Chart.js to create the chart. However, I’m currently having two main issues:

The percentages are not showing up, even though I’m calculating them in JavaScript using Chart.js and the chart is properly rendered.
The total percentage adds up to over 100%.
Here’s a breakdown of what I’ve done so far:

PHP part: I’m using PHP to parse the CSV file and count the occurrences of different emotions. I then pass the emotion labels and their counts to JavaScript.
Chart.js part: I’m using the Chart.js datalabels plugin to try to show percentages on the chart.

Here’s my PHP code to read the CSV and count the occurrences of each emotion:

<?php
$data = array_map('str_getcsv', file('data_export.csv'));
array_shift($data);  // Skip header if present

$emotion_map = [
    'Excitement' => 1,
    'Inspiration' => 2,
    'Joy' => 3,
    'Curiosity' => 4,
    'Pride' => 5,
    'Hope' => 6,
    'Stress' => 7,
    'Panic' => 8,
    'Relief' => 9,
    'Confusion' => 10,
    'Boredom' => 11,
    'Disappointment' => 12,
];

$emotion_count = array_fill_keys(array_keys($emotion_map), 0);

foreach ($data as $row) {
    $emotion = trim($row[0]);
    if (isset($emotion_map[$emotion])) {
        $emotion_count[$emotion]++;
    }
}
?>

And here’s my JavaScript code for generating the Doughnut chart:

const doughnutCtx = document.getElementById('emotionDoughnutChart').getContext('2d');

const emotionLabels = <?php echo json_encode(array_keys($emotion_count)); ?>;
const emotionCounts = <?php echo json_encode(array_values($emotion_count)); ?>;

// Calculate the total count
const totalCount = emotionCounts.reduce((sum, count) => sum + count, 0);

const doughnutChart = new Chart(doughnutCtx, {
    type: 'doughnut',
    data: {
        labels: emotionLabels,
        datasets: [{
            label: 'Emotion Distribution',
            data: emotionCounts,
            backgroundColor: [
                '#1E90FF', '#FF7F50', '#FFE4B5', '#8BC34A', '#32CD32', '#4CAF50', '#D3D3D3',
                '#DC143B', '#8BC34A', '#7FFFD4', '#DDA0DD', '#D8BFD8'
            ],
            hoverOffset: 5
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false, 
        plugins: {
            legend: {
                display: true,
                position: 'top',
                labels: { font: { size: 10 } }
            },
            title: { display: true, text: 'Emotion Distribution' },
            datalabels: {
                color: 'white',
                formatter: function(value, context) {
                    let percentage = (value / totalCount * 100).toFixed(2);
                    return `${percentage}%`;  // Display percentage
                },
                font: { weight: 'bold', size: 14 }
            }
        },
        layout: { padding: { top: 10, bottom: 10 } }
    }
});

I have tried sing the chartjs-plugin-datalabels plugin to display the percentage but no luck .

The md5 hashing function in php is processed at different speeds on different servers [closed]

Good afternoon.

I have rented a VPS server and my website is running on it.
To increase the bandwidth, I decided to move to a more powerful server. (the characteristics are shown below)

The old server:
Characteristics of the old server

  • CPU: 4 core

  • RAM: 6GB

  • HDD: 165 GB

The new server:
Characteristics of the new server

  • CPU: 12 core

  • RAM: 24 GB

  • HDD: 295 GB

But as a result, I got that everything works 5 times slower on the new server.

Performed profiling on both servers using xdebug.

As a result of the analysis of the results, it turned out that the md5 function works in 2 ms on the old server, and in 10 ms on the new server.

Since this function is used in the process of localization of the site text into other languages, this feature slows down the loading of all countries by ~ 5 times

Below is the function in which the md5 function is called:

function __($key = ''){
        if(get_session('language')){
            $language = get_session('language');
        }else{
            if(!get_user("language")){
                $code = get_user("language");
                $language = db_get("*", TB_LANGUAGE_CATEGORY, ["code" => $code]);
                if(empty($language)){
                    $language = db_get("*", TB_LANGUAGE_CATEGORY, ["is_default" => 1]);
                }
            }else{
                $language = db_get("*", TB_LANGUAGE_CATEGORY, ["is_default" => 1]);
            }
            
            $language = json_encode($language);
            if(!empty($language)){
                set_session(["language" => $language]);
            }
        }

        if($language){
            $language = is_string($language)?json_decode( $language ):$language;

            if(isset($language->code)){
                $lang_file = WRITEPATH."lang/".$language->code.".json";
                if(file_exists($lang_file)){
                    $data = file_get_contents(WRITEPATH."lang/".$language->code.".json");
                    $data = json_decode($data, 1);
                    if(isset($data['data'])){
                        $data = $data['data'];
                        if($key != "" && isset($data[ md5($key) ])){
                            return $data[ md5($key) ];
                        }
                    }
                }
            }
        }

        return $key;
    }

The old server:

The new server:

QUESTION: The crux of the question is why the function runs 5 times slower on the new server (in 10 ms, versus 2 ms on the old server)

addition: The results in 2ms and 10ms are only for 1 function call. And there are more than 50 such calls when loading a page, which ultimately leads to a delay of 5 seconds for the user.

Ghostscript is not working with imagick error FailedToExecuteCommand

I have PHP Laravel script working with following configuration.

Laragon
Apache httpd-2.4.54-win64-VS16
PHP 8.3
Ghostscript 10.04.0
ImageMagick 7.1.0-18 Q16 x64

When I tried to convert pdf into image using exec command it works.

$pdfPath = $cvFile;
$outputPath = 'd:/temp/test.png';
$gsCommand = "gs -dNOPAUSE -dBATCH -sDEVICE=pngalpha -r144 -sOutputFile="$outputPath" "$pdfPath"";
exec($gsCommand, $output, $returnCode);

But it doesn’t works when I tried to convert pdf using Imagick().

$imagick = new Imagick();
$imagick->readImage($cvFile);

I got this error when I tried the execute the above code on line readImage().

FailedToExecuteCommand `”gs” -sstdout=%stderr -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 “-sDEVICE=pngalpha” -dTextAlphaBits=4 -dGraphicsAlphaBits=4 “-r72x72” -dPrinted=false “-sOutputFile=C:/Users/alish/AppData/Local/Temp/magick-fzsvjp49WgV_dLqdzA-KMiGFzpNpmnvQ%d” “-fC:/Users/alish/AppData/Local/Temp/magick-dC4PEbPqgCO7mlsy_cDaOIWgVTrR6Ixu” “-fC:/Users/alish/AppData/Local/Temp/magick-EJa1tcrtqJ9dcGUOrY2gv7–rqFtZS21″‘ (The system cannot find the file specified. ) @ error/delegate.c/ExternalDelegateCommand/516

Imagick should able to convert pdf into image using Ghostscript.

Get discount on first item only with coupon

I’m using woocommerce coupon. After using the “bcx” coupon code, every category (only just one not) make 50% discount. I want to make that gives customer a 50% discount on the first of each item on the cart. For example, customer buys 2 pcs of product A and 1 pcs of product B. The customer should get first item of product A and the product B the 50% discount. And important, that NOT using coupon code for one specific category). So it doesn’t matter how many pcs of each items you buy, the first one is always on 50% discount on each individual items. How can I solve this?

I tried with differnet plugins and it didn’t work.

Javascript suddenly not working on my WordPress Site [closed]

I am working my WP site with Git and because of that I have a local site, the same but on a Development Stage and again but for the Public and that’s the actual site ofc. Basically what is happening is that suddenly some Peepso (social network plugin) scripts stopped working and now the console tells me that some things are undefined. The thing is that this happens ONLY in the DEV Site, my local and public site are perfect, apart from an unique client that reported having the same issue, all people does not have any problem. Does anybody knows why is this happening or did you have a similar issue? Thanks in advance!
This is the dev site console:
enter image description here

This is the local site console (public site is basically the same) and those ‘left’ errors doesn’t cause problems:
enter image description here

I would like to understand what can cause those kind of problems and get to know how to solve it in the future.

filament via spatie laravel permissions

I’m using filament and spatie laravel permissions for roles(only for roles, it’s not my decision). When I’m trying to make Select in form like this:

Select::make('roles.name')
->relationship('roles', 'name')
->options(RoleType::class)
->required(),

I’m encountering the error:
SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for type bigint: “writer” CONTEXT: unnamed portal parameter $3 = ‘…’ (Connection: pgsql, SQL: insert into “model_has_roles” (“model_id”, “model_type”, “role_id”) values (2, user, writer))
My enum:

enum RoleType: string implements HasLabel
{
    case Writer = 'writer';
    case User = 'user';

    public function getLabel(): ?string
    {
        return __('enums/role_type.' . $this->value);
    }
}

Also I’m using casts in Role model (via enum). I spent like 4 hours to solve this problem, but I can’t solve it. Also, when I’ve asked my mentor(I’m laravel intern) he said that I can’t use getStateUsing, options(list them all) e.t.c
Help me pls
P.S. php 8.3, laravel 11.30, filament 3.2, laravel-permission 6.10

I tried to use chatGPT to solve this problem, but he just used getStateUsing or options that I shouldn’t use.