Reload does not change post state

I have a problem where i want to reload the page on submit,
I did this with the simple script function shown below, however the echo’d “hello” does not disappear when I reload. Is there a reload function that changes the state of my submit post and the “hello” is no longer appearing

<html lang="en">

   <body>
   <form method="post">
                            <button class="btn-login" type="submit" name="submit" >Sign in</button>
</form>
      <?php
if(isset($_POST['submit'])){
    echo "hello";
    echo "<script>window.location.reload(true)<script>";
}
?>

Javascript – Uncaught TypeError: Failed to execute ‘appendChild’ on ‘Node’: parameter 1 is not of type ‘Node’

I have this code in my vue component

<template>
  <div class="container-fluid p-0">
    <div class="row m-0">
      <div class="col-12 vh-100 p-0" @drop="drop($event)" @dragover.prevent id="camView">
        <canvas class="position-absolute top-0 end-0" ref="targetImg" id="targetImg"></canvas>
        <div class="position-absolute" id="selection" draggable="true" @dragstart="drag($event)"></div>
        <img src="@/assets/lu.jpeg" class="img-fluid" id="srcImg" ref="srcImg">
      </div>
    </div>
  </div>
</template>

<script>

export default {
  name: 'DropView',
  data() {
    return {

    }
  },
  mounted() {
 
  },
  methods: {
    drag(e) {
      console.log(e)
      e.dataTransfer.setData('text', e.target.id);
    },
    drop(e) {
      console.log(e)
      e.preventDefault();
      let data = e.dataTransfer.getData('text');
      console.log(data)
      let box = document.getElementById(data)
      console.log(box)
      e.target.appendChild(box);
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.col-12 {
  #selection {
    width: 360px;
    height: 240px;
    border-style: dashed;
    border-width: 1px;
    border-color: white;
    background-color: transparent;
    z-index: 1;
  }
  #target-img {
    overflow: hidden;
    width: 320px;
    height: 240px;
    z-index: 1;
  }
  #srcImg {
    height: 100%;
    display: block;
    width: 100%;
    object-fit: cover;
  }
}
</style>

I’m trying to use drag and drop to moove a div that is positioned on top of an image. I’m able to start the drag operation but when I release the div into another position I will get this error in console

Vue warn]: Unhandled error during execution of native event handler 
Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.

I’ve noticed that the div will disappear and is not mooved. Is there any fix?

React render message to stay at the bottom

Currently working on a 1:1 live chat messenger. when i send a message its shows up at the bottom of chat where i want it to, but upon page refresh it returns to the top of the messenger. How do i set it so newest message is always at the bottom? heres some code i believe the problem is in setActiveChat or or addMessageToConversation.

const sendMessage = (data, body) => {
    socket.emit("new-message", {
      message: data.message,
      recipientId: body.recipientId,
      sender: data.sender,
    });
  };

  const postMessage = async (body) => {
    try {
      const data = await saveMessage(body);

      if (!body.conversationId) {
        addNewConvo(body.recipientId, data.message);
      } else {
        addMessageToConversation(data);
      }
      sendMessage(data, body);
    } catch (error) {
      console.error(error);
    }
  };
  const addNewConvo = useCallback(
    (recipientId, message) => {
      setConversations(previousState => previousState.map(convo => {
        if (convo.otherUser.id === recipientId) {
          convo.messages.push(message)
          convo.latestMessageText = message.text;
          convo.id = message.conversationId;
          return convo
        }
        return convo
      }))
    },
    [setConversations],
  );

  const addMessageToConversation = useCallback(
    (data) => {
      // if sender isn't null, that means the message needs to be put in a brand new convo
      const { message, sender = null } = data;
      if (sender !== null) {
        const newConvo = {
          id: message.conversationId,
          otherUser: sender,
          messages: [message],
        };
        newConvo.latestMessageText = message.text;
        setConversations((prev) => [newConvo, ...prev]);
      }
      conversations.forEach((convo) => {
        if (convo.id === message.conversationId) {
          const convoCopy = { ...convo };
          convoCopy.messages.push(message);
          convoCopy.latestMessageText = message.text;
          return convoCopy;
        } else {
          return convo;
        }
      });
      setConversations([...conversations]);
    },
    [setConversations, conversations],
  );


  const setActiveChat = useCallback((username) => {
    setActiveConversation(username);
  }, []);



 

Indicate the refresh status of a backend on a webpage

I have a web application which periodically connects to some 3rd party API, does some calculations, and then displays the latest result when the relevant page is requested. The backend calculation happens every 10 seconds or so, unless there is a problem (e.g. 3rd party API doesn’t respond).

I’d like to be able to show the “health status” of these “under the hood” operations.

So far I’ve simply been writing the latest calculate time on the page, e.g. “Updated: 2022-05-06 10:41:26”. This allows the user to see how stale the data is.

However, this is not user-friendly as it requires the user to look at the time, look at his own clock, and make a manual check.

I’d like to be able to say “Last update: N seconds ago”, and let the N update once a second via javascript. But how should this number be calculated? Possible options:

  1. Assume page load latency as acceptable margin of error, send across the initial value of N and just add 1, every second. (Possibly a bit inaccurate)
  2. Send across an actual timestamp and then let the local machine calculate it. (Possibly just wrong if user clock is wrong)
  3. Something else?

How do I print data from SQL database to HTML page in Python Flask?

I am building a web application in Python Flask where the user can create an account and select one or more tourist attractions in the city of Boston. Here is the HTML (the user can select one or more attractions from categories “start”, “waypoints”, and “end”):

<select id="start" name="start">
            <option value="Arnold Arboretum, Boston, Massachusetts">Arnold Arboretum</option>
            <option value="Beacon Hill, Boston, Massachusetts">Beacon Hill</option>
            <option value="Boston Public Garden">Boston Public Garden</option>
            <option value="Boston Public Library">Boston Public Library</option>
            <option value="Boston Public Garden">Boston Public Garden</option>
            <option value="Boston Public Library">Boston Public Library</option>
            <option value="Chinatown, Boston">Chinatown</option>
            <option value="Fanueil Hall, Boston">Fanueil Hall</option>
            <option value="Fenway Park, Boston">Fenway Park</option>
            <option value="Isabella Steward Gardner Museum, Boston">Isabella Steward Gardner Museum</option>
            <option value="Museum of Fine Arts, Boston, Massachusetts">Museum of Fine Arts</option>
            <option value="Museum of Science, Boston, Massachusetts">Museum of Science</option>
            <option value="New England Aquarium">New England Aquarium</option>
            <option value="North End, Boston">North End</option>
            <option value="TD Garden, Boston">TD Garden</option>
            <option value="USS Constitution, Boston">USS Constitution</option>
   </select>
<select multiple id="waypoints" name="waypoints">
            <option value="Arnold Arboretum, Boston, Massachusetts">Arnold Arboretum</option>
            <option value="Beacon Hill, Boston, Massachusetts">Beacon Hill</option>
            <option value="Boston Public Garden">Boston Public Garden</option>
            <option value="Boston Public Library">Boston Public Library</option>
            <option value="Bunker Hill Monument, Boston">Bunker Hill Monument</option>
            <option value="Chinatown, Boston">Chinatown</option>
            <option value="Fanueil Hall, Boston">Fanueil Hall</option>
            <option value="Fenway Park, Boston">Fenway Park</option>
            <option value="Isabella Steward Gardner Museum, Boston">Isabella Steward Gardner Museum</option>
            <option value="Museum of Fine Arts, Boston, Massachusetts">Museum of Fine Arts</option>
            <option value="Museum of Science, Boston, Massachusetts">Museum of Science</option>
            <option value="New England Aquarium">New England Aquarium</option>
            <option value="North End, Boston">North End</option>
            <option value="TD Garden, Boston">TD Garden</option>
            <option value="USS Constitution, Boston">USS Constitution</option>
        </select>
<select id="end" name="end">
            <option value="Arnold Arboretum, Boston, Massachusetts">Arnold Arboretum</option>
            <option value="Beacon Hill, Boston, Massachusetts">Beacon Hill</option>
            <option value="Boston Public Garden">Boston Public Garden</option>
            <option value="Boston Public Library">Boston Public Library</option>
            <option value="Bunker Hill Monument, Boston">Bunker Hill Monument</option>
            <option value="Chinatown, Boston">Chinatown</option>
            <option value="Fanueil Hall, Boston">Fanueil Hall</option>
            <option value="Fenway Park, Boston">Fenway Park</option>
            <option value="Isabella Steward Gardner Museum, Boston">Isabella Steward Gardner Museum</option>
            <option value="Museum of Fine Arts, Boston, Massachusetts">Museum of Fine Arts</option>
            <option value="Museum of Science, Boston, Massachusetts">Museum of Science</option>
            <option value="New England Aquarium">New England Aquarium</option>
            <option value="North End, Boston">North End</option>
            <option value="TD Garden, Boston">TD Garden</option>
            <option value="USS Constitution, Boston">USS Constitution</option>
        </select>

And then hit the submit button:

<input type="submit" id="submit" value="Submit"/>

In Flask, I have built a functionality which saves the user’s selected options into a variable that is stored in an SQL database:

@app.route("/", methods=['GET','POST'])
@login_required
def index():
    if request.method == "GET":
        return render_template("attractions5.html")
    else:
        start = (request.form.get['start'])
        waypoints = (request.form.get['waypoints'])
        end = (request.form.get['end'])
        route = Route(start=start, waypoints=waypoints, end=end)
        db.execute("INSERT INTO routes (userid, route) VALUES (?, ?)", userid=session["user_id"], route=route)
        return redirect("/")

From here, I want to be able to print the stored values back into the HTML webpage, such that if the user were to login to their account at a later time, their selections would be maintained. However, I don’t know how to implement this functionality into Flask. I’m also not sure if my current implementation in Flask is correct as far as saving the user’s selections. Let me know if I should clarify anything else – thanks in advance!

How to use “oneOf” in this schema?

I’d like to have either A or B, but not both (mutual exclusive.)

I have to use whatever is avaliable in Draft 3, even though it says 4 on the top. Reason being, when using array for “required”, it throws an error that it can’t convert an array to a boolean. If I remove arrays without putting that I’m using draft 4 [Newtonsoft.Json.Schema.Extensions]::IsValid does not validate. It returns “true” willy nilly.

Yes, I have to use an obsolete Newtonsoft.

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "description": "",
  "type": "object",
  "additionalProperties": false,
  "properties": {
    "SearchCriteria": {
      "type": "array",
      "uniqueItems": true,
      "minItems": 1,
      "required": true,
      "items": {
        "type": "object",
        "additionalProperties": false,
        "properties": {
          "A": {
            "type": "string",
            "minLength": 1,
            "pattern": "^[^\s]*$"
          },
          "B": {
            "type": "array",
            "items": {
              "type": "string",
              "minLength": 1,
              "pattern": "^[^\s]*$",
              "enum": ["One", "Two"]
            },
            "minItems": 1
          },
          "C": {
            "type": "string",
            "required": true,
            "minLength": 2
          },
          "D": {
            "type": "array",
            "required": true,
            "items": {
              "type": "string"
            },
            "minItems": 1,
            "uniqueItems": true
          }
        }
      }
    }
  }
}

Pass Value from input to Fetch API Headers in JavaScript

How can I pass a value from text input box to a variable and use it in my Fetch API call>

I don’t want to have a fixed header in my fetch call. I want to be able to pass a value from the UI text input to the headers variable and use it in my fetch call. The x-tlc-auth-token value will be whatever I type in/submit in the UI text box. The x-tlc-people value is fixed and doesn’t change.

This is what I have, but nothing changes when I do this.


<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <input type="text" placeholder="Submit Token" id="myToken">
  <button type="button">Submit</button>

<script> 
function DisplayResults(url) {
  const tokenVal = document.getElementById("myToken").value;
  const headers = {
    "x-tlc-auth-token": +tokenVal,
    "x-tlc-people": "all-access",
  };

  fetch(url, { headers })
    .then((res) => (res.ok ? res.json() : Promise.reject(res)))
    .then((data) => {
        results.append(DisplayResults(data));
      }
    })
    .catch(console.error);
}

// Get Token input value

const myToken = document.getElementById("myToken");

myToken.addEventListener("onclick", document.getElementById(myToken).value);



</script>

</body>

</html> 

This is what I would have in the header variable if I was using fixed values:

  const headers = {
    "x-tlc-auth-token":
    "89009738-783902-7884003384",
  "x-tlc-people": "all-access",

  }

event listener’s event is being used more than once

I have this weird bug that whenever I want to add an item/card to the list and I cycle between clicking the text input and then clicking outside of it, the list won’t add only one item but the number of times I pressed in and out.

enter image description here

const main = document.querySelector('main')

main.addEventListener('click', (e) => {

  // Name a group

  if (e.target.id === 'groupNameInput') {
    console.log(e.target)
    let groupNameInput = e.target
    groupNameInput.addEventListener('change', () => {
      let groupName = groupNameInput.parentElement
      console.log(groupNameInput.value)
      groupNameInput.style.display = 'none'
      groupName.innerText = `${groupNameInput.value}`
      groupName.parentElement.lastElementChild.classList.remove('notAssigned')
      groupName.parentElement.lastElementChild.style.display = 'inline'
    })
  } else if (e.target.classList == 'addCardInput' && e.target.classList != 'notAssigned') {

    let addCardInput = e.target
    let taskUl = addCardInput.parentElement.querySelector('.taskUl')
    addCardInput.addEventListener("keydown", function(event) {
      if (event.key == 'Enter') {
        console.log("I'm in!")
        let newLi = document.createElement('li')
        newLi.innerHTML = `${event.target.value}`
        taskUl.appendChild(newLi)
      }
    })
  }
})
<main>
  <section class="groupSection">
    <span class="groupName">
                        <input type="text" autocomplete="false" id="groupNameInput" placeholder="name">
                    </span>
    <ul class="taskUl">
    </ul>
    <input type="text" class="addCardInput" placeholder="Add a card...">
  </section>
  <section class="addItemsSection">
    <button id="addItemsBtn">
                        <img src="./srcs/add_Icon.png" alt="" id="addItemsImage">
                    </button>
  </section>
</main>

How to call an external API from Google Apps Script

I want to call the Steem API from inside a Google Apps Script function. I want to see the appropriate server resonse. But I get the following error instead.

GAS error

According to this documentation, I ran the following test.

// @see https://github.com/steemit/steem-js/tree/master/doc#browser

const getHelloWorld = () => {
  const SOURCE_CODE_URL = 'https://cdn.jsdelivr.net/npm/steem/dist/steem.min.js';
  const response = UrlFetchApp.fetch( SOURCE_CODE_URL, );
  const code = response.getContentText();
  const steem = eval( code, );

  steem.api.getAccounts([ 'ned', 'dan', ], ( error, response, ) => {
    Logger.log( error, response, );
  });
}

In my prior research, I read that this answer says:

You can do this: eval(UrlFetchApp.fetch("my url").getContentText())

How can I call the Steem API from inside Google Apps Script?

React Hooks – Using useRef without direct access to HTML Element Code?

With React I’m inside of one repository, and the HTML elements are loading from another repo, which I watch for using pageLoaded. Inside updateHeader there is just more HTML element selecting and attribute/class manipulation.

useEffect(() => {
        if (pageLoaded.status) {
            if (someCondition) {
                updateHeader(ubeName);
            } else {
                document.querySelector('.headerbar-menu').style.display = 'block';
                if (document.querySelector('.headerbar-menu.affiliates-wrapper')) {
                    document.querySelector('.headerbar-menu.affiliates-wrapper').style.display = 'none';
                }
            }
        }
    }, [pageLoaded.status])

The problem here is obviously we shouldn’t be using querySelector, and i think it may be causing some unexpected functionality. The elements dont properly evaluate and render until some piece of state changes i.e. a scroll state handler, so on initial page load the elements dont show with their new attributes until a scroll.

I’d like to attempt to resolve using useRef, but don’t have direct access to the html. Is there a way to dynamically connect a ref to an element without access to the HTML code?

Thanks for your time and attention!

JavaScript – Map over nested array into table

I am trying to map over a multi level array and display the contents into a table.

Here are the first two entries within the array:

samples: Array(47)
0:
data: (2) [22.5, 401.0454]
time: "2022-05-05T19:00:00Z"
[[Prototype]]: Object
1:
data: (2) [22.4, 400.8234]
time: "2022-05-05T19:30:00Z"

Here is my current code:

<tbody>
                <tr>
                    <th>Date</th>
                    <th>Temp</th>
                    <th>C02</th>
                </tr>
                {data.map( item => (
                    <tr>
                        <td>{item.samples.time}</td>
                        <td>{item.samples.data[0]}</td>
                        <td>{item.samples.data[1]}</td>
                    </tr>
                ))}
            </tbody>

The const data set in a UseEffect() call to an API.

The error I am getting is “Uncaught TypeError: data.map is not a function”

Any help is appreciated!

What is the meaning of async resolve parameter in promises?

I have the following javascript code which will record voice for 3 seconds and then play it back:

const recordAudio = () =>
  new Promise(async resolve => {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    const mediaRecorder = new MediaRecorder(stream);
    const audioChunks = [];

    mediaRecorder.addEventListener("dataavailable", event => {
      audioChunks.push(event.data);
    });

    const start = () => mediaRecorder.start();

    const stop = () =>
      new Promise(resolve => {
        mediaRecorder.addEventListener("stop", () => {
          const audioBlob = new Blob(audioChunks, { type: "audio/mpeg" });
          const audioUrl = URL.createObjectURL(audioBlob);
          const audio = new Audio(audioUrl);
          const play = () => audio.play();
          resolve({ audioBlob, audioUrl, play });
        });

        mediaRecorder.stop();
      });

    resolve({ start, stop });
  });

const sleep = time => new Promise(resolve => setTimeout(resolve, time));

const handleAction = async () => {
  const recorder = await recordAudio();
  const actionButton = document.getElementById("action");
  actionButton.disabled = true;
  recorder.start();
  await sleep(3000);
  const audio = await recorder.stop();
  audio.play();
  await sleep(3000);
  actionButton.disabled = false;
};

How does resolve work in this code?

when calling for example recorder.start(). Will it just trigger the piece of code

const start = () => mediaRecorder.start();

In recordAudio?

array of objects with 6 keys, how to group them into fewer keys?

sorry if the title is a bit missleading, I new to js so idk how to explain what I want to do properly so I’m gonna show my code and what I expect instead.

so I have this array of objects

const mi_array = [{
    text: "1st title",
    col2015: 81.8,
    col2016: 86.4,
    col2017: 67.3,
    col2018: 70.8,
    col2019: 67.6
},{
    text: "2nd title",
    col2015: 90.8,
    col2016: 67.4,
    col2017: 39.3,
    col2018: 50.8,
    col2019: 95.6
}];

I need something like this

const new_array = [{
    name: "1st title",
    data: [81.8,86.4,67.3,70.8,67.6]
},{
    name: "2nd title",
    data: [90.8,67.4,39.3,50.8,95.6]
}];

I’ve been searching on how to do it but this is all I found so far and it comes close to what I need but not quite there yet

const new_array = [];

mi_array.forEach(value => {
    for (let key in value) {
        new_array.push(value[key]);
    }
});

console.log(numbers);

But my output it’s this

["1st title", 81.8, 86.4, 67.3, 70.8, 67.6, "2nd title", 90.8, 67.4, 39.3, 50.8, 95.6];

How to return a value from a callback inside a async function? [duplicate]

I’m trying to use the SERP API to get google search snippets.
However, I only can get undefined in this case.

const SerpApi = require('google-search-results-nodejs')
const search = new SerpApi.GoogleSearch(API_KEY)

const params = (query) => {
  const str = query.join(' ')
  return { q: str }
}

const getSnippets = async (query) => {
  search.json(params(query), (data) => {
    return data['organic_results'].map((result) => result.snippet)
  })
}

const print = (arg) => {
  getSnippets(arg).then((data) => {
    console.log(data)
  })
}

print(['eclipse'])

// Console
undefined

It gets results, but I can’t access them later.

const getSnippets = async (query) => {
  search.json(params(query), (data) => {
    console.log(data['organic_results'].map((result) => result.snippet))
  })
}

// Console
[
  'The Eclipse Foundation - home to a global community, the Eclipse IDE, Jakarta EE and over 415 open source projects, including runtimes, ...',
  'An eclipse is an astronomical event that occurs when an astronomical object or spacecraft is temporarily obscured, by passing into the shadow of another ...',
  "This is NASA's official eclipse Web site. It contains maps and tables for 5000 years of eclipses and includes information on eclipse ...",
  'Eclipse Tools is the prime seller of advanced computer networking tools and testers. Contact us today if you are looking for such computer networking ...',
  'A total solar eclipse is coming to America on April 8, 2024. Find maps, videos, how to view, best places to go, eclipse glasses, and more.',
  '1 : to cause an eclipse of The sun was eclipsed by the moon. 2 : to be or do much better than : outshine ...'
]

I’m new to async functions. I can do simple async functions, but I can’t make this one right.