Uncaught ReferenceError and CORS Policy Error

Title:
Uncaught ReferenceError and CORS Policy Issue in XMLHttpRequest

Description:
I’m facing two issues in my web application:

Uncaught ReferenceError:

When clicking a button, I’m encountering “Uncaught ReferenceError: accessData is not defined,” although the function is declared in my JavaScript code.
CORS Policy Error:

I’m making an XMLHttpRequest to ‘http://localhost:8000/backend’ from my front-end code.
The request is blocked due to a CORS policy issue: “Access to XMLHttpRequest at ‘http://localhost:8000/backend’ from origin ‘null’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.”

server.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors'); // Add this line

const app = express();
const port = 8000;

app.use(cors()); // Enable CORS
app.use(bodyParser.json());

// Function to check if it's lunch break
function accessDataDuringLunchBreak() {
    const currentHour = new Date().getHours();
    return currentHour >= 12 && currentHour < 13;
}

app.post('/backend', (req, res) => {
    const action = req.body.action;

    if (action === 'delete_data') {
        if (accessDataDuringLunchBreak()) {
            res.status(403).json({ error: 'Access denied during lunch break' });
        } else {
            // Implement your logic to delete data here
            res.json({ message: 'Data deleted successfully' });
        }
    } else {
        res.status(400).send('Invalid action');
    }
});

app.listen(port, () => {
    console.log(`Server is running at http://localhost:${port}`);
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Data Access and Deletion</title>
</head>
<body>

<button onclick="accessData()">Access Data</button><br><br>
<button onclick="deleteData()">Delete Data</button>

<script>
function accessData() {
    if (accessDataDuringLunchBreak()) {
        alert("Access denied during lunch break!");
    } else {
        // Perform AJAX request for data access (you can implement this as needed)
        alert("Data accessed successfully!");
    }
}

function deleteData() {
    if (accessDataDuringLunchBreak()) {
        alert("Access denied during lunch break!");
    } else {
        // Perform AJAX request for data deletion
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    var response = JSON.parse(xhr.responseText);
                    alert(response.message);
                } else {
                    var error = JSON.parse(xhr.responseText);
                    alert(error.error);
                }
            }
        };

        xhr.open("POST", "http://localhost:8000/backend", true);
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.send(JSON.stringify({ action: 'delete_data' }));
    }
}

function accessDataDuringLunchBreak() {
    var currentTime = new Date();
    var currentHour = currentTime.getHours();

    // Assuming lunch break is between 12:00 PM and 1:00 PM
    return (currentHour >= 12 && currentHour < 13);
}
</script>

</body>
</html>

Is conditional awaiting misleading?

I’ve been toying with a JavaScript implementation similar to the one provided at https://developer.mozilla.org/en-US/docs/Web/API/Scheduling/isInputPending#examples and had a discussion with a colleague around whether the implementation might be misleading. Here is the abstracted-out version of the discussion.

For the purpose of this discussion, I assume that we’re inside an async function and don’t care about return values (i.e., we are interested only in side-effects and in the order in which things execute). These assumptions may not be strictly necessary but they simplify things for us.

Let’s say condition is a boolean, conditionalCodeBlock is a code block that we only want to run when condition is true (and for simplicity we can assume it returns a promise), and unconditionalCodeBlock is a block we want to execute (a) after the promise for conditionalCodeBlock evaluates if condition is true, (b) immediately and synchronously otherwise (i.e., without yielding).

In the context of the examples for isInputPending that I linked at the beginning, condition would be a check for navigator.scheduling.isInputPending, conditionalCodeBlock is just yielding (nothing too special happens inside there), and unconditionalCodeBlock is the code we actually want to execute if there is no pending input.

Here are two versions of the code that do this:

Long version without await:

if (condition) {
    conditionalCodeBlock.then(unconditionalCodeBlock);
} else {
    unconditionalCodeBlock;
}

Short version with await:

if (condition) {
    await conditionalCodeBlock;
}
unconditionalCodeBlock;

Both of them achieve the same thing effectively; the latter version is shorter because unconditionalCodeBlock doesn’t need to be repeated in the two cases.

However, the flip side of the second block is that it hides the fact that unconditionalCodeBlock is being invoked in different ways depending on whether condition is true or false: it’s invoked asynchronously if true and synchronously if false. A colleague pointed out that sweeping this complexity under the rug can be misleading and make it harder to reason about the code, so his preference would be for the more verbose first way.

I’m curious what people think about the pros and cons of the two ways of structuring the code, and what criteria they would use to decide which way is better in a specific situation.

Here is some more specific code (combining different code snippets that my colleague and I wrote into one giant code snippet) just to showcase that async/await in JavaScript works as I described, and provide a little more clarity on how things yield to each other:

var innerFunctionUsingPromise = (str) => {
  console.log('before promise evaluation: ' + str)
  return Promise.resolve(str)
    .then(v => {console.log('attached to promise: ' + v); return v;})
}

var innerFunctionNotUsingPromise = (str) => {
  console.log('no promise evaluation: ' + str);
}

var conditionalTrue = async () => {
  console.log('Pre: Conditional True')
  if (true) {
    console.log('before innerFunctionNotUsingPromise in conditionalTrue without await')
    innerFunctionNotUsingPromise('conditionalTrue without await')
    console.log('before innerFunctionUsingPromise in conditionalTrue without await')
    innerFunctionUsingPromise('conditionalTrue without await')
    console.log('before innerFunctionNotUsingPromise in conditionalTrue with await')
    await innerFunctionNotUsingPromise('conditionalTrue with await')
    console.log('before innerFunctionUsingPromise in conditionalTrue with await')
    await innerFunctionUsingPromise('conditionalTrue with await')
    console.log('Post: Conditional True Inside')
  }
  console.log('Post: Conditional True Outside')
}

var conditionalFalse = async () => {
  console.log('Pre: Conditional False')
  if (false) {
    console.log('before innerFunctionNotUsingPromise in conditionalFalse without await')
    innerFunctionNotUsingPromise('conditionalFalse without await')
    console.log('before innerFunctionUsingPromise in conditionalFalse without await')
    innerFunctionUsingPromise('conditionalFalse without await')
    console.log('before innerFunctionNotUsingPromise in conditionalFalse with await')
    await innerFunctionNotUsingPromise('conditionalFalse with await')
    console.log('before innerFunctionUsingPromise in conditionalFalse with await')
    await innerFunctionUsingPromise('conditionalFalse with await')
    console.log('Post: Conditional False Inside')
  }
  console.log('Post: Conditional False Outside')
}

console.log('Pre: Global')
conditionalTrue()
conditionalFalse()
console.log('Post: Global')

This is the result:

Pre: Conditional True
before innerFunctionNotUsingPromise in conditionalTrue without await
no promise evaluation: conditionalTrue without await
before innerFunctionUsingPromise in conditionalTrue without await
before promise evaluation: conditionalTrue without await
before innerFunctionNotUsingPromise in conditionalTrue with await
no promise evaluation: conditionalTrue with await
Pre: Conditional False
Post: Conditional False Outside
Post: Global
attached to promise: conditionalTrue without await
before innerFunctionUsingPromise in conditionalTrue with await
before promise evaluation: conditionalTrue with await
attached to promise: conditionalTrue with await
Post: Conditional True Inside
Post: Conditional True Outside

The above code can help verify these things:

  • As expected, none of the stuff inside if (false) in conditionalFalse gets triggered. This also means that the code after the if (false) executes immediately and synchronously as there is no yielding happening in that case.
  • All functions, whether using await or not, start executing immediately when invoked.
  • In the case of an awaited function, the caller yields the microtask queue, so even when the awaited function completes (and even if it doesn’t include any promise evaluation!) the control doesn’t immediately return to the caller; everything that is in the queue at the time of yielding gets executed first.
  • Similarly, any time we get to a Promise.resolve, the microtask queue is yielded, so the code inside will get executed after everything else in the queue at the time of yielding.

How can I access and modify a website’s HTML locally using code?

I’m trying to make a program that looks through the website you’re on, and censors bad words. I can use CTRL-shift-c to pull up Chrome Dev tools, and go through each element and erase the words I don’t want easily enough, but how might I do that with code?

I understand a little about web-scrapping using beautifulsoup, so finding the no no words should be simple enough, but I have no idea how to give that program the ability to edit the HTML of the website.

I’m thinking there are two solutions; I can scrape each element for its text, and then re-insert the new text in its place, or I would have to snatch a copy of the website’s HTML, have my code scan and edit it, and then upload this new HTML in its place?

The more I think about it the less feasible it seems.

Thanks for your help.

how to implement validate password with confirm password value (the reverse) in Javascript

Implemented something similar to this from here only but what if the user tries to edit the password field to match the confirm password field to get rid of errors.

function validarPasswordConfirm(password, confirmPassword) {

  var typedpassword = document.getElementsByName('password').value;
 
  var confirmTypedPassword = document.getElementsByName('passwordConfirm').value;

  if(typedpassword !== confirmTypedPassword) {
    return { value: false, text: 'Passwords are not the same.' }
  } else {
    return { value: true, text: '' }
  }
}

Expecting a code snippet for reverse validation

Why do I get HTML code when I tried to use useQuery?

I’m try to learn TanstackQuery, when I tried to console.log my useQuery this is what I get

This is my query statement.

 const { isPending, error, data, isFetching } = useQuery({
    queryKey: ['repoData'],
    queryFn: () =>
      axios
        .get('"http://localhost:5000/api/result/getCEIS')
        .then((res) => res.data),
  })

  console.log(data)

I get the result of html file

<!doctype html>
<html lang="en">
  <head>
    <script type="module">
import RefreshRuntime from "/@react-refresh"
RefreshRuntime.injectIntoGlobalHook(window)
window.$RefreshReg$ = () => {}
window.$RefreshSig$ = () => (type) => type
window.__vite_plugin_react_preamble_installed__ = true
</script>

    <script type="module" src="/@vite/client"></script>

    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + React</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx?t=1706065018396"></script>
  </body>
</html>

Listen for all ways a user might attempt to perform an undo

I want to be able to run code every time the user attempts to make an undo. For example, the user might use a keyboard shortcut like ctrl+z, they might right click and select “Undo” from a context menu, they might tap the “undo” button on a mobile keyboard, etc. There are many ways a user can make an undo command, and I’d like to listen to all of them.

I found this practically identical question but the answer will not work for my use case because it listens strictly for the input event – which only fires when the user’s undo attempt actually modifies the content of an input element. I don’t want my code to only run when the user makes a successful undo on an input element – I want it to run every time they attempt an undo, whether it actually resulted in a change or not.

Currently I’m simply listening for ctrl+z and the “Undo” event.key value that’s described here in a keydown event listener. The problem with this is that users may have changed their keyboard shortcut from ctrl+z to something else, they may attempt an undo from the right-click context menu, some mobile keyboard implementations may show “undo” buttons which do not fire key events at all, or many other potential situations which I’m not aware of but of which I’m sure there are many.

I know there are cut, copy, and paste events that allow you to do exactly what I’m looking for in those situations, but nothing like that seems to exist for undos or redos.

JavaScript element html wrong

The simple code below gives me an interesting output

     const dropdownElements = document.querySelectorAll('.modify-response-dropdown-content');

     dropdownElements.forEach((element) => {
        Logger.log('1.element.style.display', element.style.display)
        Logger.log('2.element.outerHTML', element.outerHTML)
        Logger.log('3.element', element)
     );

This is the log:

 1.element.style.display block
2.element.outerHTML <div class="modify-response-dropdown-content" style="display: block;">

            <button type="button">Longer</button>
            <button type="button">Shorter</button>
            <button type="button">Simpler</button>
            <button type="button">Casual</button>
            <button type="button">Formal</button>
            <button type="button">Serious</button>

    </div>
3.element <div class=​"modify-response-dropdown-content" style=​"display:​ none;​">​<button type=​"button">​Longer​</button>​<button type=​"button">​Shorter​</button>​<button type=​"button">​Simpler​</button>​<button type=​"button">​Casual​</button>​<button type=​"button">​Formal​</button>​<button type=​"button">​Serious​</button>​</div>​

The accurate one is display ‘none’ and the div is not showing on the page. I don’t understand why it changes to block when called in JS. I tested on multiple browsers and it’s the same.

Any idea how to fix?

Thank you,

Bilel

How do I make a vibration in JavaScript without explicit interaction on a mobile browser?

I get a message from Back-end with FastApi.
There is no problem about sending message.
And now I want to make vibrate in mobile browser.
How can I make a vibration?

window.navigator.vibrate() didn’t work.
I asked to chat-gpt, but answer didn’t for solving problem.
“In general, browsers can’t perform vibrations without explicit interaction from the user”

socket.addEventListener("message", function(event) {
    console.log("received message: ", event.data);
    const data = JSON.parse(event.data)
    const anybodyThere = data.anybodyThere;

    // SHOW STATUS WITH PIR SENSOR DATA
    if (anybodyThere === 1) {
        //! want to make vibrate 
    } else {
        //! want to remove vibrate
    }
});

How to avoid swipeup while doing pinch zoom with javascript

I’m facing the problem of swipe up is happening when doing pinch zoom on image

Question : how to avoid swipeup while doing pinch zoom ?

As you know we do pinch zoom with 2 fingers simultaneously but swipeup with a single finger

Here is what my current code looks like :

          let swipeUpY;
           const zoomContainer = document.getElementById('zoomContainer');
          zoomContainer.addEventListener('touchstart', (e) => {
            // Record the starting Y-coordinate when the touch starts
            swipeUpY = e.touches[0].clientY;
          });


zoomContainer.addEventListener('touchend', (e) => {
            // Calculate the change in Y-coordinate
            const deltaY = e.changedTouches[0].clientY - swipeUpY;

            const swipeUpThreshold = 50;
            const swipeDownThreshold = -50;

            if (deltaY < swipeDownThreshold) { // Swipe Up
              console.log('Swipe Up Detected!');
            } else if (deltaY > swipeUpThreshold) { // Swipe down
              console.log('Swipe Down Detected!');
            }
          });
.image-preview-with-zoom{
   width: 600px;
   height: 400px;
}

.image-preview-with-zoom img{
   width:100%;
   height:100%;
}
<div class="image-preview-with-zoom" id="zoomContainer">
    <img src="https://placehold.co/600x400/orange/white"/>
</div>

component receives “columns” array from App.vue; Bootstrap dropdown Button options should be all names in that Array

In the header of the modal, users should be able to select the column in which the new task will be created using a selector with the ID “modalSelectColumn.” For this purpose, the component receives the “columns” array from App.vue and displays the names of all columns as selectable options.

this is a shortened version of the Array in the App.vue Component:

function loadColumns() {
columns.value = [
    {
        id: 0,
        name: 'To Do',
        tasks: [
            { ... },
            { ... },
            { ...}
        ]
    },
    {
        id: 1,
        name: 'In Progress',
        tasks: [
            { ...},
            { ...}
        ]
    },
    {
        id: 2,
        name: 'Done',
        tasks: [
            { ...},
            { ...},
            { ...] }
        ]
    }
]
}

This is how I tried to solve it in the select tag:

<select class="form-select" aria-label="Default select example" style="max-width: 150px;" id="modalSelectColumn">
<option v-for="column in columns" :value="column" :key="column">{{ column.value }}</option>

and i also did defineprops in the script setup from the modal.vue component:

defineProps({
        columns: {
            type: Array,
            required: true
        }
    });

What am I doing wrong?

Why isn’t my home.js displaying anything in the browser?

I am enrolled in a full stack web development course and currently learning react on the side to build a project for a portfolio in hopes of getting into a front end web developer position.

Found this 2 year old tutorial in which I thought was a decent start to learn: https://www.youtube.com/watch?v=QwarZBtFoFA&t=700s.

I’ve tried and noticed the following:

  1. The HTML doesn’t show up in the browser inspect
  2. locahost:3000 (nothing)
  3. localhost:3000/Home (nothing)
  4. I’ve followed the tutorial (rewatching if i missed any steps)
  5. compared my code to the tutorials’ repository code
  6. started from scratch twice (for Home.js/App.js)
  7. changed to <Route path=”/” exact component={} />
  8. the only thing I’m getting the following error on browser (nothing on VSC):

Warning: ReactDOM.render is no longer supported in React 18. Use createRoot instead. Until you switch to the new API, your app will behave as if it’s running React 17. Learn more: https://reactjs.org/link/switch-to-createroot

AND

No routes matched location “/Home”

I’ve updated and checked the version for react and says 10.2.4, haven’t been able to find out whether it’s version React 18 or less. How do I implement the createRoot to the existing documents I have?

T.I.A

pages/Home.js

import React from 'react';
import { Link } from 'react-router-dom';


function Home() {
    return (
        <div className='home'>
            <div className='headerContainer'>
                <h1>Heavy Hitters Gym</h1>
                <p>WHERE YOU GET FIT</p>
                <Link to="/Menu">
                    <button> JOIN NOW </button>
                </Link>
            </div>
        </div>
    );
}

export default Home;

src/App.js

import React from 'react';
import Home from './pages/Home';
import './App.css';
import Navbar from './components/Navbar';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';

function App() {
  return (
    <div className="App">
      <Router>
        <Navbar />
        <Routes>
          <Route path="/" exact component={Home} />
        </Routes>
      </Router>
    </div>


  );
}

export default App;

src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import reportWebVitals from './reportWebVitals';

const rootElement = document.getElementById("root");
ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

HTML Javascript on click button for top 10 not working

I just started learning js html and css and I’m trying to figure out how to launch a web page!

This is my current javascript function code in my app.js file that pulls the top 10 based on the basic_monthly_median!

The js code is currently taking top 10 for the entire dataset but I want to take the top 10 for the year that the user inputs on the webpage and I need help with this part!!

Also!! I want to launch one web page that asks the user for input of ‘Year’ and put a ‘See results’ button that call the function that I need help with above ^ after clicked, what is the html code for the input and button? But I want to display it in a web component. How do I do that?

Javascript app.js file code:

async function displayTop10EmploymentData() { 
  try { 
    const allEmploymentData = await loadEmploymentSurveyData(); 
 
    if (!allEmploymentData) {  
      console.error('Unable to fetch employment survey data.'); 
      return; 
    } 
    const sortedData = allEmploymentData.sort((a, b) => b.basic_monthly_median - a.basic_monthly_median); 
 
    // Take the top 10 records 
    const top10Data = sortedData.slice(0, 10); 
 
    // Display the top 10 records 
    console.log('Top 10 Employment Data:', top10Data); 
  } catch (error) { 
    console.error('Error displaying top 10 employment data:', error); 
  } 
} 
 
// Call the function to fetch and display top 10 data 
displayTop10EmploymentData();

HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Top 10 Employment Data</title>
</head>
<body>

  <h1>Top 10 Employment Data</h1>

  <form id="yearForm">
    <label for="year">Enter Year:</label>
    <input type="number" id="year" name="year" required>
    <button type="button" onclick="submitForm()">Submit</button>
  </form>

  <script src="app.js"></script>

</body>
</html>

I also tried using the input and button on click but I’m not sure how to link everything up

exception error on server iis input string not in correct format

I work on asp.net MVC application . I get error input string not in correct format

i don’t know what is the reason of this issue and which line give me this issue

on local pc issue not happen but on iis publish site web app it happen

so how i know reason of this issue please

and can i do some enhancement on code to display more clear message or prevent this error from happen

And which line generate issue

if i write some parsing on code with wrong way please tell me to correct it

my action code as below

public class ResignationRequester
  {
  [Display(Name = "Employee No : ")]   [Required,]   
public int EmpID { get; set; }
[Display(Name = "Line Manager: ")]
public int? LineManager { get; set; }
  }

[HttpPost]
  public JsonResult RequesterIndex(ResignationRequester resignationRequester)
  {
      dynamic responseData = new ExpandoObject();
      responseData.success = false;
      responseData.message = "";
      try
      {
          var filenumber = resignationRequester.EmpID;
          if (Session[SessionKeys.UserCode] != null)
          {
              JDEUtility jde = new JDEUtility();
       
              resignationRequester.EmpID = Convert.ToInt32(Session[SessionKeys.UserCode]);
                        
           
             


              if (ModelState.IsValid)
              {

                  
                 
                 
                  if (Convert.ToString(resignationRequester.LineManager).Length < 6 && !string.IsNullOrEmpty(resignationRequester.LineManager.ToString()))
                  {
                      responseData.success = false;
                      responseData.message = "Length Line Manager Must Be equal 6 or More";
                      return Json(responseData);

                  }
                  
                  if (Convert.ToInt32(resignationRequester.EmpID) == Convert.ToInt32(resignationRequester.DirectManager) &&
  Convert.ToInt32(resignationRequester.EmpID) == Convert.ToInt32(resignationRequester.LineManager)
  && !string.IsNullOrEmpty(Convert.ToString(resignationRequester.LineManager)) && !string.IsNullOrEmpty(Convert.ToString(resignationRequester.DirectManager)))
                  {
                      responseData.success = false;
                      responseData.message = "Requester Have Same Number of Manager";
                      return Json(responseData);

                  }
                  if (!string.IsNullOrEmpty(Convert.ToString(resignationRequester.LineManager)))
                  {
                      responseData.success = false;
                      responseData.message = "Line Manager Name Blank";
                      return Json(responseData);

                  }
                 

                 
                 



                 
               
                  if (string.IsNullOrEmpty(ViewBag.errorMsg))
                  {
                      responseData.success = true;
                      responseData.message = "Resignation Submission form Created successfully";
                      

                      return Json(responseData);
                  }



              }
              
          }
         
      }
     
      catch (System.FormatException ex)
      {
          responseData.success = false;
          responseData.message = ex.Message;
      }
      return Json(responseData);
      
  }

on UI View this is what i do

$("#txtLineManagerId").autocomplete({
            source: function (request, response) {
                var searchText = $("#txtLineManagerId").val();
                console.log("search text" + searchText)
                $.ajax({
                    url: '@Url.Action("GetAllEmployeeBasedSearchText", "Resignation")',
                    data: { searchText: searchText },
                    method: "GET",
                    dataType: "json",
                    success: function (data) {
                        if (!data.length) {
                            var result = [
                                {
                                    label: 'No matches found',
                                    value: response.term
                                }
                            ];
                            response(result);
                        }
                        else {
                           
                            response($.map(data, function (item) {
                                
                                return {
                                    
                                    label: "File No : " + item.EmployeeID + " - " + "Name :" + item.EmployeeName + " - " +
                                        "Designation : " + item.Designation, value: item.EmployeeID,
                                    employeeName: item.EmployeeName,
                                    designation: item.Designation
                                };

                            }))
                        }
                    }
                });
            },
            position: { my: "right top", at: "right bottom" },
            appendTo: '#searchContainer',
            select: function (event, ui) {
              
                $("#LineManagerName").val(ui.item.employeeName);
             
            },
            minLength: 2,
          
        }).data("ui-autocomplete")._renderItem = function (ul, item) {
            console.log("after autocomplete" + item);
            
            return $("<li>")
                .append("<div>File No: " + item.value + "<br/>Name: " + item.employeeName + "<br/>Designation: " + item.designation + "</div>")
                .appendTo(ul);
            
        };

 <div class="form-group col-md-6">
     <div class="col-md-5">
         @Html.LabelFor(model => model.LineManager, htmlAttributes: new { @class = "control-label" })


     </div>

     <div class="col-md-7">
         @Html.EditorFor(model => model.LineManager, new
         {
             htmlAttributes = new
             {
                 @class = "form-control"
        ,
                 id = "txtLineManagerId"
             }
         })
         <div id="searchContainer">

         </div>
 
        
     </div>
 </div>

Change button twice

I want to change the button options when clicked, but I can’t figure out how to do it after it changes once. I want to list the next choices for the next question after I click either the yes or no option.

document.getElementById("pack1").onclick = function() {
    nextQuestion();
    fail++;
    choicesElement.innerHTML = "<button id='feed1'>Yes</button> <br><button id='feed2'>No</button>";
};

document.getElementById("pack2").onclick = function() {
    nextQuestion();
    fail++;
    choicesElement.innerHTML = "<button id='feed1'>Yes</button> <br><button id='feed2'>No</button>";
};

document.getElementById("pack3").onclick = function() {
    nextQuestion();
    fail++;
    choicesElement.innerHTML = "<button id='feed1'>Yes</button> <br><button id='feed2'>No</button>";
};

was my first attempt and I after I tried:

//variables
const spanElement = document.querySelector(".span");
const spanElement1 = document.querySelector(".span1");
const spanElement2 = document.querySelector(".span2");
const spanElement3 = document.querySelector(".span3");
const choicesElement = document.getElementById("choicespan");
const btnElement = document.querySelector(".choices");
let success = 0;
let fail = 0;
let index = 0;
let index1 = 0;
const myList = ["The leader of your group says to feed your horses before you leave. Do you feed them?", "Your leader, John Bartleson, has told you that it's time to start your journey. You're on the trail, but your son has to go to the bathroom; what do you do?", "Your daughter complains of hunger. What do you do?", "You reach a stop shortly, and John announces, 'Alright, cook meals, hunt, anything. Be back before dawn and be ready to go.'", "You sleep until five in the morning when you are woken up by a cow bell sound. At which point there is someone telling everyone to get up and ready. Your son is groaning about having to wake up what do you do?", "After much more travel, your group comes upon a boulder blocking your path."];

//first question and options
spanElement.textContent = ">-----------------<";
spanElement1.textContent = "You are in Independence, Missouri. You and other fur traders and trappers are going to explore the northwest. What do you pack?";
choicesElement.innerHTML = "<button id='pack1' class='choices'>Lantern</button> <br><button id='pack2' class='choices'>Lantern and butter churn</button> <br><button id='pack3' class='choices'>Butter churn</button> <br><button id='pack4' class='choices'>Box</button> <br><button id='pack5' class='choices'>Barrel</button> <br><button id='pack6' class=choices'>Butter churn and box</button> <br><button id='pack7' class='choices'>Butter churn and barrel</button> <br><button id='pack8' class='choices'>Lantern and box</button> <br><button id='pack9' class='choices'>Lantern and barrel</button> <br><button id='pack10' class='choices>Box and barrel</button> <br><button id='pack11' class='choices'>Pot</button> <br><button id='pack12' class='choices'>Medicine, water, and other bottled liquids</button> <br><button id='pack13' class='choices'>Pot and box</button> <br><button id='pack14' class='choices'>Pot and barrel</button> <br><button id='pack15' class='choices'>Pot and lantern</button> <br><button id='pack16' class='choices'>Pot and butter churn</button> <br><button id='pack17' class='choices'>Pot and medicine</button> <br><button id='pack18' class='choices'>Medicine and box</button> <br><button id='pack19' class='choices'>Medicine and barrel</button> <br><button id='pack20' class='choices'>Medicine and lantern</button> <br><button id='pack21' class='choices'>Medicine and butter churn</button> <br><button id='pack22' class='choices'>All</button>";

//function to check what the question is and change it
function nextQuestion() {
    if (index < myList.length) {
        document.getElementById("span1").textContent = myList[index];
        index++;
    };
};

//change choices
function changeQuestion() {
    nextQuestion();
    choicesElement.innerHTML = "<button id='feed1' class='choices'>Yes</button> <br><button id='feed2' class='choices'>No</button>"
};


//where the problem arises
function changeQuestionAgain() {
    if (changeQuestion() == true) {
        nextQuestion();
        choicesElement.innerHTML = "<button id='bath1' class='choices'>Pull over</button> <br><button id='bath2' class='choices'>Let him go in the pot</button> <br><button id='bath3' class='choices'>Tell him to hold it until the whole group stops</button>";
    };
};

//check which answer and add points
btnElement.addEventListener("click", () => {
    changeQuestion();
    if($("div").attr("id") == "pack22" || "feed1") {
        success++;
    };
});

which is closer but still doesn’t work

Here is my html and css by the way:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Oregon Trail</title>
        <link rel="stylesheet" href="styles.css">
    </head>
    <body>
        <div id="game-container">
            <h1>Oregon Trail</h1>
            <h1><span class="span"></span></h1>
            <h2><span class="span2"></span></h2>
            <h2><span class="span3"></span></h2>
            <h2><span id="span1" class="span1"></span></h2>
            <h2><span id="choicespan" class="choices"></span></h2>
        </div>
        <script src="script.js"></script>
    </body>
</html>
body {
    font-family: Georgia, 'Times New Roman', Times, serif;
    text-align: center;
    background-color: black;
    color: lime;
}

#game-container {
    max-width: 600px;
    margin: 30px;
    padding: 10px;
    border: 2px solid #ccc;
    border-radius: 10px;
}

button {
  background-color: transparent;
  color: lime;
  border: 0;
  background-image: linear-gradient(
  to bottom,
  transparent 0%,
  transparent 90%,
  lime 90%,
  lime 100%
  );
  background-repeat: no-repeat;
  background-size: 0% 100%;
  background-position-x: right;
  
  transition: background-size 300ms;
}

button:hover {
  background-size: 100% 100%;
  background-position-x: left;
}

Server client ajax calls now requiring json?

I have an app running for over 6-7+ years working perfectly fine built with jquery and php. There are sections of the app where I call the PHP server using a simple post query.

$("#btn").on("click",function(e){
       e.preventDefault();
       var el = $(this),
           oid = el.data("id");
       $.post("/ajax/get",
           {
               id: id
           },
           function(data){
               if(data == "good"){
                    
                   /// DO something

                   } else {
                       // SHOW ERROR
                   }
               });
   });

and on the php function side it will just echo a string back to the client.

function get(){

  /// get id and do something conditionally and return string

  ///....

  echo 'good';
}

This used to work. It worked perfectly fine for a long time.
But now for some reason, this no longer works anymore. After sometime I realized I had to change this to return json_encode() instead.

function get(){

  /// get id and do something conditionally and return string

  ///....
  $data = array('status' => 'good');
  echo json_encode($data);
  exit;
}

Does anybody know the reason why this all of a sudden is an issue and possibly directly me to where I can learn about these changes. I’m assuming they are some kind of new browser updates.