How to render new password with button in input field? PHP

I got problem,where after I hit Heslo(password) button it did what it should, but everytime resets whole page. How should I make it, that after hitting button it renders new password just in input field without reseting whole page?

this is part, where password is generated

<?php

if(!isset($_POST['generate'])){
  $password = "heslo pre edit/delete";
}else{
  $password = substr(md5(rand()), 0, 5);
}

?>

and html part for button and input

 <div class="input-group mb-3">
     <div class="input-group-prepend">
     <button class="btn btn-dark" type="submit" id="generate" name="generate">Heslo</button>
 </div>
     <input readonly="readonly" type="text" class="form-control"  name="editPassword" 
      id="editPassword" value="<?php echo $password ?>">
 </div>

enter image description here

Applying Specific Data Formatting from a Returned Data Object in JavaScript

I have a list of project data as below, the data in the object is based on the projectId. I am now trying to make a new data object that will be formatted based on userId to see which user has which projectId.

const projects = [
  {
    projectId: "abc123",
    name: "Project 1",
    userProjects: [
      {
        userId: "xyz789",
        projectId: "abc123",
        user: {
          userId: "xyz789",
          email: "[email protected]"
        },
      },
      {
        userId: "sdf012",
        projectId: "abc123",
        user: {
          userId: "sdf012",
          email: "[email protected]"
        },
      },
    ],
  },
  {
    projectId: "def456",
    name: "Project 2",
    userProjects: [
      {
        userId: "xyz789",
        projectId: "def456",
        user: {
          userId: "xyz789",
          email: "[email protected]"
        },
      },
    ],
  },
]

Below is my code that I am able to get all the existing users and all the existing projects.

const userInfo = [];
const projectInfo = [];

for (let i = 0; i < projects.length; i++) {
  const userProject = projects[i].userProjects;

  for (let j = 0; j < userProject.length; j++) {
    const projectExist = projectInfo.some((project) =>
      project.projectId.includes(userProject[j].projectId)
    );
    if (!projectExist)
      projectInfo.push({
        projectId: projects[i].projectId,
        name: projects[i].name,
      });

    const userExist = userInfo.some((item) =>
      item.userId.includes(userProject[j].user.userId)
    );
    if (!userExist)
      userInfo.push({
        userId: userProject[j].user.userId,
        email: userProject[j].user.email,
        project: projectInfo,
      });
  }
}

However, I am having to implement that which user owns which project. If now I print out the userInfo, it will show up both users has both projects in the array, which is not correct (user sdf012 only has the abc123).

Also, I am bad at data formatting like this task. Are there any resources you would recommend to learn? It is so important as I work with MongoDB and sometimes need to retrieve data and modify data to different specific formatting.

Thank you for the help!!!

Iterate nested object with for loop

how can I get the values of a nested object in a loop? I need to iterate through both levels:

for (let unit in ds1.units) {      
    for (let ports in ds1.units[unit].switchPorts) {
        console.log(ports)
    }
}

}

Object looks like this:
Screen
There is no output. When I access the value with ds1.units[unit].switchPorts I get it. Also I get the unit after the first for loop.

Content Security Policy issue in Chrome Extension

I am trying to make a chrome extension, and I would have to update a JS file very often, so I put a external link for it. I want to acess the variable promocodes (which is an object) in that carregar() function.

function carregar(){
    const promocodesScriptObj = document.createElement("script");
    promocodesScriptObj.setAttribute("src", "https://raw.githubusercontent.com/leonardobagi/robloxpromocodemaster/main/promocodesObj.js");
    promocodesScriptObj.setAttribute("type", "text/javascript");
    document.querySelector("head").appendChild(promocodesScriptObj);
...
}

But then when I try loading the page, it catches the following error:

Refused to load the script ‘https://raw.githubusercontent.com/leonardobagi/robloxpromocodemaster/main/promocodesObj.js’ because it violates the following Content Security Policy directive: “script-src ‘self’ ‘unsafe-inline’ ‘unsafe-eval’ *.evidon.com *.gigya.com *.google-analytics.com *.ns1p.net adservice.google.com ajax.aspnetcdn.com ajax.googleapis.com …

I have no idea of how to fix it. I’ve tried adding the following line to manifest.json, but it stills returning the same error

    "content_security_policy": {
        "extension_pages": "script-src 'self'; object-src 'self'",
        "sandbox": "sandbox allow-scripts; script-src 'self' 'https://apis.google.com/' 'https://www.gstatic.com/' 'https://*.firebaseio.com' 'https://www.googleapis.com' 'https://ajax.googleapis.com' 'https://raw.githubusercontent.com'; object-src 'self'"
    },

Am I calling this API correctly for HaveIBeenPwned (HIBP)?

I am fairly new to web development and using API’s, and for some reason I keep getting a 401 “Access denied due to missing hibp-api-key.” error when trying to use this one API for the website HaveIBeenPwned. I’m using Postman just to check the API, and here is what I am using: https://haveibeenpwned.com/api/v3/pasteaccount/foo%40bar.com%20hibp-api-key:%20XXXXXXXXXXXX #API Key was redacted at the end, and the email is a test email.

Can anyone tell me what I’m doing wrong, and why it keeps giving me an error? I’ve checked my API key a million times and I just don’t know why this isn’t working! Here is the documentation: https://haveibeenpwned.com/API/v3
It says:

The API takes a single parameter which is the email address to be
searched for. The email is not case sensitive and will be trimmed of
leading or trailing white spaces. The email should always be URL
encoded. This is an authenticated API and an HIBP API key must be
passed with the request.

GET https://haveibeenpwned.com/api/v3/pasteaccount/{account}
hibp-api-key: [your key]

Reference a specific row by an API call or webhook and run a function on just that row

I have code here that when it runs, it emails the Project Owner the project name, and all related tasks & notes for all projects. It checks to see if the LastUpdate is within 24 hours of the current time.
(Thank you @Tanaike)

Ideally what I would like, is in Appsheet when I press a button it makes a webhook/api call reference to the single project based on an API call/webhook? so it doesnt send an email for every single project. Just a single project from referenced row from a webhook/api/appsheet button.

Here is the Code:

function myFunction() {
  // Retrieve 3 sheets.
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const [sheetITPM, sheetITPM_Tasks, sheetNotes] = ["ITPM", "ITPM_Tasks", "Notes"].map(e => ss.getSheetByName(e));

  // Retrieve IDs, names and emails.
  const values = sheetITPM.getRange("A2:J" + sheetITPM.getLastRow()).getValues().map(r => ({ id: r[0], name: r[1], email: r[9] }));

  // Retrieve Tasks.
  const tasks = sheetITPM_Tasks.getRange("A2:H" + sheetITPM_Tasks.getLastRow()).getValues().reduce((o, r) => (o[r[2]] = o[r[2]] ? [...o[r[2]], { description: r[3], status: r[4], dueDate: r[6], t_lastUpdate: r[7] }] : [{ description: r[3], status: r[4], dueDate: r[6], t_lastUpdate: r[7] }], o), {});

  // Retrieve Notes.
  const notes = sheetNotes.getRange("A2:F" + sheetNotes.getLastRow()).getValues().reduce((o, r) => (o[r[1]] = o[r[1]] ? [...o[r[1]], { note: r[2], date: r[4], n_lastUpdate: r[5]}] : [{ note: r[2], date: r[4], n_lastUpdate: r[5] }], o), {});
  Object.entries(notes).forEach(([, v]) => v.sort((a, b) => a.date.getTime() < b.date.getTime() ? 1 : -1)); // Sort Notes by Date field 

  // Check if task last update within 24 hours
  const now = new Date().getTime();
  const before24h = now - (25 * 60 * 60 * 1000);
  Object.entries(tasks).forEach(([k, v]) => {
    tasks[k] = v.filter(({t_lastUpdate}) => {
      const temp = dueDate.getTime();
      return now > temp && temp > before24h;
    });
  });
  Object.entries(notes).forEach(([k, v]) => {
    notes[k] = v.filter(({n_lastUpdate}) => {
      const temp = date.getTime();
      return now > temp && temp > before24h;
    });
  });

  // Send emails.
  values.forEach(({ id, name, email }) => {
    const message = [
      `Here is the project update for: ${name}`,
      "",
      `Assigned Tasks:`,
      ...tasks[id].map(({ description, status, dueDate, t_lastUpdate }, i) => [`Task ${i + 1}:`, description, status, dueDate, t_lastUpdate, ""].join("n")),
      "",
      `Project Notes:`,
      ...notes[id].map(({ note }, i) => [`Note ${i + 1}:`, note, ""].join("n")),
    ].join("n");
    MailApp.sendEmail({ to: email, subject: "Project update", body: message });
  });
}

SpreadsheetExample+TheOutput

Modern best practice for innerHTML replacement when you want to insert formatted text?

From what I understand, setting innerHTML on an element is bad, because if the new contents come from users, a malicious user can use it to inject <script> tags and other harmful content.

As demonstrated by this question, there are now about eight different alternative tags (with some non-standard).

In my case, I want to be able to insert actual html tags like <b> and <i>, and even <a>.

But I never need <script> to be inserted.

Is there a standardized best-practice alternative to innerHTML using vanilla Javascript?

node error cannot find package Arch linux

I got this error trying to run nodejs

node: error while loading shared libraries: libicui18n.so.70: cannot open shared object file: No such file or directory

i tried updating using

sudo pacman -Syu

and i also tried removing nodejs and re-installing it with no help.

I use Arch btw.

Javascript Get Multiple elements with multiple classes

How can i get multiple elements in javascript for example:

<p class="zrowOdd"> odd </p>
<p class="zrowEven"> even </p>
<p class="zrowOdd"> odd </p>
<p class="zrowEven"> even </p>

Is it possible to get all that elements in order in X:

var x = document.getElementByClassName("zrowOdd + zrowEven")// I know this 
dont work but just to be clear what i need

how to create a drag and drop website builder

Introduction

My company needs to build a Website Builder platform and I was tasked to gather all the needed Information and technologies needed.
It will be used to create a simple admin dashboards for our customers to be able to login and view reports done by our company, it will be personalized according to each customer but it will mostly have the same layout and components
e.g:

Same:

  • headers
  • same amount of pages
  • mostly same amount of objects

but will differ in:

  • colors
  • text
  • some additional tables that will be added according to each customer.

so overall the template itself won’t change that much but the design will.

Basic Information

  • After completing the project it is expected to be used by a “non-developer” employee so it needs to be user friendly and mostly use the GUI to interact with the project to create the website with as little coding as possible.
  • It is highly preferred if it is done as a browser based project not an application since it needs to be accessible in both Mac and Windows systems as well as the ability to use it in mobile/iPad systems.
  • It must be an in house project so can’t just use something like WIX or squarespace
  • I know its a mammoth task but I am not doing it alone, we have a team of developers and I am just gathering information and ideas.

what’s expected form the answers

  • Any good additional ideas/Modifications to improve this project
  • Overall step by step of how to achieve this project if possible (like you should do this then this but not like a detailed tutorial of course)
  • Technologies Recommendations to be used (languages, libraries, etc..)

Note: To eliminate confusion Whenever I mention “Project” I mean the “Website builder” itself

Thanks in advance

undefined value from function in javascript

I’m trying to get purchase order details from server

This is my code:

    function getPurchaseOrderInfo() {
      try {
        let po_ref = document.getElementById("po_ref").value;
        let data = new FormData();
        data.append("po_ref", po_ref);
        data.append("request_token", request_token);
        fetch(URL_ROOT + "purchase-orders/get_purchase_order_info", {
            method: "POST",
            body: data,
          })
          .then((res) => res.json())
          .then((msg) => {
            console.log(msg);
            return msg.status ? msg.data : false;
          });
      } catch (error) {
        console.log(error);
      }
    }

    console.log(getPurchaseOrderInfo());

This is what I got by executing the script

I have no idea why I’m getting an undefined value instead of object shown at console.log(msg);

I need the object to print a table and show details to user

How to get a domain variable value

so I have a question, which maybe it’s a little ez, but… I don’t know hehe, so, how do you get a value that’s in the domain? like:

https://example.com?test=helloworld

how do I get the value of the “test” variable that is there?

Having issues with highlighting text on button press – chrome extension

I am working on a Google Chrome Extension that will have a feature to highlight specific words. I have been able to get the extension to highlight words within the popup window. However, when I try to modify my code and highlight words from the Active Tab I run into issues. I am trying to use chrome.tabs.sendMessage to perform the action. The message never hits the listener that I have in place. Maybe I have it in the wrong file?

popup.html

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="button.css">
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.6.0.min.js"></script>
    <script src="popup.js"></script>
    <script src="selection.js"></script>
    <script src="hilitor.js"></script>

</head>
<body>
    <button id="highlightText">Scan for Washington</button>
</body>
</html>

background.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
    if (request.message == "getSelection"){
       console.log("Inside Get Selection");
       var myHilitor = new Hilitor("content"); // id of the element to parse
       myHilitor.apply("washington state one");
       console.log(request, sender, sendResponse);
    }
    sendResponse();
});

popup.js

$(function(){
    $('#highlightText').click(function(){highlightAllText();});
});

function highlightAllText() {
    console.log("Inside Highlight All Text");

    chrome.windows.getCurrent(w => {
        chrome.tabs.query({active: true, windowId: w.id}, tabs => {
            chrome.tabs.sendMessage(tabs[0].id, {
                "message": "getSelection"
            });
        });
    });

I am currently using Washington Wikipedia as my page to highlight. I am also using the Hilitor Library to perform the highlighting at this moment. Again, I can highlight everything in the popup window that is created from popup.html, but I can’t highlight outside of that.

Can PNGs (or GIFs) loop only the last few images (rather than all the images)

I want to have a PNG sequence that displays 68 frames of animation and then loops the final 20 frames x number of times.

I based my code on the suggestion from ‘r3mainer’ on your page:
[https://stackoverflow.com/questions/43595504/play-one-part-of-gif-first-then-loop-a-certain-section-indefinitely]

But I can not get it to work.

I created the vertical PNG ‘film strip’, a CSS file with the appropriate background style info, and a JS file referenced in an HTML.

With the PNG, the JS, the HTML, and the CSS uploaded all I get for an image on the page is the first ‘frame’ of the PNG strip. There are no error messages.

I think there’s something I don’t understand about how the JS code should be deployed.

Here’s my HTML file:

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Strip Test</title>    
    <script src="film_strip_script.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <link rel="stylesheet" href="draw.css">
 </head>

<body>
<div id="draw"></div>
</body>

The CSS:

#draw {
  width: 279px;
  height: 202px;
  margin:  0 auto;
  background: url(basquiat_strip.png) top center;
}

JavaScript file:

$(function() {
  var ani = {
    frame_height: 202,
    num_frames: 68,
    loop_frame: 30,
    frame_duration: 1,
    cur_frame: 0
  };
  window.setInterval(
    function() {
      $('#draw').css( 'background-position-y',
                      (-ani.frame_height * ani.cur_frame ) + 'px'
                    );
      ani.cur_frame = (ani.cur_frame + 1) % ani.num_frames;
      if (ani.cur_frame == 0) ani.cur_frame = ani.loop_frame;
    },
    ani.frame_duration
  );
});