want to send button value with event-triggered submit

A button has a name/value pair. When I click it, after a two-second delay, I want the form to submit with the button’s name/value pair as part of the form data.

Without any Javascript, the form would submit without delay with the button’s name/value pair as part of the form data.

Please see my MWE below.

<!doctype html>
<html lang="en">
    <head>
        <script src="import/jquery-3.6.4.min.js"></script>
        <script>
            $(document).ready(function(){

                var waittime=2;
                var blocksubmit=true;

                $('form').submit(function (evt) {
                    if (blocksubmit) evt.preventDefault();
                });

                $('button').click(function(me){
                    theval = this.value;
                    $('#msg').html('Submitting "'+theval+'" in '+waittime+' seconds.');
                
                    setTimeout(
                        function () {
                            blocksubmit=false;
                            $('form').first().trigger('submit');
                            $('#msg').html('The URL should now display ?'+theval+' at its end.');
                        },
                        1000*waittime
                    );

                });
            });
        </script>
    </head>
    <body>
        <form action="?" method="get">
            <p id="msg">Choose one:</p>
            <button name="choice" value="True">True</button>
            <button name="choice" value="False">False</button>
        </form>
        <p>Expected behavior: Two seconds after clicking a button, the browser loads `?choice=True` or `?choice=False`.</p> 
        <p>Actual behavior: Two seconds after clicking a button, the browser loads `?`. The input value is not included.</p> 
    </body>
</html>

Why is it ignoring the form data set when I click a button? choice is not set when the form submits.

Thanks!

MySQL ERR in Express Back-End Server

I am facing an MySQL err while I am executing a query on my Express server.

My code is as follows.

module.exports.generateDailyWords = async function () {
  try {
    // generate the shape of word combination for the day
    var shape = generateRandomNumbers();

    // retrieve 4 words from the dictionary
    var q_1 = `
            SELECT word 
            FROM new_dic 
            WHERE LENGTH(word) = ?
            ORDER BY RAND() 
            LIMIT 1
        `;
    var first = await excuteQuery(q_1, [shape[0]]);
    var word_1 = first[0].word;

    var q_2 = `
            SELECT word 
            FROM new_dic 
            WHERE LENGTH(word) = ? 
            AND word LIKE ?
            AND word != ?
            ORDER BY RAND() 
            LIMIT 1
        `;

    var second = await excuteQuery(q_2, [shape[1], word_1[0] + "%", word_1]);
    var word_2 = second[0].word;

    var q_3 = `
            SELECT word 
            FROM new_dic 
            WHERE LENGTH(word) = ? 
            AND word LIKE ? 
            AND word != ?
            AND word != ?
            ORDER BY RAND() 
            LIMIT 1
        `;

    var third = await excuteQuery(q_3, [
      shape[1],
      word_1[word_1.length - 1] + "%",
      word_1,
      word_2,
    ]);
    var word_3 = third[0].word;

    var q_4 = `
            SELECT word
            FROM new_dic
            WHERE LENGTH(word) = ?
            AND word LIKE ?
            AND word != ?
            AND word != ?
            AND word != ?
            ORDER BY RAND()
            LIMIT 1
        `;

    var forth = await excuteQuery(q_4, [
      shape[0],
      word_2[word_2.length - 1] + "%" + word_3[word_3.length - 1],
      word_1,
      word_2,
      word_3,
    ]);
    var word_4 = forth[0].word;

    // save the combination into the database
    var combination = JSON.stringify([word_1, word_2, word_3, word_4]);

    return combination;
    // return '["jube","juicy","ender","ywar"]'
  } catch (err) {
    console.log(err, "err while generating daily words");
    await this.generateDailyWords();
  }
};

So this function – generateDailyWords is responsible for retrieving a combination of 4 words which meets a certain condition. I run this regularly(will be daily, for now every 10 min for testing.) and sometimes I got this error which implies that retrieving a word from db has failed.

Any idea regarding this issue?

p.s. I haven’t got much experience with back-end development so would appreciate if someone can let me know an efficient way for error handling, like best practice for writing error handling helper function.

TypeError: Cannot read properties of undefined (reading ‘word’)

I tried to log retrieved data, which sometimes gave me undefined variables.

I have to pick several things at once. With the original sequence intact, I would like to shift from Select A to Select B and vice versa

I have two select elements: added position skill (Select B) and skills set (select A). In order to transfer options from the Skills set to the Added Position Skill and vice versa, I want to preserve their original location, index, and/or position within the second choose element. The code I have is moving components from one select box to another if one is selected. Additionally, when I move items back from the second select box to the first, they either add to the top of the list or to the bottom, which is not where they were moved from Select A.

UI:
Select Boxes

Javascript code:

<script>
let skillBox = document.querySelector('#skillSelectionBox');
            let skillToPositionBox = document.querySelector('#skillPositionSelectionBox');
            let addButton = document.querySelector('#addSkill');
            let removeButton = document.querySelector('#removeSkill');

            function moveOptions(sourceBox, targetBox) {
                const selectedOptions = Array.from(sourceBox.options).filter(option => option.selected);

                selectedOptions.forEach(selectedOption => {
                    const clonedOption = new Option(selectedOption.text, selectedOption.value);
                    targetBox.add(clonedOption);
                    const originalIndex = Array.from(sourceBox.options).indexOf(selectedOption);
                    originalIndices.push(originalIndex);
                    sourceBox.remove(originalIndex);
                });

                // Sort options in targetBox based on original indices
                originalIndices.sort((a, b) => a - b);

                originalIndices.forEach(index => {
                    const originalOption = sourceBox.options[index];
                    if (originalOption) {
                        const clonedOption = new Option(originalOption.text, originalOption.value);
                        targetBox.add(clonedOption);
                    }
                });

                // Clear originalIndices array after moving options
                originalIndices = [];
            }

            // Assuming addButton and removeButton are the button elements in your HTML
            addButton.addEventListener('click', function() {
                moveOptions(skillBox, skillToPositionBox);
            });

            removeButton.addEventListener('click', function() {
                moveOptions(skillToPositionBox, skillBox);
            });
</script>

Connect Postgres database to nodejs program

I’m trying to connect a postgres database that I created with render.com and I’m getting this error:

Error: read ECONNRESET at TCP.onStreamRead (node:internal/stream_base_commons:217:20) { errno: -4077, code: 'ECONNRESET', syscall: 'read' }

I’m trying to use the pg import with the external connect string that render.com offers with its database:

    const { Client } = require('pg');
    const client = new Client(process.env.RENDER_EXTERNAL_URL);
    client.connect(function(err) {
        if (err) throw err;
            console.log("Connected!");
        });

The code snippet does not run of course, but I’m wondering why I’m getting this error when I simply try to connect. I’ve read about it elsewhere, and it looks like it pops up when people try to access too much of the database at once.

I tried both the URL supplied from render.com and the individual parts of the URL broken down into an object that is passed in as arguments to the Client object. This is what I found on multiple tutorial websites. Anything helps, including better ways to do this!

Calling removeChild on the parent element of a selected element completes without error but does not remove child

I am trying to select a group of html elements and delete them from their parent elements. Currently, I get no exceptions when running the code, but the child elements remain on the page. In addition, running the same code in the developer console works without issue.

HTML:

<div>
  <img class="example">
</div>
<div>
  <img class="example">
</div>
<div>
  <img class="example">
</div>

JavaScript:

document.querySelectorAll("img.example").forEach(e => {
    /*
    Unrelated code that makes use of the e argument
    */
    e.parentElement.removeChild(e);
});

If there is a better way to remove said elements, I would be happy to be told what it is, but I would also like to know if there is an issue with my code regardless.

How to replicate import.meta.url to get the relative path in a non type=”module” script?

I’m trying to get the relative path to the current script when the script is a “classic script” (when the type is not set as type=module).

<script src="./scripts/foo.js"></script>

I’d like to be able to get the current relative path to that script.

I have tried getting the URL from the document.currentScript.src but this doesn’t factor in if the page has a <base href="./foo"> and I am not sure if there are other modifiers that affect the path.

Is there a comprehensive way to resolve the relative or absolute path to the current script?

Pass JSON data to html table using ajax laravel

I’m a newbie in JavaScript, but I’m still learning. I have a Laravel project and got stuck when I tried to pass the JSON data that I grouped using Ajax to Table.

This is the Ajax code below:

$.ajax({
    type: "get",
    url: "https://res.cloudinary.com/dtuwzzusm/raw/upload/v1707126845/project/get_schedule_tkmqoa.json",
    dataType: "json",
    success: function (response) {
        var group = function(xs, key) {
        return xs.reduce(function(rv, x) {
            (rv[x[key]] = rv[x[key]] || []).push(x);
            return rv;
        }, {});
        };
        var groubedByname = group(response, 'name')
        console.log(groubedByname);
        $.each(response, function( index, value ) {
            // How to pass to the table as my expected table, please see an image attached
        });
    },
    error: function (response) {
    }
});
table, th, td {
  border: 1px solid;
}
th, td {
padding : 10px;
}
<!DOCTYPE html>
<html>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
<body>
  <table id="schedule-table">
      <thead>
          <tr>
              <th>Name</th>
              <th>01</th>
              <th>02</th>
              <th>03</th>
              <th>04</th>
              <th>05</th>
              <th>06</th>
              <th>07</th>
              <th>08</th>
              <th>09</th>
              <th>10</th>
              <th>11</th>
              <th>12</th>
              <th>13</th>
              <th>14</th>
              <th>15</th>
          </tr>
      </thead>
      <tbody id="body_schedule">
           
      </tbody>
  </table>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</body>
</html>

I would like to pass the JSON data that I grouped using Ajax to HTML Table.

example expected table I need :

[enter image description here](https://i.stack.imgur.com/64h7q.png)

is there anyone who can help me?

Thank you.

Does JS event loop always prioritize microtask queue over macrotask queue?

I was recently watching a workshop video by Will Sentence on async javascript and I am having trouble understanding whether microtask queue always has priority over macrotask queue.

function display(data) {console.log(data)}
function printHello() {console.log(“Hello”);}
function blockFor300ms() {/* blocks js thread for 300ms with long for loop */}

setTimeout(printHello, 0);

const futureData = fetch('https://twitter.com/will/tweets/1')
futureData.then(display)

blockFor300ms()

console.log(“Me first!”);

In this example, Will explains that printhello is added to the macrotask (callback) queue then the fetch request gets executed and suppose at 201ms of the code exuction, the display callback is added to the microtask queue. Meanwhile the blockFor300ms had blocked the code for 300ms.
At about 301ms Me first! gets console logged, then since the microtask queue has priority over the macrotask queue, the data from the fetch request gets logged and finally the setTimeout’s Hello. So the order of the console.logs:

1. console.log("Me first!")
2. console.log(data) // data from fetch request
3. console.log("Hello")

I tried executing similar code example in various environments (Chrome, Firefox, Safari, node), with various blocker functions (with varying durations) and I always get:

1. synchronous code console.log("Me first!")
2. console.log from the setTimeout
3. console.log with data from fetch request .then

I thought maybe the result depends on when the fetch request gets resolved and the data is received but I have also tried blocking the code for more than 10 or 20 seconds and the outcome is always setTimeout first then the fetch. Whats going on here and what’s the reason behind this?

Here is the code I tested with:

function display(data) {console.log("Fetched data:", data);}
function printHello() {console.log("Hello")}
function blockForDuration(duration) {
  const startTime = Date.now();
  while (Date.now() - startTime < duration) {}
}

setTimeout(printHello, 0);

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => response.json())
  .then(display)
  .catch(error => console.error("Fetch error:", error));


blockForDuration(10000);

console.log("Me first!");

/*
  Console log order
  1. "Me first!"
  2. "Hello"
  3. "Fetched data:", data
*/

Changing an element’s opacity after checking a box

I am making a web app similar to reminders app on iphone and I want to integrate a feature that turns the opacity of a task down if it’s marked as completed.

Here’s my current HTML:

import "bootstrap/dist/css/bootstrap.css";
import "./TaskList.css"

function TaskList() {
  return (
    <div className="card rounded-0">
      <div className="row g-0">
        <div className="col-md-8 d-flex column align-items-center task">
          <label class="custom-checkbox">
            <input type="checkbox"></input>
            <span class="checkmark"></span>
          </label>
          <div className="card-body task-body">
            <h5 className="card-title">Task #1</h5>
            <p className="card-text">This is a standard task.</p>
            <p className="card-text">
              <small className="text-body-secondary">Due Date: </small>
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}

export default TaskList;

And my CSS Code:

input[type="checkbox"]{
  opacity: 0;
}

.custom-checkbox {
  width: 40px;
  height: 27px;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
}

.custom-checkbox .checkmark:hover{
  background-color: whitesmoke;
}

.custom-checkbox .checkmark{
  width: 100%;
  height: 100%;
  border: 2px solid black;
  border-radius: 3px;
  background: white;
}

.custom-checkbox input:checked + .checkmark{
  background: url(check2.svg) center/100%;
}

.task{
  border-bottom: 1px solid black;
  width: 100%;
}

.task-body{
  opacity: 1;
}

.custom-checkbox input:checked ~ .task-body{
  opacity: 0.5;
}

The opacity won’t go to 0.5 after the checkbox has been checked. What’s causing the issue?

I tried multiple times to create a new class to put the element under and that didn’t fix my issue. All help is appreciated. Thank you!

Good Ol’ CORs question, ASP.Net, asmx, soap

I have an old asp.net soap service that I need to keep running for the next few years but I am updating the interface to run via a webapp instead of an old Windows app.
I am trying to get to work and calling a simple method via jQuery AJAX (probably better ways to do it, sure).

I am running into CORS issues.
I have access to the IIS server which the service is running.
After checking all over the Googles AND reading suggestions on StackOverflow I implemented a few properties to the web.config to no avail.

I have tried setting the web.config settings:

        <add name="Access-Control-Allow-Origin" value="*" />
       <!-- <add name="Access-Control-Allow-Methods" value="*" />-->
        <add name="Access-Control-Allow-Methods" value="GET,POST,OPTIONS" />
        <add name="Access-Control-Allow-Headers" value="Content-Type, soapaction" />

So far my jQuery and HTML code is:

 <input type="text" value="" />
 <span>Push go</span>

<script src="https://code.jquery.com/jquery-3.7.1.min.js" crossorigin="anonymous"></script>
<script>
$('span').on('click', function(){
var number = $('input').val();
justGo(number);

});

//--RUNNING INTO CORS ISSUES
 function justGo(incomingNumber){
var SoaMessage = '<?xml version="1.0" encoding="utf-8"?>'
 +'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
  xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'
 +'<soap:Body>'
 +'<IsUserCheckedIn xmlns="http://tempuri.org/">'
     + '<VisitorID>' + incomingNumber + '</VisitorID>'
    +'</IsUserCheckedIn>'
  +'</soap:Body>'
 +'</soap:Envelope>';
var url = "http://servicesite.somesite.com/ws/MyService.asmx?op=GetUserInfo";
//$.support.cors = true; //Even with this on it still same error
$.ajax({
 // crossorigin: "anonymous",
    type: "GET", //also POST
    url: url,
    //jsonpCallback: "GetUserInfo",  //Using SOAP so this doesn't work?
    dataType: "xml",
    processData: false,
    contentType: "text/xml; charset="utf-8"",
    success: function (msg) {

   console.log("message: " + msg);
    },
    error: function (msg, xhr) {
        console.log("Failed: " + msg.status + ": " + msg.statusText);
    }

   });
   }
 </script>

I am running localhost via VisualStudio Code and Live Server.
I also tried just tossing a index.html file up onto the same server as the service, AND a server that has the same domain (note that I am using port 80 right now for everything so it is not an HTTPS issue, and the service is only allowed internal to our networks, so it is not public and yes my local machine can resolve the service URL in my browser).

But so far nothing has helped me to hit the call and get a response back.
It just gets caught with the error:

Access to XMLHttpRequest at ‘http://servicesite.somesite.com/ws/MyService.asmx?op=GetUserInfo’ from origin ‘http://MyCallingSite.somesite.com’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.

OR

Access to XMLHttpRequest at ‘http://servicesite.somesite.com/ws/MyService.asmx?op=GetUserInfo’ from origin ‘http://localhost:5501’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.

Any ideas is super helpful?

I can ask ChatGPT, but that has given me mixed results in the past and most of the time the same answers I have found elsewhere.

How to Change the Order of TradingView Header Buttons

I have added a chart reset button to the existing header buttons using the following code:

I am facing an issue where I want the reset button to be positioned in front of the previously created buttons.

Is there a way to achieve this?

let initialState = {
    width: '100%',
    height: '445',
    interval: '1D',
    symbol: coin_type + "_" + market_type,
    timezone: "Asia/Seoul",
    debug: false,
    container: "graph_view",
    library_path: "/chart2/charting_library/",
    locale: "ko",
    custom_css_url: '/css/exchange/chart.css',
    enabled_features: ["keep_left_toolbar_visible_on_small_screens"],
    disabled_features: [
        "use_localstorage_for_settings",
        "header_symbol_search",
        "header_compare",
    ],
    datafeed: {}
}

let widget = new TradingView.widget(initialState);

I learned from the documentation how to create a reset button in the header. However, this button always goes to the back.

widget.headerReady().then(function() {
    var button = widget.createButton();
    button.setAttribute('title', 'reset');
    button.addEventListener('click', function() {
        // Initial widget setup
        initializeWidget();
    });
    button.textContent = 'reset';
});

Thank you in advance.

How do I make this sorting functional?

Enter a movie title and your rating. Do this with several movies. when a-z in ‘sort’ dropdown is clicked, the list of movies should be reordered to be alphabetical.. z-a should make them ordered backwards.. low to high should sort from lowest rating to highest.. high to low should be from 10-1.

https://wrenjupiter.github.io/movies/

I don’t think I’ve ever worked with the sort method before and looking at the docs for it isn’t helping me understand how to implement it effectively.

I tried this:

 $("#az").on("click", function () {
      $("#movieList").innerHtml("");
      for (let movie of curMovies) {
        const sorted = $(movies).sort();
        $("movieList").append(sorted);
      }
    });

but it doesn’t do anything. I’m new to this and JavaScript is really hard for me. I’m supposed to use JQuery for it too. I’m using a custom bootstrap style sheet.

This is what I have so far

<h1 class="container heading bg-secondary text-light text-center">
      Movies!
    </h1>

    <div class="container text-center">
      <div class="">
        <div class="form-group rounded">
          <hr />
          <form id="form" class="row">
            <div class="input-group col-6">
              <label for="title" class="px-3 py-2">Enter a Title:</label>
              <input
                class="text-center form-control"
                type="text"
                id="title"
                name="title"
                placeholder="Deadpool"
                minlength="2"
              />
            </div>
            <div class="input-group col-6">
              <label for="rating" class="px-3 py-1">Enter a Rating:</label>
              <input
                class="text-center form-control"
                type="text"
                id="rating"
                name="rating"
                placeholder="10"
                minlength="0"
                maxlength="10"
              />
            </div>
            <div class="col-12 pt-4">
              <button
                type="sumbit"
                id="ad"
                class="btn-block shadow btn btn-success"
              >
                Add To List
              </button>
            </div>
          </form>
          <hr />
        </div>
      </div>
    </div>

    <div class="form-group" class="dropdown">
      <button
        class="btn shadow btn-primary dropdown-toggle ml-3"
        type="button"
        id="dropdownMenuButton"
        data-toggle="dropdown"
        aria-haspopup="true"
        aria-expanded="false"
      >
        Sort
      </button>
      <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
        <a class="dropdown-item id='az'" href="#">A - Z</a>
        <a class="dropdown-item id='za'" href="#">Z - A</a>
        <a class="dropdown-item id='lh'" href="#">Low to high</a>
        <a class="dropdown-item id='hl'" href="#">High to low</a>
      </div>
    </div>
    <div>
      <ul id="movieList"></ul>
    </div>
    <script
      src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
      integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"
      integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"
      integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
      crossorigin="anonymous"
    ></script>
  </body>
  <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
  <script>
    let id = 0;
    let movies = [];
    let ids = [id];

    $(document).ready(function () {
      $("#ad").on("click", function (evt) {
        evt.preventDefault();
        let title = $("#title").val();
        let rating = $("#rating").val();
        let rem = $(
          "<button class='rem shadow btn btn-danger btn-sm rounded-circle mx-2'>X</button>"
        );
        let curMovie = { title, rating, id };
        movies.push(curMovie);

        let li = $("<li>");
        li.id = id;
        li.html(curMovie["title"] + ": " + curMovie["rating"]);
        li.append(rem);
        //object wont stringify
        $("#movieList").append(li);
        console.log(curMovie);

        rem.on("click", function () {
          li.remove();
        });
        id++;
      });
    });

https://wrenjupiter.github.io/movies/

Stripe Checkout Session Django Subscription

I’m not a developer or software engineer. We’ve put together almost the entirety of a web app with the help of chatgpt. It’s worked great up to this point…

I would like to do the following:

Implement payments on my website through Stripe

Use the Stripe Checkout Session

Use the ui_mode = embedded option. I would like an embedded form not a redirect away from our website to Stripe's

Must use python django framework

The Stripe documentation has a guide that I’m sure is great for a flask app but I am really struggling to adapt it to django. https://stripe.com/docs/checkout/embedded/quickstart?lang=python

Would any be able to help translate the flask documentation to a django framework?