Using AJAX WordPress Plugin to Change values on a DIV container

I working on a simple plugin that need to make a call and pass the results using AJAX.

Here is my function JS


function courseGradeHistory(student_id) {
  
  // Ensure jQuery is available

  if (typeof jQuery === 'undefined') {
    console.error('jQuery is not defined. Please ensure jQuery is loaded before this script.');
    return;
  }

  // Get the course code and student ID from the input fields
  
    var course_code = document.getElementById("course_code").value;
  var $resultsContainer = $('#studentCourseSchedule');
  var student_id = student_id || document.getElementById("student_id").value;

  console.log("Course Code: " + course_code);
  console.log("Student ID: " + student_id);

  // Validate inputs
  if (!student_id || !course_code) {
    alert("Please provide both Student ID and Course Code.");
    return;
  }

  alert("Loading Course History for Student ID: " + student_id + " and Course Code: " + course_code);

  $resultsContainer.html('<p>Loading Courses...</p>');

  // Make the AJAX request to fetch course grade history
  // Ensure that 'ajaxurl' is defined in your WordPress environment
  $.ajax({
    url: ajaxurl,
    type: 'POST',
    data: {
      action: 'connect_course_history',
      student_id: student_id,
      course_code: course_code,
      numberofdays: 30 // You can adjust this value as needed
      
    },
    success: function(data) {
      $resultsContainer.html(data);
    },
    error: function(xhr, status, error) {
      $resultsContainer.html('<p>Error loading courses. Please try again.</p>');
      console.error('AJAX Error:', status, error);
    }
  });
}

Here is my PHP function

// register the ajax action for authenticated users
add_action(‘wp_ajax_connect_course_history’, ‘connect_course_history’);

// register the ajax action for unauthenticated users
add_action(‘wp_ajax_nopriv_connect_course_history’, ‘connect_course_history’);

function connect_course_history($student_id, $course_code, $numberofdays) {

    global $wpdb;

    $sql = "CALL sp_connect_course_history('$student_id', '$course_code', $numberofdays);";
    $wpdb->query($sql);
    $course_history = $wpdb->get_results($sql, ARRAY_A);

    if (empty($course_history)) {
        return "<p>No course history found for this student.</p>";
    }

    // Prepare the output
    $output = "<table><tr><th>DATE</th><th>Grade</th></tr>";

    foreach ($course_history as $course) {
        $output .= "<tr>";
        $output .= "<td>{$course['DATE']}</td>";
        $output .= "<td>{$course['grade']}</td>";
        $output .= "</tr>";
    }


    $output .= "</table>";


return $output;
}

This all I see in Developer Console

    error   @   myplugin_script.js:63
c   @   jquery.min.js?ver=3.7.1:2
fireWith    @   jquery.min.js?ver=3.7.1:2
l   @   jquery.min.js?ver=3.7.1:2
(anonymous) @   jquery.min.js?ver=3.7.1:2
XMLHttpRequest.send     
send    @   jquery.min.js?ver=3.7.1:2
ajax    @   jquery.min.js?ver=3.7.1:2
(anonymous) @   jquery-migrate.min.js?ver=3.4.1:2
e.<computed>    @   jquery-migrate.min.js?ver=3.4.1:2
courseGradeHistory  @   myplugin_script.js:48
onchange    @   ?page_id=1238&student_id=954894:516
handleMouseUp_  @   unknown

I expect the results from the call to update resultsContainer.

Some properties missing when converting object to JSON using JSON.stringify [closed]

I have a JavaScript object that I want to convert to JSON using JSON.stringify. However, the conversion is incomplete, and some parts of the object are not included in the JSON output. In the below example, the responses property appears empty in the JSON string, even though console.log shows the object correctly with all its properties and the code directly set a value to it. The object is not cycled as you can see.

const obj = {};
obj[
  "https://stexmmt.mathhub.info/:sTeX?a=courses/FAU/SMAI/problems&p=math/prob&d=find-mv&l=en&e=problem"
] = {
  responses: [],
  uri: "https://stexmmt.mathhub.info/:sTeX?a=courses/FAU/SMAI/problems&p=math/prob&d=find-mv&l=en&e=problem",
};
obj[
  "https://mathhub.info?a=courses/Jacobs/GenCS/problems&p=dmath/prob&d=hair-color-ind&l=en&e=problem"
] = {
  responses: [],
  uri: "https://mathhub.info?a=courses/Jacobs/GenCS/problems&p=dmath/prob&d=hair-color-ind&l=en&e=problem",
};
obj[
  "https://mathhub.info?a=courses/Jacobs/GenCS/problems&p=dmath/prob&d=hair-color-ind&l=en&e=problem"
].responses[
  "https://mathhub.info?a=courses/Jacobs/GenCS/problems&p=dmath/prob&d=hair-color-ind&l=en&e=problem"
] = "dssas";
obj[
  "https://stexmmt.mathhub.info/:sTeX?a=courses/FAU/SMAI/problems&p=math/prob&d=find-mv&l=en&e=problem"
].responses[
  "https://stexmmt.mathhub.info/:sTeX?a=courses/FAU/SMAI/problems&p=math/prob&d=find-mv&l=en&e=problem/problem_5"
] = "test for";
console.log(obj);
console.log(JSON.stringify(obj));

The output:

The screenshot from output of deno in my PC

I expect the output of JSON.stringify contains all of obj data.

I tried on Deno 2.2.11 and Node v22.15.0 on Windows machine.

What could be causing this issue, and how can I ensure the entire object is properly converted to JSON? Is there a specific configuration for JSON.stringify that I need to use, or could the issue be related to the structure of my object?

How to make TypeScript raise error on impossible conditions?

function detonateBomb(): boolean {
    return false;
}

if (detonateBomb() == null) {
    console.log("Safe! Everyone is alive!");
} else {
    console.log("Boooom! Everyone killed! Typescript is Literally NOT SAFE");
}

During migration 2.0, detonateBomb() now returns a boolean instead of a detonationReason.
The developer replaced the return type from String to :boolean and trusted TypeScript will keep everyone safe.

But no, the bomb exploded. Everyone died.

Because TypeScript did not raise an error if (detonateBomb() == null) { here. This can never be null or undefined, hence likely a bug.

Is there a compiler flag that fixes this?

File upload error – unable to create a temporary file. PHP/HERD/LARAVEL

I’m using the following stack:

  • Laravel Herd
  • Laravel v12.0
  • PHP v8.2.28
  • maatwebsite/excel v3.1 (Laravel Excel)
  • Postman
  • Windows 10 OS

What I’m Trying to Do

I want to send a POST request containing an Excel file (.xlsx). This file should then be processed using the maatwebsite/excel package to create new records based on its contents.

The Problem

When I send the POST request using Postman with form-data containing the Excel file, I get this error:

Warning: File upload error - unable to create a temporary file in Unknown on line 0

Here’s a screenshot for more details:
error screnshoot

Here’s my code

routesapi.php

Route::controller(AlumniController::class)->group(function () {
    ...
    Route::post('/alumnis/import', 'importExcel'); // this is the endpoint for import excel
});

appHttpControllersAlumniController.php

use IlluminateHttpRequest;
use AppImportsAlumnisImport;
use MaatwebsiteExcelFacadesExcel;

class AlumniController extends Controller
{
    ...

    public function importExcel()
    {
        try {
            Excel::import(new AlumnisImport, request()->file('alumni_excel'));
        } catch (Throwable $th) {
            dd($th);
        }
    }
}
appImportsAlumnisImport.php

use AppModelsAlumni;
use AppModelsJurusan;
use MaatwebsiteExcelConcernsToModel;

class AlumnisImport implements ToModel
{
    /**
     * @param array $row
     *
     * @return IlluminateDatabaseEloquentModel|null
     */
    public function model(array $row)
    {
        $jurusan = Jurusan::firstOrCreate(
            ['nama' => $row['nama_jurusan']],
            ['nama' => $row['nama_jurusan']]
        );

        return new Alumni([
            'nama' => $row['nama'],
            'tgl_lahir' => $row['tgl_lahir'],
            'tahun_mulai' => $row['tahun_mulai'],
            'tahun_lulus' => $row['tahun_lulus'],
            'no_tlp' => $row['no_tlp'],
            'email' => $row['email'],
            'password' => isset($row['password']) ? $row['password'] : null,
            'alamat' => $row['alamat'],
            'tempat_kerja' => $row['tempat_kerja'] ?? null,
            'jabatan_kerja' => $row['jabatan_kerja'] ?? null,
            'tempat_kuliah' => $row['tempat_kuliah'] ?? null,
            'prodi_kuliah' => $row['prodi_kuliah'] ?? null,
            'kesesuaian_kerja' => isset($row['kesesuaian_kerja']) ? filter_var($row['kesesuaian_kerja'], FILTER_VALIDATE_BOOLEAN) : null,
            'kesesuaian_kuliah' => isset($row['kesesuaian_kuliah']) ? filter_var($row['kesesuaian_kuliah'], FILTER_VALIDATE_BOOLEAN) : null,
            'photo' => $row['photo'] ?? null,
            'jurusan_id' => $jurusan->id,
        ]);
    }
}

Need Help

Has anyone experienced this issue before? Could it be related to Laravel Herd? I’d really appreciate any help or suggestions to solve this. If you need more info, feel free to leave a comment. Thanks

Laravel 11 Events Firing Multiple Times in Production (Nginx, Azure App Services, PHP 8.3)

I’m encountering an issue where Laravel events are firing multiple times, but only in the production environment.

Environment:

  • Laravel: 11.x
  • PHP: 8.3
  • Web Server: Nginx
  • Hosting: Azure App Services
  • Setup:
    • One App Service runs the main Laravel application
    • A separate App Service handles scheduled tasks (cron)

We are dispatching Laravel events like this:

event(new ApplicationStatusChanged($application));

In production, these events trigger multiple times for a single operation. For example, a single POST request causes the event listener to run 2 times.

Check on direct GET request for Test and getting the same.

This does not happen in the local development environment.

We’re trying to understand:

  • Could this be due to Azure App Service architecture, deployment replication, or Nginx misconfiguration?
    • Why might synchronous Laravel events fire multiple times in a production setup like this?
  • Are there known quirks or debugging tips for this kind of behavior in Laravel 11/PHP 8.3?

We’ve ruled out:

  • Not using ShouldQueue on either the event or the listener — they are all synchronous.
  • Listeners are not making changes that could retrigger the event.
  • Confirmed it’s not job retries or queue-related (we’re not queuing).
  • No duplicate requests are hitting the endpoint.
  • Cache cleared completely (config, route, event, etc.).
  • Stopped the cron App Service entirely — issue still persisted

PHP Fatal Error: Failed opening required file ‘../models/user.class.php’ – Path issue [duplicate]

I’m getting a fatal error when trying to include user.class.php in my Laravel-like project running on XAMPP. The error occurs in auth_api.php (line 4) when it tries to require ../models/user.class.php, but the file exists in the correct location.

PHP Fatal Error: Failed opening required file ‘../models/user.class.php’


<?php

require_once '../configs/db_config.php';
require_once '../models/user.class.php';

class AuthApi {
    function login($data) {
        global $db;
        global $tx;

        if (isset($data["signin"])) {
            $username = trim($data["username"]);
            $password = trim($data["password"]);

            if (empty($username) || empty($password)) {
                echo json_encode(["success" => 0, "message" => "Username and password are required."]);
                return;
            }

            $stmt = $db->prepare("SELECT id, username, role_id, email, password FROM {$tx}users WHERE username = ?");
            $stmt->bind_param("s", $username);
            $stmt->execute();
            $result = $stmt->get_result();
            $u = $result->fetch_object();

            if ($u != null && password_verify($password, $u->password)) {
                $jwt = new JWT();
                $payload = [
                    "id" => $u->id,
                    "username" => $u->username,
                    "role_id" => $u->role_id,
                    "email" => $u->email,
                    "ip" => $this->get_ip(),
                    "iss" => "jwt.server",
                    "aud" => "intels.co"
                ];

                $token = $jwt->generate($payload);

                echo json_encode(["success" => 1, "token" => $token]);
            } else {
                echo json_encode(["success" => 0, "message" => "Invalid username or password."]);
            }
        }
    }
}

Illegal mix of collations on basic SELECT query

I got the following error on a simple select query:

[21-May-2025 20:20:52 America/New_York] PHP Fatal error:  Uncaught PDOException: SQLSTATE[HY000]: General error: 1267 Illegal mix of collations (latin1_swedish_ci,IMPLIC
IT) and (utf8mb4_0900_ai_ci,COERCIBLE) for operation '=' in /home/server/public_html/api/v1/0.50/includes.php:196
Stack trace:
#0 /home/server/public_html/api/v1/0.50/includes.php(196): PDOStatement->execute(Array)
#1 /home/server/public_html/api/v1/0.50/emailVerify.html(86): dbSelect('SELECT * FROM u...', Array)
#2 {main}

Its a table that hosts user emails and verification codes. The user is sent an email and when they click on a link in the email, the link the opens the validation page and in that page it does the following query simple query:

$vCode = $_REQUEST['v'] ;       // IE:  YzFlMGM3M2M1NDIyMzhkNDUxNGFkNGF
$userEmail = $_REQUEST['e'] ;   // IE: [email protected]

$query = "select * from userEmailVerify where user_email=? and code=?" ;
$stmt = $pdo->prepare($query) ;
$result = $stmt->execute([$userEmail,$vCode]) ;

This query is performed dozens of times a day and over the 3 years this table and scripts have been in service this is the first time I have ever seen this error. I manually performed the same SELECT query using the users email and verification code that triggered this error and the query worked fine. The error happened back on the 21st and the same scripts have been processed dozens of times since that error without any further error.

I have read several threads about collation and don’t think any of what I read applies to this situation.

What could have caused this?

Call to undefined function hexToRgb() [closed]

In my script file head.blade.php I have this:

<link rel="apple-touch-icon" sizes="180x180" href="{{asset('favicon/apple-touch-icon.png')}}">
<link rel="icon" type="image/png" sizes="32x32" href="{{asset('favicon/favicon-32x32.png')}}">
<link rel="icon" type="image/png" sizes="16x16" href="{{asset('favicon/favicon-16x16.png')}}">
<link rel="manifest" href="{{asset('site.webmanifest')}}">
@vite(['resources/scss/app.scss', 'resources/js/app.js'])

<style>
    :root {
    @if(config('settings.palette'))
        @foreach(config('attr.colors.'.config('settings.palette')) as $color => $value)
            {{'--color-gray-'.$color.':'.hexToRgb('#'.$value)}};
        @endforeach
    @else
        @foreach(config('attr.colors.zinc') as $color => $value)
            {{'--color-gray-'.$color.':'.hexToRgb('#'.$value)}};
        @endforeach
    @endif
           --color-primary-500: @if(config('settings.color')){{hexToRgb(config('settings.color'))}}@else{{hexToRgb('#8b5cf6')}}@endif;
    }
</style>
{!! config('settings.custom_code') !!}
@if(config('settings.onesignal_id'))
    <script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" defer></script>
    <script>
        window.OneSignal = window.OneSignal || [];
        OneSignal.push(function () {
            OneSignal.init({
                appId: "{{env('ONESIGNAL_APP_ID')}}"
            });
        });

        OneSignal.push(function () {
            OneSignal.showNativePrompt();
        });
    </script>
@endif

And I get the error : Call to undefined function hexToRgb()
Image:

enter image description here

Can be from composer? Or what?

I tried to add a color for it but doesn’t work…

React build error stripe.js not available

I’ve updated stripe package from

@stripe/react-stripe-js: ^1.16.5
@stripe/stripe-js: ^1.54.2

To

@stripe/react-stripe-js: ^3.5.0
@stripe/stripe-js: ^6.1.0

When running yarn build getting error
“Stripe.js not available”

Tried update react from 17 to 18 but still getting this error.
Note: “no errors with old version”

aligned variable declaration (js)

Is there a formatter similar to Prettier that can format Node.js code with aligned variable declarations like this?

const PRICE_BUTTER = 1.00;
const PRICE_MILK=3.00;
const PRICE_EGGS=6.95;

To:

const PRICE_BUTTER = 1.00;
const PRICE_MILK   = 3.00;
const PRICE_EGGS   = 6.95;

Prettier doesn’t have this options

Display text instead of icons when trying to change the look of 2 Font Awesome icons with Google Material Symbols, when adding the same stylesheet

Trying to change the aspect of 2 Font Awasome icons with both sharp Google Material Symbols adding the same stylesheet it gives me a text (the writen name of the icon) instead of the icon itself. To be more precise one icon is displayed correctly while the other appears as text. What I noticed is that the problem occurs only when both icons are sharp.

enter image description here

What I did: first I copy past the stylesheets (how the icons should look) from Google material symbols (for each icon) into my “Code before tag” section.

This is the code for the sharp “delete” icon:

<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+**Sharp**:opsz,wght,FILL,[email protected],100..700,0..1,-50..200&icon_names=delete" />
<style>
.material-symbols-**sharp** {
  font-variation-settings:
  'FILL' 0,
  'wght' 200,
  'GRAD' 0,
  'opsz' 20
}
</style>

This is the code for the sharp “shopping_basket” icon:

<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+**Sharp**:opsz,wght,FILL,[email protected],100..700,0..1,-50..200&icon_names=shopping_basket" />
<style>
.material-symbols-**sharp** {
  font-variation-settings:
  'FILL' 0,
  'wght' 200,
  'GRAD' 0,
  'opsz' 24
}
</style>

After that I put a Javascript code into my custom .js field of the theme do replace the old Font Awasome icons with the new Google Material Symbols. I did like this:

For the “delete” icon:

document.querySelectorAll("i.fa.fa-trash-o").forEach(icon => {
    icon.replaceWith(Object.assign(document.createElement("span"), {
        className: "material-symbols-sharp",
        textContent: "delete"
    }));
});

For the “shopping_basket” icon:

var cartIcon = $(".fa.fa-shopping-bag.fa-fw.icon");
        cartIcon.parent().html("<span class='material-symbols-sharp'>shopping_basket</span>")

The result it’s like in the picture attached above, the “delete” it’s correctly displayed since the “shopping_basket” is not.

What makes the terminal to get stuck when trying to launch a project on my development environment?

Have been working on a nextjs project( 5 days into it to be specific), and everything was working fine. But for now, when I try to launch it on my Dev environment, it just get stuck at “Starting…. I have no idea of what is causing this. Here is a screenshot of The terminal upon running “npm run Dev”.
Your would be greatly appreciated.

I tried uninstalling both node modules and package-lock.json and then installed them afresh but still failed. I even tried launching other projects but also failed, have also tried to use different CLI tools such as bash and the window intergrated terminal, and PowerShell, but got stuck too.

Need help deploying an express api using vercel

im just trying a barebone express app to fix another bigger issue im having:

const express = require('express');
const app = express();

const startupMessage = `--- API/INDEX.JS TOP LEVEL EXECUTION - Deployed: ${new Date().toISOString()} ---`;
console.log(startupMessage);

app.get('/ping', (req, res) => {
    const pingMessage = `--- /ping route in api/index.js HIT - Request at: ${new Date().toISOString()} --- req.originalUrl: ${req.originalUrl}, req.path: ${req.path}`;
    console.log(pingMessage);
    res.status(200).json({
        message: "Pong from api/index.js!",
        originalUrl: req.originalUrl,
        path: req.path,
        startup: startupMessage,
        pingedAt: new Date().toISOString()
    });
});

app.use((req, res, next) => {
  const catchAllMessage = `--- API/INDEX.JS EXPRESS CATCH-ALL: ${req.method} originalUrl: ${req.originalUrl}, path: ${req.path} at ${new Date().toISOString()} ---`;
  console.log(catchAllMessage);
  res.status(404).json({
      error: `Express app in api/index.js 404: Route ${req.method} ${req.originalUrl} (path: ${req.path}) not found.`,
      originalUrl: req.originalUrl,
      path: req.path,
      startup: startupMessage,
      requestedAt: new Date().toISOString()
  });
});

module.exports = app;

and my vercel.json:

{
  "version": 2,
  "builds": [
    {
      "src": "api/index.js",
      "use": "@vercel/node"
    }
  ],
  "rewrites": [

    { "source": "/(.*)", "destination": "/" }
  ]
}

im trying to deploy this onto vercel and it works, when i try the vercel.app/api/index.js i get the catchallmessage but trying the vercel.app/api/ping or api/index/ping gives me the vercel 404, this is really frustrating ive honestly lost all hope. everything works fine locally but of course vercel has to stop everything. if someone knows how to fix this i would be eternally grateful