How to solve this error, “Error parsing response on javascript”

I get this error when running on a live server but works fine on localhost

Error parsing response: Unexpected token ‘C’, “Connection”… is not valid JSON

  $.ajax({
        type: 'POST',
        url: 'retrieve-client.php',
        data: { accountId: accountId },
        success: function(response) {
            setTimeout(function() {
                try {
                    var data = JSON.parse(response);
                    $('#accountName').val(data.fname + ' ' +data.lname).removeClass('hidden');
                    $('#accountType').val(data.type).removeClass('hidden');
                    $('#Transfer').removeClass('hidden');
                    $('#hide1').removeClass('hidden');
                    $('#hide2').removeClass('hidden');
                    $('#accountId').prop('readonly', true);
                    $('#retrieveButton').hide();
                    // Clear any previous error message
                    $('#accountError').text('');
                } catch (error) {
                    $('#accountName').val('').addClass('hidden');
                    $('#accountType').val('').addClass('hidden');
                    $('#Transfer').addClass('hidden');
                    $('#hide1').addClass('hidden');
                    $('#hide2').addClass('hidden');
                    // Display error message near the input field
                    $('#accountError').text('Error parsing response: ' + error.message);
                } finally {
                    // Hide loader after processing response
                    $('#loader').hide();
                }
            }, 3000); // Delay for 3 seconds
        },
        error: function(xhr, status, error) {
            $('#accountName').val('').addClass('hidden');
            $('#accountType').val('').addClass('hidden');
            $('#Transfer').addClass('hidden');
            $('#hide1').addClass('hidden');
            $('#hide2').addClass('hidden');
            var errorMessage;
            if (xhr.responseText) {
                var errorResponse = JSON.parse(xhr.responseText);
                errorMessage = errorResponse.error;
            } else {
                errorMessage = 'Error retrieving client details: ' + error;
            }
            // Display error message near the input field
            $('#accountError').text(errorMessage);
            // Hide loader in case of error
            $('#loader').hide();
        }
    });

Java to Node.js Conversion of AES and RSA Encryption

I’m working with an application (Jobvite) that requires me to encrypt data that is sent to its API. Specific steps involve generating a random AES key, using it to encrypt a JSON message, then using a RSA public key to encrypt the AES key, and then send both the encrypted message and the encrypted AES key to the API endpoint (in a JSON object).

I have an example for doing this using Java that works as expected (the code generates the encrypted message + key, which I then post to the API endpoint using Postman, and I get back a successful response). I have implemented a Node.js version of that code. But when I post the encrypted message + key generated by this code to the API endpoint, it returns an error. I verified using online tools that the encrypted message and key produced by the Node.js code do get decrypted successfully, so it seems like the issue might be with the format, or padding, etc.

Any help is appreciated. Thanks in advance.

JAVA

String public_key_string = "MIIBIjANBgk************BEtWbhxQIvd4QIDAQAB";

String message = "{"filter":{"process":{"DateCreated":{"gte":"2023-10-01T10:50:00Z","lte":"2024-01-31T10:50:00Z"}}}}";

KeyGenerator key_generator = KeyGenerator.getInstance("AES");
key_generator.init(256);
SecretKey aes_key = key_generator.generateKey();
byte[] aes_key_byte_array = aes_key.getEncoded();
SecretKey secret_key = new SecretKeySpec(aes_key_byte_array, "AES");

byte[] pub_key_byte_array = Base64.getDecoder().decode(public_key_string);
EncodedKeySpec encoded_key_spec = new X509EncodedKeySpec(pub_key_byte_array);
PublicKey public_key = KeyFactory.getInstance("RSA").generatePublic(encoded_key_spec);

Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(1, public_key);
byte[] encrypted_key_bytes = cipher.doFinal(secret_key.getEncoded());
String encrypted_key = Base64.getEncoder().encodeToString(encrypted_key_bytes);

Cipher cipher2 = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher2.init(1, secret_key);
byte[] cipher_bytes = cipher2.doFinal(message.getBytes(StandardCharsets.UTF_8));
String encrypted_message = Base64.getEncoder().encodeToString(cipher_bytes);

System.out.println(encrypted_message);
System.out.println(encrypted_key);

Node.js

const public_key = "-----BEGIN PUBLIC KEY-----nMIIBIjANBgk*****BEtWbhxQIvdn4QIDAQABn-----END PUBLIC KEY-----n"

const message = JSON.stringify({"filter":{"process":{"DateCreated":{"gte":"2023-10-01T10:50:00Z","lte":"2024-01-31T10:50:00Z"}}}});

const aes_key = crypto.randomBytes(32);
const encrypted_key = crypto.publicEncrypt({"key": public_key, "padding": crypto.constants.RSA_PKCS1_PADDING}, aes_key).toString("base64");

const cipher = crypto.createCipheriv("aes-256-ecb", Buffer.from(aes_key), null);
let encrypted_message = cipher.update(message, "utf8", "base64");
encrypted_message += cipher.final("base64");

console.log(encrypted_message);
console.log(encrypted_key);

Customizing Stamping Functionality in Mozilla PDF.js Library

We are currently using the Mozilla PDF.js library to implement PDF viewing functionality in our application. Our requirement is to customize the stamping feature in PDF.js to include predefined images such as “Approve,” “Done,” and “Rejected.”

We’ve reviewed the documentation Reference link and are aware of the capability to upload images as stamps. However, we need guidance on how to integrate our custom predefined stamping images.

  1. How can we add custom predefined stamping images to the PDF.js stamping functionality?
  2. What modifications are required in the code to enable users to select and apply predefined stamps like “Approve,” “Done,” and “Rejected”?

How to manage an array brought from a query into a php form select

I’m triying to assemble a Select intput for a form in HTML/PHP, from JavaScript, as follows:

  function cerrando(){
    $(".creaDetFact").empty();
    $(".bvp").empty();
    var rfFac = $("#rfFac").val();
    var vTDF = "Pago de Factura";
    var datos = new FormData();
    datos.append("rdffac",rfFac);
    document.getElementById("TDF").innerHTML = vTDF;
    $(".creaDetFact").append(
      '<form role="form" method="post" autocomplete="off">'+
        '<div class="form-group">'+
          '<div class="col-xs-6" style="padding-right: 0px;">'+
            '<div class="input-group">'+
              '<select class="form-control input-lg" type="number" name="creaCate" id="creaCate" required>'+
                '<option value="">Seleccione Categoría</option>'+
                '<?php'+
                  $.ajax({
                    url: "ajax/ventas.ajax.php",
                    method: "POST",
                    data: datos,
                    cache: false,
                    contentType: false,
                    processData: false,
                    dataType: "json",
                    success: function (dataset){

/* This above procedure brings back an array of n rows */

                      foreach(dataset){
                        echo '<option value=' + dataset["mp_pago"] + '>' + dataset["mp_descripcion"] + '</option>'+
                      }

/* why is the parser telling me that this instruction is wrong */
                      
                    }
                  }) +
                '?>'+
              '</select>'+
            '</div>'+
          '</div>'+
          '<div class="col-xs-6" style="padding-left: 0px;">'+
            '<div class="input-group">'+
              '<input type="text" class="form-control" id="rfTsc" name="rfTsc" required>'+
              '<span class="input-group-addon"><i class="fa fa-lock"></i></span>'+
            '</div>'+
          '</div>'+
        '</div>'+
        '<button type="button" style="margin-right: 40px" class="btn btn-primary pull-right">Guardar</button>'+
      '</form>'
    );

the parser of VSC is telling me that I have an error at the foreach and I can’t get it

As I’ve said, I’m trying to assemble a select input for a HTML/PHP form, from Javascript, with the dataset coming from a query to the database.

The query brings back n rows (5, 4, 3, depending on the query) and those rows are parameters for a Select input in the intended form

Create a backend API endpoint for the provided course data

How to Create a backend API endpoint for the provided course data. (use mongoimport –db mongo-test –collection courses –file courses.json –jsonArray) to import the included data
-Retrieve all published backend courses and sort them alphabetically by their names.
-Select and extract the name and specialization of each course.
-Retrieve all published BSIS (Bachelor of Science in Information Systems) and BSIT (Bachelor of Science in Information Technology) courses from the curriculum.
-Perform data validation at each step to ensure the accuracy and integrity of the retrieved information.
-Document the test procedure, including any challenges faced and solutions implemented.

I need the code for this?. for anyone that can help me, thank you in advanced.

Tampermonkey Script – getComputedStyle(variable).display inconsistency

I am trying to make a script that only triggers on certain conditions on a web tool.

There are two text blocks, when one is active, the style inspector says says:
style=”display: block”
and the other is
style=”display: none”

When I use a command like the following though

console.log("Block status is: " + getComputedStyle(element1).display);
Output is: block (as expected)

console.log("Block status is: " + getComputedStyle(element2).display);
Output is: block (despite style inspector saying “none”)

When printing the whole object using:
console.log(getComputedStyle(element1).display); console.log(getComputedStyle(element2).display);
Delving into them, they both say block, even though only one is displayed and the style inspector saying only one is displayed.

They are both a very simple class and I don’t have much to work with when it comes to triggering an action based on their state. Can anyone help clarify what is happening here or recommend any alternative solutions?

How to check if a reference to a function has changed

I have the following function.

function doSomething() {
    console.log('a');
}

I’ve then created a WebSocket.

var websocket = new WebSocket(HOSTNAME);
websocket.onmessage = doSomething;

Then, I’ve created an interval function.

setInterval(function(){
    console.log(websocket.onmessage == doSomething);
    console.log(websocket.onmessage.toString() == doSomething.toString());
}, 5000);

When the interval function runs, it logs false twice.

When I check to see what websocket.onmessage returns, it returns dr(eA).

And when I check what websocket.onmessage.toString() returns, it returns "function(eA){try{ey['Y'](eA)&&ez[d(143)](this,eA);}catch(eC){var eB=cI(cL(ey['C']),d(405));if(ey['C']['o']['tb'](eB,eC,(eA[d(314)]||d(636))+'.'+ey['ab']+':\x20'+ax(ey['da'])))throw eC;}}".

How can I reliably check if websocket.onmessage is the same function as doSomething?

I’m trying to write a highscore to a file in p5js

I’m using p5js to make a game, and I would like to write the highscore to a text file so that it stays the same when I stop and start the program. Is there a way to edit a text file with code in p5js that already exists?

The only solutions I’ve seen have involved creating a new file entirely but I want the highscore file to be a part of the project that isn’t created when it is run. Thank you in advance.

How to get and display name and email from fetchUserAttributes() in basic AWS Amplify React JS webapp

I have the same issue as listed in the link below, although I am struggling to display the user email as a simple text string in my webapp (in the return output):

get-current-authenticated-users-email-in-aws-amplify-v6

Approximately two months ago (Dec 2023) AWS Amplify changed functions such as AUTH which broke my former coding to display current user name and email. I am new to javascript and React so really need basic beginner examples of how the new changes to AWS Amplify React Javascript V6 work (migrating from V5). The current documentation is dreadful (for a beginner). A simple entire App.js example to display user name and user email (a simple Hello world) is required.

I found some information here too, and it is very helpful but I’m learning javascript and still can’t display user email (no errors or warnings, but nothing appears). (imported as ‘Auth’) was not found in ‘aws-amplify’

The solution shown below that was provided by @Abiram does successfully show the user’s email in the Console, but I’m not sure how to display the email in my webapp (instead of the console).

I’m basically building a chat app and want to include the username, user email, and current datetime in every chat message.

The code below works, but instead of ‘userAttributes.email’ print to Console I want to return/output (display on my webapp) into a textbox.

import { fetchUserAttributes } from '@aws-amplify/auth';
import { Authenticator } from '@aws-amplify/ui-react';
import '@aws-amplify/ui-react/styles.css';
import { Amplify } from 'aws-amplify';
import React from 'react';

import awsExports from './aws-exports';
Amplify.configure(awsExports);

export default function App() {

  // Function to print access token and id token
  const printUserAttributes = async () => {
    try {
      const userAttributes = await fetchUserAttributes();
      console.log('Email:', userAttributes.email);
    }
    catch (e) { console.log(e); }
  };

  return (
    <Authenticator hideSignUp loginMechanisms={['username']}>
      {({ signOut, user }) => (
        <main>
          <h1>Hello {user.username}</h1>
          <button onClick={signOut}>Sign out</button>
          <button onClick={printUserAttributes}>Print Attributes</button>
        </main>
      )}
    </Authenticator>
  );
}

I can display user email to console, but learning javascript and not sure how to display in return/output.

How can I hide the actual file name behind the domain?

My page has many .php sites, e.g. mydomain.com/index.php, mydomain.com/news.php, mydomain.com/biography.php etc.

How can I mask the actual PHP names in the URL so that only the domain is displayed?

You should only see mydomain.com regardless of the name of the actual .php file you are browsing (news.php, biography.php etc.).

According to my webspace provider he can only forward site x to site y, but cannot hide the file name behind the domain name.

CSS Scrollbar issue

Scroll bar takes space from main content when it appears, pushing it to the left. Is there any way to make it appear without pushing it?

I tried to set ::webkit-scrollbar’s position to absolute, but it didn’t work. For now I set body overflow-y: scroll; but it would be better if I could achieve what I want

How to fix: TypeError: fn is not a function while running artillery script

I am getting the error ⠇ TypeError: fn is not a function while running my artillery test file.

Here is the yml layout:

  target: "https://www.therisecollection.co/"  # Update with your test URL
   # Load the Playwright engine:
  engines:
    playwright: {}
  processor: './javascriptTest.js'
  phases:
    - duration: 60
      arrivalRate: 5
      name: Warm up
    - duration: 120
      arrivalRate: 5
      rampTo: 50
      name: Ramp up load
    - duration: 600
      arrivalRate: 50
      name: Sustained load

scenarios:
  - engine: "playwright"
    flowFunction: 'viewHome'
    flow: []


here is the JavaScript I am attempting to use:

async function viewHome(page) {
  await page.goto('https://www.therisecollection.co/');
  await page.getByRole('button', { name: 'Home' }).click();
  await page.getByRole('button', { name: 'About' }).click();
  await page.getByRole('button', { name: 'Home' }).click();
  await page.getByRole('button', { name: 'About' }).click();
  await page.getByRole('button', { name: 'Home' }).click();
  await page.getByRole('button', { name: 'About' }).click();
  await page.getByRole('button', { name: 'Home' }).click();
  await page.getByRole('button', { name: 'About' }).click();
}

module.export = viewHome;

I have seen the following recommended but haven’t attempted this yet:

  • Run artillery from a different location
  • Re-install artillery

What is the best way to begin debugging this issue? From what I can see, everything related to the function is defined correctly.

Material ui Select component with asynchronous data. How to use it in react hook form?

In my React application, I am using react-hook-form and Material UI. I have a situation like this. need to show a dropdown with a list of values. This list of values is getting from the API response. another API is getting the value previously stored. My problem is initially the dropdown is not getting selected with saved value.

what I have is :

const { data: allCountryList } = useGetCountryList(); // Fetching entire countrylist

const countryList = useMemo(() => { //Processing the countrylist
const list = allCountryList?.result?.countryList?.map((country) => ({
  label: country?.name,
  value: country?.code,
}));
return list;
}, [allCountryList]);

const fetchDetails = useCallback(async () => {
const response = await getProfileDetails(); // getting previously saved values

const {
  email = '',
 .........
  country = '',
} = response?.result?.user ?? '';
response?.result?.user?.companies;

return {
  email,
  .........
  country,
 };
 }, []);

const {
control,
setValue,
formState: { errors },
watch,
trigger,
getValues,
reset,
setError,
} = useForm<FormDataType>({
resolver: yupResolver(schema),
defaultValues: fetchDetails,
shouldFocusError: true,
mode: 'all',
});

   ......
return(
....................
<FormControl sx={{ display: 'flex', marginBottom: '0' }}>
                  <Controller
                    name="country"
                    control={control}
                    render={({ field }) => (
                      <Select
                        id="country"
                        label="country
                        aria-label="country"
                        required
                        displayEmpty
                        MenuProps={{ sx: { maxHeight: 200 } }}
                        {...field}
                        error={!!errors?.country?.message}
                        helperText={errors?.country?.message}
                        onChange={onCountryChange}
                      >
                        <MenuItem value="" disabled>
                          {t('fields.country')}
                        </MenuItem>
                        {countryList?.map((country, index) => (
                          <MenuItem value={country.value} key={`${country.value} - ${index}`}>
                            {country.label}
                          </MenuItem>
                        ))}
                      </Select>
                    )}
                  />
                </FormControl> 
      )

The output is :
enter image description here

How to solve this?