Why does my JavaScript code receive a “No ‘Access-Control-Allow-Origin’ is present on the requested resource” error, while Postman does not? [duplicate]

Access to XMLHttpRequest at ‘https://firebasestorage.googleapis.com/v0/b/uvp-foundation-e5ece.appspot.com/o?name=startup_docs%2FNYd63qcNGWZB3O4SYime3rXefqh1%2FSorting%20Algo.pdf’ from origin ‘https://asmitsaxena.github.io’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.

POST https://firebasestorage.googleapis.com/v0/b/uvp-foundation-e5ece.appspot.com/o?name=startup_docs%2FNYd63qcNGWZB3O4SYime3rXefqh1%2FSorting%20Algo.pdf net::ERR_FAILED

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?

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

java script text binding for Telemetry value

i do not have any clue about Java Script and programming at all but i am trying to set up a sim racing dash and the software (MOZA PitHouse) gives me some good opportunities, but the results arend’t that great.

The software gives an included Java Script Text Binding command to read out the time left in the session.

Telemetry.get(“v1/gameData/SessionTimeLeft”).value
The Value i get is seconds.

I can choose between different formats, like raw, 0 and also hh:mm:ss:fff
The format i want to have is hh:mm:ss. Sadly it is not available and my hour long search of the www wasn’t helpful.
I tried diffrent Java Script codes i found, but nothing worked. I still added “/60” after “value” to get the minutes, but dind’t found a solution to the format.

I hope that someone has an idea and can help me to get the right format or some solution.

Thanks in advance

enter image description here
Text Binding window

enter image description here
Text Binding window with format

Why is javascript treating ‘ as an apostrophy in a function call?

Thanks for your help with this. I have this table:

    <table>
    <thead>
        <tr>
            <th>Shortcut</th>
            <th>Problem Text</th>
        </tr>
    </thead>
    <tr onclick="editRow('37a2b0ea97224176a8fd950110f2992a', 'RE', 'Rx given to pt&#39;s wife.')">
        <td>RE</td>
        <td>Rx given to pt&#39;s wife.</td>
    </tr>
    <tr onclick="editRow('189dbad1b8e94fa7a36a4c495c61436b', 'RE', 'Rx given to pt&#34;s wife.')">
        <td>RE</td>
        <td>Rx given to pt&#34;s wife.</td>
    </tr>
</table>
<script>
function editRow (id, noo, boo) {alert ("it clicked");}
</script>

When I click on the table row with the HTML entity &#34; in it, the function fires fine, but when I click on the row with the &#39; in it, I get an error in the console of “Uncaught SyntaxError: missing ) after argument list”.

Maybe javascript is treating the &#39; as a literal apostrophe and expecting an end parenthesis? Is there a better way to handle apostrophes in data that is passed to a function?

Thanks for your help.

How to use JavaScript to build a simple new Component in Java for Vaadin

I worked with Vaadin before but could not figure out how to build my own Vaadin components with JavaScript from scratch. Then I did some work with Perl, Mojolicious, JavaScript, HTML and building my HTML+JavaScript components worked like a charm.

Now I am back to Vaadin and JavaScript.
I downloaded a Vaadin+Springboot example project an am trying to add JavaScript to it. I followed a Vaadin tutorial but I keep getting an error.

import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.Tag;
import com.vaadin.flow.component.dependency.JavaScript;
import com.vaadin.flow.component.dependency.JsModule;
import com.vaadin.flow.dom.Element;

//@JavaScript("keyboard-german.js")
//@Tag("cerebrummi_keyboard")
//@JsModule("keyboard-german.js")
public abstract class Keyboard extends Component
{
   private static final long serialVersionUID = -4476014165075742457L;

   
   public Keyboard()
   {
      
   }

   public Keyboard(Element element)
   {
      super(element);
      
   }
}

Each of the tags results in the same error:

error during build: [31m[vite]: Rollup failed to resolve import
“keyboard-german.js” from
“C:/Users/…/generated-flow-imports.js”.
This is most likely unintended because it can break your application
at runtime. If you do want to externalize this module explicitly add
it to ‘build.rollupOptions.external’

Where do I find ‘build.rollupOptions.external’? I googled but could not find an answer.

The JavaScript file is just simple right now:

<script type="module">
export var cerebrummi_keyboard = "This will become the keyboard";
</script>

Need suggestion of zustad state access via dynamic hook in react

i am using zustand to store templates, which is a multi-dimension array, and i have created a function to get value from store in single hit.

Why, i am doing this way is because i am not want to write a state-picks every time i need something from state like.

const template = useStoreName((state) => state.template))

and so on….

so i come up with the solution( as i think this is solution) crate a function which is responsible for accept store ref, and keys which i want to get from store.

here are functions

export function createSelectorHook<
  TStore extends StoreApi<any>,
  TKeys extends keyof ExtractState<TStore>,
>(
  store: TStore,
  keys: TKeys[],
  equalityFn?: <K extends TKeys>(
    a: ExtractState<TStore>[K],
    b: ExtractState<TStore>[K],
  ) => boolean = Object.is,
): Pick<ReturnType<TStore['getState']>, TKeys> {
  const selections = {} as Pick<ReturnType<TStore['getState']>, TKeys>;
  keys.forEach(key => {
    selections[key] = useStoreWithEqualityFn(store, s => s[key], equalityFn);
  });
  return selections;
}

this is responsible for retrun store value in object

i use this in this way like
const {template, count} = createSelectorHook(storeRefrence, ['template', 'count'])

i know i am Violating React Hook rules

Why, i create below function is my requirement for render purpose is to direct get template data from index, so i use dotted string to store where they belong

i have another function which is responsible for getting value from store through dotted string.

export function useGetSelectorByPathHook<TStore extends StoreApi<any>, TKeys extends string>(
  store: TStore,
  keys: TKeys,
  equalityFn: <K extends TKeys>(
    a: ExtractState<TStore>[K],
    b: ExtractState<TStore>[K],
  ) => boolean = Object.is,
): Record<TKeys, any> | any {
  // return useStore(store, state => getValueAtPath(state, keys));
  const render = useStoreWithEqualityFn(store, state => getValueAtPath(state, keys), equalityFn);
  return render;
}

function getValueAtPath(obj: any, path: string) {
  return path.split('.').reduce((acc, part) => {
    if (acc === undefined || acc === null) return undefined;
    return acc[part];
  }, obj);
}

i use this function like

const layout = useGetSelectorByPathHook(storeRef, 'template.0.layout.1')

I just want confirmation that it is a write way to do that am i doing, or i am violating any rule of zustand or react or it make problem in future.

or there could be problem for memoization level if i am using this.

any suggestion or improvements will help me to do it in better way.