Select2 loaded in a remote modal does not load

I have modal loading a remote link where inside it has a select2, however the select2 does not appear.

I use Laravel so my template makes use of blades, I will illustrate how I set up the code:

js for open modal ajax

$(document).ready(function(){
  $('.ls-modal').on('click', function(e){
  e.preventDefault();
  $('#defaultModal').find('.modal-body').load($(this).attr('href'));
  });
});

Here instead the select that should be replaced by a select2, this blade is loaded AFTER the modal is opened.

This would be in changegame.blade.php:

{{ Form::select('games', array('' => 'Select Game') + $games, $user_dati->id_game ?? '',  array('class' => 'sele_game','data-placeholder'=> 'Select Game')) }}

In the main layout of the template I put after js callback to select2 and jquery:

<script type="text/javascript">
$(document).ready(function(){
    $('.sele_game').select2({
    placeholder: 'Select Game',
    ajax: {
      url: 'https://***.it/ajax/load_game',
      dataType: 'json',
      delay: 250,
      processResults: function (data) {
        return {
          results:  $.map(data, function (item) {
                return {
                    text: item.nome,
                    id: item.id
                }
            })
        };
      },
      cache: true
    }
  });
});
</script>

This javascript with the Select2 callback I put in after calling Select2 (v. 4.0.13) via CDN

The chrome console does not report any javascript errors to me.
Where is my mistake?
If I put the jquery, js and select2 inside changegame.blade.php, it loads the select2 correctly (however it is a raw page), if I open changegame.blade.php via button in modal, it loads the css etc but not the select2.

when I press the toggle button the parameter changes to “toggle=on”. is it possible to make it go to “toggle=off” when I press it again?

i want to make a toggle button for my sidebar in javascript via parameters. when I press the toggle button the parameter changes to “toggle=on”. is it possible to make it go to “toggle=off” when I press it again?

html code:

<div class="toggle" onclick="toggle(this)"> <div class="bar1"></div> <div class="bar2"></div> <div class="bar3"></div> </div>

javascript code:

function toggle(x) {
function addOrUpdateURLParam(key, value) {
    const searchParams = new URLSearchParams(window.location.search)
    searchParams.set(key, value)
    const newRelativePathQuery = window.location.pathname + "?" + searchParams.toString()
    history.pushState(null, "", newRelativePathQuery)
    window.location.replace = newRelativePathQuery
}

addOrUpdateURLParam("toggle", "on");
x.classList.toggle("change");
}

Trouble fetching data from API using JavaScript and JSON

I am making a weather app using HTML, CSS, JS, so i took api from https://openweathermap.org/current and used that in my code but i didn’t get the proper/expected result in the browser console.
I don’t know how to access the objects from the result. I need to take/access weather.main, main.temp, main.humidity, wind.speed

code:

async function getData(){
    let response = await fetch(weatherAPI);
    let data = await response.json();
    return data;
}

console.log(getData());

result:

Promise {<pending>}
[[Prototype]]
: 
Promise
[[PromiseState]]
: 
"fulfilled"
[[PromiseResult]]
: 
Object
base
: 
"stations"
clouds
: 
{all: 20}
cod
: 
200
coord
: 
{lon: -0.1257, lat: 51.5085}
dt
: 
1684501221
id
: 
2643743
main
: 
{temp: 15.6, feels_like: 14.86, temp_min: 14.72, temp_max: 17.25, pressure: 1026, …}
name
: 
"London"
sys
: 
{type: 2, id: 2075535, country: 'GB', sunrise: 1684469018, sunset: 1684525832}
timezone
: 
3600
visibility
: 
10000
weather
: 
[{…}]
wind
: 
{speed: 3.6, deg: 50}
[[Prototype]]
: 
Object

expected result:

{
  "coord": {
    "lon": 10.99,
    "lat": 44.34
  },
  "weather": [
    {
      "id": 501,
      "main": "Rain",
      "description": "moderate rain",
      "icon": "10d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 298.48,
    "feels_like": 298.74,
    "temp_min": 297.56,
    "temp_max": 300.05,
    "pressure": 1015,
    "humidity": 64,
    "sea_level": 1015,
    "grnd_level": 933
  },
  "visibility": 10000,
  "wind": {
    "speed": 0.62,
    "deg": 349,
    "gust": 1.18
  },
  "rain": {
    "1h": 3.16
  },
  "clouds": {
    "all": 100
  },
  "dt": 1661870592,
  "sys": {
    "type": 2,
    "id": 2075663,
    "country": "IT",
    "sunrise": 1661834187,
    "sunset": 1661882248
  },
  "timezone": 7200,
  "id": 3163858,
  "name": "Zocca",
  "cod": 200
} 

I need this expected result so that i can use the properties of the json data

How to get the progress for loading an html input file?

Is there a way to get the progress of the html input file as it is being loaded into the browser?

I have an application in which I’m trying to upload a large file (about a gigabyte) to my server.
I have a basic html fine input to get the file onto the browser and then a submit button, which sends the file to the server. I also have a progress bar demonstrating the progress of uploading the file to the server.
The issue I’m running into is that just getting the file from the html input element can take a long time, over a minute for a one gigabyte file. It’s a poor user experience to select a file and then see nothing happen for over a minute. Is there a way to get the progress of the html file input?
I have seen this question already here: How to get onloading progress of input type=file? but found the answer unsatisfying, and that question is over 7 years old by now.
I don’t think this is relevant, but just in case: it’s an angular-ionic application.

The basic input file html looks like this:

<input type="file" (change)="fileEvent($event)">

Get req.body from a list [closed]

Get req.body from a list

I’m trying to get the req.body.email from a request body that contains a list like

    {
        "email": [
            "[email protected]"
        ]
    }

I have tried req.body.email, req.body[0].email, req.body.email[0] but to no avail. This is for an external api so not having the brackets is not an option unfortunately

Appending user id to fetch data

I am fetching data from an api and the api contains information about users with their name, userid and all that information. Now I am fetching the data from the api but I want to fetch data for a specific user only. Initially I want to display the name and a button to view more information about the person. But when the button is clicked I want to fetch all information about the user using user_id

let table;
const show = (data) => {
  table.innerHTML = data
    .map(({id,name,email, gender,status}) => `<tr>
      <td colspan="3">${name} </td>
      <td><button class="more" data-id="${id}" data-name="${name}" data-email="${email}" data-gender="${gender}" data-status="${status}"><span class="material-symbols-outlined">visibility</span></button></td>
      <tr hidden><td>${email}</td>
      <td>${gender}</td>
      <td>${status}</td>
      </tr>`)
    .join("");
};
const load = () => {
  fetch("url")
    .then(result => result.json())
    .then(show);
};
window.addEventListener("DOMContentLoaded", () => {
  table = document.getElementById('table');
  table.addEventListener("click", (e) => {
    const tgt = e.target.closest("button");
    if (!tgt) return;
    const id = tgt.dataset.id;
    const name = tgt.dataset.name;
    const email = tgt.dataset.email;
    const gender = tgt.dataset.gender;
    const status = tgt.dataset.status;
    document.getElementById("modal-name").textContent = name;
    document.getElementById("modal-email").textContent = email;
    document.getElementById("modal-gender").textContent = gender;
    document.getElementById("modal-status").textContent = status;
    $('#myModal').modal('show');
  })
  load();
});

How to generate a polygon with N edges and L1 for even and L2 for odd edges that has the base always perfectly horizontal?

I want to create a function that generates a polygon with N edges and with different size L1 for even edges and L2 for odd edges.

This is my code so far:

function generatePolygon(n, L1, L2) {
    let longerEdges = Math.ceil(n / 2);
    let shorterEdges = n - longerEdges;
    let Lavg = (L1 * longerEdges + L2 * shorterEdges) / n;
    const r = Lavg / (2 * Math.sin(Math.PI / n)); 
    let startAngleRad = Math.PI * (90 - (2 - 1) * 360 / (2 * n)) / 180; 
    let angle = 0; 

    let vertices = [];

    for (let i = 0; i < n; i++) {
        let x = Math.round((r * Math.cos(angle + startAngleRad)) * 10) / 10;
        let y = Math.round((r * Math.sin(angle + startAngleRad)) * 10) / 10;
        
        vertices.push([x, y]);
        
        if ((i + 1) % 2 === 0) {
            angle += 2 * Math.PI * L1 / (Lavg * n);
        } else {
            angle += 2 * Math.PI * L2 / (Lavg * n);
        }
    }

    return vertices;
}

It works ok but i now want to have the base (bottom edge) of the polygon always perfectly horizontal.

This is the result of running my function with N = 10, L1 = 180, L2 = 144:
outcome

The problem as you can see is that the base is not perfectly horizontal.

I should also mention that I want the first or the last edges to be the base and I also need this function to work with any N.

Google Analytics 4 – events not visible

In migration from GAU to GA4, I’m running into problems tracking some events, specifically those resulting from my form submissions. I have used the Tag Assistant debugger, and I see the events being triggered, but I don’t see them when I query for events. An example is a “phone_capture” event.

Hit Details (filtered):
    Page Location   dl  https://16v8x.elite80-001.ihousedev.com/contact
    Page Referrer   dr  https://tagassistant.google.com/
    Page Title  dt  Contact Us | New Tester | 111-111-1111 | Paradise Valley AZ Homes for Sale
    Event Name  en  phone_capture
    Event Parameter ep.event_category   lead
    Event Parameter ep.event_label  Contact Us

API Call:
    gtag("event", "phone_capture", {event_category: "lead", event_label: "Contact Us"})

Data Layer
    {
      event: "phone_capture",
      gtm: {uniqueEventId: 14, start: 1684510761995, priorityId: undefined},
      eventModel: {
        event_category: "lead",
        event_label: "Contact Us",
        send_to: "G-6ZMEJ6WQZQ"
      }
    }

I generate the report with:

$report_params = 
[
    'property'        => "properties/$property_id",
    'dateRanges' => [['start_date'=>'2023-04-28', 'end_date'=>date('Y-m-d')]],
    'dimensions' => [ new Dimension( ['name' => 'eventName'] )],
    'metrics'    => [ new Metric( ['name' => 'totalUsers'] )],
];
$response = $client->runReport( $report_params );

I do see other events:
EventName Users
capture 2
first_visit 4
form_submission 2
form_view 2
login 1
page_view 5
session_start 5
user_engagement 4

Is there a different dimension I can use to grab my phone_capture event? Or something else that I have missed?

Creating a dynamic number of controlled inputs

I have a page where a dynamic, previously unknown, number of records comes from different database entities in the form of objects { id, name }, where the name field is unique. They are output, and each of them corresponds to input, react-hook-form is used to collect data from the form

I need to get access to the data from each input (make them controllable)

const { register, handleSubmit } = useForm();

<form onSubmit={handleSubmit(submit)}>
  {firstItemArray.map((item) => {
    <div>
      {item.name}
      <input {...register(`${item.name}`)} />
    </div>;
  })}
  {secondItemArray.map((item) => {
    <div>
      {item.name}
      <input {...register(`${item.name}`)} />
    </div>;
  })}
  <button type="submit" />
</form>

I have already tried useFieldArray, but it allows you to create only one array, like:

{
  "array": [
    {
      "id": "1",
      "inputValue": "10"
    },
    {
      "id": "2",
      "inputValue": "12"
    }
  ]
}

And I need several arrays:

{
  "firstArray": [
    {
      "id": "1",
      "inputValue": "12"
    },
    {
      "id": "2",
      "inputValue": "34"
    }
  ],
  "secondArray": [
    {
      "id": "1",
      "inputValue": "42"
    },
    {
      "id": "2",
      "inputValue": "24"
    }
  ]
}

How to nest async/await functions returned through other functions

I’m trying to create a root promise function (calling an API) that can be reused by other functions to do more specific requests with the API. However the result I get at the end is an incomplete API response. It looks as if it’s not “awaiting” the response.

// Original API call
const callAPI= async(a, b) =>{
    const url = "https://someapi.com/endpoint/" + a + "/" + b;
    const results = await fetch(url);
    return results
}
// more specific API call using the above function
const specificAPI = async(x) =>{
    const results = await callAPI("abc", x);
    return results;
}
// main
async function main(){
    const results = await specificAPI("123");
    console.log(results);
}

The output of the console.log() in the main() function ends up being a fragment of the result. Like its not waiting for the response to return.

How to check if a div class has been clicked in JavaScript?

I want to check if a div class element has been clicked.Is there a way in Javascript. I have a conditional statement which checked whether a style has certain attributes, but there is no way I know of checking whether a div class in that conditional statement has been clicked…

Here’s my code so far:

let a = document.getElementsByClassName("roll")[0];
let b = document.getElementsByClassName("effect")[0];

a.onclick = function(){
    b.setAttribute('style','border-right:4px solid #aa2e27')
}

a.onmouseover = function(){
    if(b.hasAttribute('style','border-right:none') && a.onclick.value == "false"){
        b.setAttribute('style','border-right:4px solid #aa2e27');
    }
}

As you can see, the if condition takes place on mouseover event. Is there a way to check this? (what I entered on mouseover doesnt trigger)

Firefox MediaRecorder webm audio container

I am trying to record audio in a webm container using MediaRecorder in Firefox. The exact mime type I’m going for is "audio/webm;codecs:vp9 which should be supported according to:

MediaRecorder.isTypeSupported("audio/webm;codecs:vp9") // outputs true

Currently, I use the following code to record the audio:

const mediaRecorderRef = new MediaRecorder(stream, {
    mimeType: "audio/webm;codecs:vp9"
});
mediaRecorderRef.start(1000);
mediaRecorderRef.current.ondataavailable = (e) => {
    // storing all chunks
};

After the recording, I create one big blob from the audio chunks as follows:

new Blob(audioChunks, { type: "audio/webm;codecs:vp9" })

Unfortunately, something is wrong with the created audio as I can not play it back. Recording and playing back audio does work on Chrome however.
I saw the same behavior using different codecs with the webm container in Firefox. Recordings did work using an ogg container, though this is not the format that I need.

Is it possible to record audio in a webm container in Firefox? If so, what is the issue with my current solution?

POST http://127.0.0.1:5500/auth 405 (Method Not Allowed) / Uncaught (in promise) Error: No token defined

I am trying to build a chatbox using JS, Scaledrone and GO.
However, using their tutorial I have encoutered many errors during coding.

Most of them I have solved myself but this one gives me a headache:

After compiling the code, I get this response in console:

POST http://127.0.0.1:5500/auth 405 (Method Not Allowed)
and underneath that this one: Uncaught (in promise) Error: No token defined

It points at one part of my code and it is this one:

const formData = new FormData();
  formData.append("clientID", drone.clientId);
  fetch("/auth", {
    method: "POST",
    body: formData,
  })
    .then((res) => res.text())
    .then((jwt) => drone.authenticate(jwt));
});

It points exactly at

fetch("auth",

I managed to open the chat box, it gives me option to write and send message. It does not assign me name, it does not log my message into chat box.

using sources from:
github.com/golang-jwt/jwt/v5
github.com/gorilla/mux

I have tried different things, from changing the /auth information to googling all possible solutions but none gave me the answer.

There are simpler options to build a chatbox using vannilla js but I would like to do it this way as it looks more cool.

I have updated all the GO files, downloaded GO manually, and also updated github.com/golang-jwt/jwt/v5 .