How to force render same id with same data?

I have some card components (soldItems, createdItems) with same data, so this mean created items and sold items both are owned by creator and displayed on his profile, i want to show soldItem if it solded and don’t show createdItem if it solded …

Example:

SoldItem.filter((sold)=>{
CreatedItem.filter((created)=>{
   if(sold.id === created.id){
   console.log("matched");
   // In case its matched i want to show one of them not both
}else{
   console.log("not matched")
}
})
})

How to do conditional defining of key in an object in JS?

Suppose I want to create an object with keys as USD and non-USD. Like Below:

    let obj = {
                USD: {
                   sourceValue: 100
                   destinationValue: 10
                }, 
                non-USD: {
                  sourceValue: 10
                   destinationValue: 100
                }
              }

Except here, instead of non-USD, I should be able to pass any currency, like SGD or HKD and I should get result of non-USD currency.

so, if I wrote obj[currency].sourceValue and currency=HKD then I should get 10

I don’t want to use obj[1].sourceValue as currency value is dynamic.

Also, I don’t want to use if(currency!='USD') index=1 and then obj[index].sourceValue

So, my question is, what should I write at place of non-USD while defining object? I checked computation names, but I am not sure, how will I pass long currency array as key name and filter USD out of it?

Contact Button Animation Problem in HTML/CSS/JS

I have the following code:

var basicTimeline = anime.timeline({
  autoplay: false,
});

var pathEls = $(".check");
for (var i = 0; i < pathEls.length; i++) {
  var pathEl = pathEls[i];
  var offset = anime.setDashoffset(pathEl);
  pathEl.setAttribute("stroke-dashoffset", offset);
}

basicTimeline
  .add({
    targets: ".text",
    duration: 1,
    opacity: "0"
  })
  .add({
    targets: ".button",
    duration: 1300,
    height: 20,
    width: 81,
    backgroundColor: "#717F7E",
    border: "0",
    zIndex: 0,
    borderRadius: 100
  })
  .add({
    targets: ".progress-bar",
    duration: 2000,
    width: 81,
    easing: "linear"
  })
  .add({
    targets: ".button",
    width: 0,
    duration: 1
  })
  .add({
    targets: ".progress-bar",
    width: 40,
    height: 39,
    delay: 500,
    duration: 750,
    borderRadius: 80,
    backgroundColor: "#71DFBE",
    left: 20
  })
  .add({
    targets: pathEl,
    strokeDashoffset: [offset, 0],
    duration: 200,
    easing: "easeInOutSine"
  });


$(".button").click(playButtonAnim);

$(".text").click(playButtonAnim);

function playButtonAnim() {
  basicTimeline.play();
}

//error animation
const form = document.forms.myform;
form.onsubmit = e => {
  e.preventDefault()
  let data = Object.fromEntries(new FormData(form).entries())

  console.log(data)

  let validationOK = true
  for (let entrie in data) {
    if (!form[entrie].checkValidity()) {
      validationOK = false
      form[entrie].classList.add('shakingErr')
      setTimeout(() => {
        form[entrie].classList.remove('shakingErr')
      }, 820)
    }
  }
  if (validationOK) {
    fetch(form.action, {
        method: form.method,
        body: JSON.stringify(data),
        headers: {
          Accept: 'application/json'
        }
      })
      .finally(() => {
        window.location = "thankyou.html"
      })
  }
}
/* Contact Form */

input[type=text],
[type=email],
select,
textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #555;
  margin-top: 6px;
  margin-bottom: 16px;
  resize: vertical;
}

input[type="text"]:focus,
input[type="email"]:focus,
#subject:focus {
  background: var(--bgFormElsFocus);
  transform: scale(1.02);
  transition: transform 0.2s ease-in-out;
}

.contactform {
  position: relative;
  border-radius: 50px;
  background-color: #f2f2f2;
  padding: 5px;
  z-index: 2;
  display: block;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: auto;
  margin-top: 1%;
  width: 100%;
  animation-name: gradient;
  animation-duration: 3s;
  animation-iteration-count: infinite;
}

.contactform:hover {
  animation-name: gradient;
  animation-duration: 15s;
  animation-iteration-count: infinite;
}

.column {
  float: center;
  width: 50%;
  margin-top: 6px;
  padding: 20px;
  display: block;
  margin-left: auto;
  margin-right: auto;
}

.row:after {
  content: "";
  display: table;
  clear: both;
}

@media screen and (max-width: 600px) {
  .column,
  input[type=submit] {
    width: auto;
    margin-top: 0;
  }
}

.shakingErr {
  border-color: red;
  animation: shake 0.82s forwards;
}

@keyframes shake {
  10%,
  90% {
    transform: translate3d(-1px, 0, 0);
  }
  20%,
  80% {
    transform: translate3d(2px, 0, 0);
  }
  30%,
  50%,
  70% {
    transform: translate3d(-4px, 0, 0);
  }
  40%,
  60% {
    transform: translate3d(4px, 0, 0);
  }
}


/* fancy button styles */

.buttonWrapper {
  height: 39px;
  width: 81px;
  position: relative;
}

.button {
  background: #2B2D2F;
  height: 39px;
  width: 81px;
  text-align: center;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  left: 0;
  cursor: pointer;
  border-radius: 4px;
  z-index: 10;
}

.text {
  font: .8rem/1 poppins;
  color: #71DFBE;
  position: absolute;
  top: 50%;
  transform: translateY(-52%);
  left: 0;
  right: 0;
  cursor: pointer;
}

.progress-bar {
  position: absolute;
  height: 20px;
  width: 0;
  left: 40px;
  top: 50%;
  border-radius: 200px;
  transform: translateY(-50%) translateX(-50%);
  background: black;
}

svg {
  width: 15px;
  position: absolute;
  top: 50%;
  left: 20px;
  transform: translateY(-50%) translateX(-8px);
}

.check {
  fill: none;
  stroke: #FFFFFF;
  stroke-width: 3;
  stroke-linecap: round;
  stroke-linejoin: round;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>replit</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
  <link href="https://fonts.googleapis.com/css?family=Poppins:600" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Poppins:600" rel="stylesheet">
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.0.2/anime.js">
  </script>

</head>

<body>
  <!-- start contact section -->
  <section id="contact">
    <div class="container" data-aos="fade-up">
      <div class="contactform">
        <div style="text-align:center">
          <div class="section-title">
            <h2><br />Get In Touch</h2>
          </div>
          <p>Feel Free To Reach Out To Me Through This Form! </p>
        </div>
        <div class="row">
          <div class="column">
            <form name="myform" action="https://formspree.io/f/xrg123232jbqpq" id="my-form" method="POST" novalidate>
              <label for="firstname">First Name</label>
              <input type="text" id="first name" name="firstname" placeholder="Your First Name.." required>
              <label for="lastname">Last Name</label>
              <input type="text" id="lastname" name="lastname" placeholder="Your Last Name.." required>
              <label for="email">Email:</label>
              <input type="email" id="email" name="email" placeholder="Your Email.." required>
              <label for="subject">Subject</label>
              <textarea id="subject" name="subject" placeholder="Lets Collaborate.." style="height:170px" required></textarea>
              <!-- <input type="submit" value="Submit"> -->
              <div class='buttonWrapper'>
                <div class="button">
                  <div class="text">Submit</div>
                </div>
                <div class="progress-bar"></div>
                <svg x="0px" y="0px" viewBox="0 0 25 30" style="enable-background:new 0 0 25 30;">
                  <path class="check" class="st0" d="M2,19.2C5.9,23.6,9.4,28,9.4,28L23,2" />
                </svg>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </section>
  <script src="script.js"></script>
</body>

</html>

The only problem I’m facing is that even though I have error animation code in the JS that calls in the shakingErr class from CSS, the animation seems to be not working when the user clicks submit with empty/wrong fields. How can I make it so that when the user clicks the submit button, the contact form has a shaking error button.

Notice that when you click the submit button, there is also an animation that plays on the button? I would not like that animation to play when the user clicks submit button on empty fields. I would only like the animation to play once the user has filled all the information in the input fields.

Any suggestions?

EXPECTED OUTPUT

https://watch.screencastify.com/v/D2VXp3493XZXl3Lmh7yR

As you can see, whenever the user tries to click submit button on empty/wrong fields (Email) then the error animation plays. Also, the button animation should not play when the user clicks the submit button on empty/wrong fields. It should play once the fields are filled and are right.

How can I make the animation work now? Please give any suggestions, thanks a lot!

how to implement BlinkID In-browser SDK in normal html and js

I am trying to implement BlinkID In-browser SDK into a project that i am working on, and i am having trouble with how to integrated and how to make it recognisable, I would really appreciate it if someone can show me a full code example of the implementation, I have read the documentation and applied what is mentioned, however note that i am new to programming

React dobble update so my useContext = undefined

Hi i have a problem with my react app, I’m using useContext to parse my user to a voting site, but I have a small problem, my app is dobble loading, then my context turns to undefined, i can see the user at the first console.log but i cannot access it.

const { user, setUser } = useContext(UserContext)
const [medarbejdere, setMedarbejdere] = useState({})

const userLogIn = document.getElementById('id').value;
const user = medarbejdere?.filter(userid => userid.id === parseInt(userLogIn)).map(currentUser => console.log(currentUser)) 
        
setUser(user);
navigate("/votingsite")```

Updating D3 interactive barchart by removing bars that are already there

Issue: I want to update the bars in my graph so that when the “Dreamworks” button is clicked, it appends new bars and gets rid of the old ones. I know it is an enter(), exit() issue, but I do not know exactly how to implement it.

Context: When my button is clicked, it activates a function that extracts the inner HTML of my button and uses it to filter my data so only observations from a company remain. The code works, but instead of getting rid of old bars, it appends the new bars on top of the old ones. When you look in the console, a new “g” element appears (which contains the new “rects”) every time the button is clicked. I lowered the opacity of the “rects” to show what is going on. I removed all exit() and remove() attempts from my code because nothing was working.

HTML Code:

            <div class= "button-holder">
                <button class= "button button-dreamworks">DreamWorks</button>
                <button class= "button button-disney">Disney</button>
                <button class= "button button-pixar">Pixar</button>
            </div>
                <div class = "chart chart1"></div>

JS Code:

async function drawBar() {
    // 2. Create Chart Dimensions 
    const width = 600
    let dimensions = {
        width,
        height: width*0.6, 
        margin: {
            top: 30,
            right: 10,
            bottom: 50,
            left: 50
        }
    }
    
    dimensions.boundedWidth = dimensions.width
        -dimensions.margin.right -dimensions.margin.left 
    dimensions.boundedHeight = dimensions.height 
        -dimensions.margin.top -dimensions.margin.left 

// 3. Draw Canvas 
const wrapper = d3.select(".chart1")
    .append("svg")
    .attr("width", dimensions.width)
    .attr("height", dimensions.height)



// 4. Load Data  
    const raw_data = await d3.csv("./data/all_movie_data.csv")


    
    const drawBarChart = function(company_name) {
    const dataset = raw_data.filter(function(d){ return  d["company"] == company_name })
    const xAccessor = d => d["name"]
    const yAccessor = d => parseFloat(d.budget) 


let bounds = wrapper
    .append("g")
    .attr("class", "bounds")
    .style(
      "transform",
      `translate(${dimensions.margin.left}px,${dimensions.margin.top}px)`
    );


// 5. Create scales 
const xScale = d3.scaleBand()
    .domain(dataset.map(xAccessor))
    .range([0,dimensions.boundedWidth])
    .padding(0.4);
    
const yScale = d3.scaleLinear()
    .domain(d3.extent(dataset,yAccessor))
    .range([dimensions.boundedHeight, 0])


// 6. Draw Data

bounds.selectAll("rect")
    .data(dataset)
    .join("rect")
    .attr("x", (d) =>  xScale(xAccessor(d))) 
    .attr("y", (d) => yScale(yAccessor(d)))
    .attr("width",  xScale.bandwidth()) 
    .attr("height", (d) => dimensions.boundedHeight - yScale(yAccessor(d))) 
    .attr("fill", "blue");
    

}

//6. Interactions 
drawBarChart("Pixar");

const button1 = d3.select(".button-dreamworks")
    .node()
    .addEventListener("click", onClick1) 

function onClick1() {
    const company = document.querySelector(".button-dreamworks").innerHTML;
    drawBarChart(company);
    }

}

drawBar(); 

You can find a version of my code in this code pen: https://codepen.io/larylc/pen/XWzbQGy

Everything is the same except for the data, which I just made up to show the issue.

How to get the amount of counties and zip codes there are in a State with the same State Code – MongoDB, Node.Js, Mongoose

I have a problem that I have been trying to work out and need some guidance. I have a Mongo Atlas database with US State information fields such as zip codes, city, county, county codes, state, state codes (ex. NY), longitude, latitude, number of zip codes, and number of counties.

My objective is to get the total number of zip codes and counties in a single State that has the same state code. Once I get the totals I want to update the field values num_of_counties and num_of_zips.

My thought is to get the sum of the lengths of both the zip codes and the counties. The setting the values to a variable which will be used in the $set field value.

Thank you in advance!

Zip Route

const express = require('express');
const router = express.Router();

const Zip = require('../models/Zip')

router.get('/', async (req, res) => {
    try {

        const zipCode = await Zip.find({ zips: req.id });

        console.log(zipCode);

        res.json(zipCode)
    } catch (err) {
        console.error(err.message);
        res.status(500).send('Server Error')
    }
});

router.get('/:zip', async (req, res) => {
    try {

        const zipCode = await Zip.find({ zip: req.params.zip }, {
            _id: 0,
            city: 1,
            county: 1,
            state: 1,
            state_code: 1
        });

        console.log(zipCode);

        res.json(zipCode)
    } catch (err) {
        console.error(err.message);
        res.status(500).send('Server Error')
    }
});


router.put('/', async (req, res) => {
    try {
        const zipVals = await Zip.aggregate([{ $group: { state_code: "state_code", zip: { $sum: "$zip" } } }])
        console.log(zipVals);
        const numOfCounties = await Zip.updateMany({}, { $set: { num_of_counties: 1 } })
        const numOfZipCodes = await Zip.updateMany({}, { $set: { num_of_zips: zipVals } })

        res.json([numOfCounties, numOfZipCodes])

    } catch (err) {
        console.error(err.message);
        res.status(500).send('Server Error')
    }
})


module.exports = router;

Model

const mongoose = require('mongoose');

const ZipSchema = mongoose.Schema({
    zip: {
        type: String,
    },
    city: {
        type: String,
    },
    state: {
        type: String,
    },
    state_code: {
        type: String,
    },
    county: {
        type: String,
    },
    county_code: {
        type: String,
    },
    latitude: {
        type: String,
    },
    longitude: {
        type: String,
    },
    num_of_counties: {
        type: Number,
    },
    num_of_zips: {
        type: Number,
    }

});

module.exports = mongoose.model('zip', ZipSchema)

Handle real `change` event in React

In javascript input has change event that in case of type="number" occures when either the input looses its focus or user uses step up or step down functionality, but not on the normal typing.

document.querySelector("input").addEventListener("change", e => {
  console.log(e.type, e.target.value)
})
<input type="number" step="0.1"> <button>&nbsp;</button>

But when I’m using react, it replaces change event by input event which occurs on typing too:

function App() {
  const [val, setVal] = React.useState("")
  
  function onChange(e) {
    console.log(e.type, e.nativeEvent.type, e.target.value)
    setVal(e.target.value)
  }
  
  return (
    <React.Fragment>
     <input type="number" step="0.1" value={val} onChange={onChange} />
     {" "}
     <button>&nbsp;</button>
    </React.Fragment>
  )
}

ReactDOM.render(<App />, document.querySelector("main"))
<script crossorigin src="//unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="//unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
<main></main>

I need to handle normal change event that does not occur on typing.
How can I do that in react?

PS: Button in the snippects is a place where you can tab to from the input.

Paper.js – how to get a list of all items inside a bounding box?

I want to allow the user to drag a rectangle around the desired items, to select multiple Paper.js items at once.

For individual item selection by clicking, I can do a hitTest which returns whatever element is under the cursor (if any).

I have already written code to draw a selection rectangle with the mouse.

But how can I get a list of all items that are inside the rectangle? Do I have to iterate all items on the project and determine if their bounding boxes fall inside the selection rectangle? or is there some built-in function to do this?

hitTestAll seems to only return the items directly under a point (if multiple items are stacked), right?

Simplifying assignment calls in javascript object

Is there a smarter way to write this this javasript? I feed in a parameter called “animalType” that changes depending on the new animal brought it. Would it be possible to destructure the object but save the changes?

  animalDiscoveryList[animalType].points += currAnimal.points
  animalDiscoveryList[animalType].owned += currAnimal.owned
  .....
  animalDiscoveryList[animalType].foodTypes =  animalDiscoveryList[selectedFilterType].foodTypes.append(currAnimal.id)

Automatically submit a value on click to a form using Javascript/Java in a Django form

I am working on a web app using Django/Python/Javascript/Java. The focal point is a map of the USA. A user should be able to click on a region and the value of that region should automatically query a database and return certain information. Currently, my code produces a const called regionName and the value of regionName is passed automatically as input to the search bar; however, from here a user needs to manually click the ‘search’ button to submit the form and query the database. As below:


  onRegionClick: function(event, code){
            console.log('event', event, 'code', code);
            const regionName = map.getRegionName(code);
            console.log('regionName', regionName);
            $("#selection").val(regionName);
  
        },

      });

What I am trying to do with the code is to automatically submit the value of regionName after it is passed to the search bar. Efforts thus far have been similar to the code below.

$(“#selection”) – the form

$(“#q”) – the name of the button

 $("#selection").on('change', function(){
                if ($("#selection").val() === regionName ) {
                  $("#q").click();
                }
              }); 

This is not producing any errors, but it’s not producing any results either.

I’ve tried various substitutes along similar lines such as:

.on(‘input’.. instead of ‘change’
.submit() instead of .click()

I’ve also have an .autocomplete() method I’m using. I’m not sure if this is causing a conflict.


<script type="text/javascript">
            $(function () {
              var states = [
                {% for states in states %}

                " {{states.state}} ",

                {% endfor %}

              ];

              $("#selection").autocomplete({
                  source: states
              }); 

            });

          </script>

TypeError: Cannot read properties of undefined (reading ‘length’) in DataTable

I want to populate a DataTable using the jQuery ajax but I keep bumping into a TypeError: Cannot read properties of undefined (reading ‘length’).

For context, I am using the Hope UI datatable template for this.

Here’s the HTML code for the table:

<div class="table-responsive">
    <table id="boards_table" class="table table-striped" data-toggle="data-table">
        <thead>
            <tr>
                <th>Model</th>
                <th>Serial</th>
                <th>Revision</th>
                <th>Owner</th>
                <th>Date Owned</th>
                <th>Updates</th>
                <th>Notes</th>
                <th>Date Added</th>
                <th>Status</th>
                <th>History</th>
            </tr>
        </thead>

        <tfoot>
            <tr>
                <th>Model</th>
                <th>Serial Number</th>
                <th>Revision</th>
                <th>Owner</th>
                <th>Date Owned</th>
                <th>Updates</th>
                <th>Notes</th>
                <th>Date Added</th>
                <th>Status</th>
                <th>History</th>
            </tr>
        </tfoot>
    </table>
</div>

This is the script I use for the Ajax call:

$(document).ready(function() {
    var table = window.DataTable = $('#boards_table').DataTable({
        "order": [],
        "bootstrap": true,
        "bAutoWidth": true,
        "responsive": true,
        "processing": true,
        "serverSide": true,
        "aLengthMenu": [
            [25, 50, 75],
            [25, 50, 75]
        ],
        "pageLength": 25,
        "ajax": {
            url: "boards-ajax.php",
            type: "POST",

            "data": {
                GetBoards: "Yes",
            },

            error: function(xhr, textStatus, errorThrown) {

                var error = textStatus;
                var details = errorThrown;
                console.log(xhr.responseText);
                console.log("Status=" + xhr.status + "nStatusText=" + xhr.statusText + "nError=" + error + "&Detail=" + details)

            }
        },

        "dom": 'Bfrtip',
        "buttons": [{
            extend: 'excelHtml5',
            className: 'btn btn-link btn-soft-light',
            exportOptions: {
                columns: [2, 3, 4],
            }
        }],
        "initComplete": function(settings, json) {
            table.buttons().container().appendTo($('#boards_table_wrapper .col-sm-6:eq(0)'));
        },
    });
   
    $("#global_search").on('keyup', function() {
        table
            .search(this.value)
            .draw();
    });
});

And this is the PHP script the gets the data from the database:

if (isset($_POST['GetBoards'])) {

    if ($InventoryCon->connect_errno) {

        header('HTTP/1.1 503 Service Unavailable');
        exit();

    } else {

        $Query = "Select *    From boards     Where IsDeleted=0;";
        $AllRecords = array();
        $Result = mysqli_query($InventoryCon, $Query);

        if (!mysqli_query($InventoryCon, $Query)) {

            header('HTTP/1.1 500 Internal Server Error');
            throw new ErrorException($InventoryCon->error, 500);
            exit();

        } else {

            while ($Row = mysqli_fetch_assoc($Result)) {
                $RowArray = array();
                $RowArray[] = $Row['ModelName'];
                $RowArray[] = $Row['SerialNumber'];
                $RowArray[] = $Row['RevisionNumber'];
                $RowArray[] = 'Owner';
                $RowArray[] = $Row['DateOwned'];
                $RowArray[] = $Row['Updates'];

                // Notes icon
                $RowArray[] = 'Note Column';


                $RowArray[] = $Row['DateAdded'];

                //Status button
                $RowArray[] = 'Status Column';


                // History button
                $RowArray[] = 'History Column';

                $AllRecords[] = $RowArray;
            }
            $output = array(
                "draw" => 25,
                "recordsTotal" => mysqli_num_rows($Result),
                "recordsFiltered" => 25,
                "data" => $AllRecords
            );
            
                echo json_encode($output );
    
        }

        mysqli_close($InventoryCon);
    }
}

The Ajax call returns 200 OK and if I add a success function, I can see that the data is also returned as it should.

I scoured the internet to see what solutions other people found, but none did the trick.

‘Refused to set unsafe header “cookie”‘ durante requisição AJAX [closed]

Olá!
Estou criando um forms tipo ‘hidden’ dentro da minha página, e usando AJAX para enviar as respostas ao meu script Google, que alimenta um Sheets com essas respostas.


Link da página:
https://mcczdmjzbk7rtly9nsqx690fd25y.pub.sfmc-content.com/5jfgjvgskj2?qs=9668f36134cc0e1ee13aa77b9332e5b392103a9f7c562abae9b517d752603a0b2d07c69ed5273475a671496c1b77abcefd27b435212c1559d3568825826915fdf1a6fe64666c9d20c478fcae3c249994ad0c05434ec04b866e1f79cb81c9ebf206d830a696fb7e64829699de91f93beb79370f049ef1a11dfc22bd774e162980&utm_source=&utm_medium=crm&utm_term=&utm_content=&utm_campaign=

Google Script link:
https://script.google.com/home/projects/1lEMTZz1a0nu-HwO7qXHlBixNIKxh54xA19RRQY59_FWlre2hqOjV5DO_/edit


O botão ‘Finalizar’ inicia as requisições AJAX.
%%=v(@email_address)=%%, por exemplo, é uma variável recebida pela página via Salesforce, com notação própria.

<form id='respostas'>
                  
  <input type="hidden" name="email_buyer" value="%%=v(@email_address)=%%">
  <input type="hidden" name="nota" value="%%=v(@nota)=%%"> 
  <input type="hidden" name="buyer_name" value="%%=v(@first_name)=%%">
    
  <div class="button-wrapper" style=" display: flex; justify-content: center;">
   
    <button style="background-color:#588e8f"type="submit" class="mt-25" id="submit-form">
    Finalizar
    </button>

  </div>
              
</form> 

As requisições são enviadas ao script Google usando ‘GET’


              $("form#respostas").submit(function(event) {
                 var $form = $('form#respostas');
                 request = $.ajax({
                        url: "https://script.google.com/a/macros/mobly.com.br/s/AKfycbyxmoJMS2UerY_sqiTuSLX5a7EO8G_NNb7Jb4aS4eo8DHCKVDG_YMqliIIrIFhrlXf-/exec?callback=?",
                        type: "get",
                        crossDomain: true,
                        datatype: "jsonp",
                        headers: {
                          "accept": "*/*",
                          "cookie": "",
                          'Access-Control-Allow-Origin': '*',
                        },
                        data: $form.serialize(),
                        success: () => {
                          console.log('Sucesso.');
                        }
                       });
                       request.done(function (response, textStatus, jqXHR){
                        console.log(JSON.stringify(response));
                        alert("Obrigado pela resposta! Você já pode sair desta página");
                    });
                    request.fail(function (response, textStatus, jqXHR){
                      console.log(response,'######',textStatus,'#######',jqXHR)
                      alert("fail");
                    });
                    event.preventDefault();
                  //return false;
                      });

Clicando no botão ‘Finalizar’, recebo o alerta de falha.
Inspecionando a página encontrei o erro Refused to set unsafe header “cookie”.
Alguém sabe dizer o que está errado no código, ou o que poderia estar faltando?
Nunca vi esse erro antes.
Obrigado!!

Google sheets script order not executing properly

I have a spreadsheet that loads a customer’s saved checkout sheet. When the function is called it loads a snapshot of the customer’s checkout sheet the last time it was saved. After the snapshot is loaded there are 3 fields that need to be altered to set the proper day and time of the new checkout.

I’ve tried writing the code where these three fields are at the end of the function, where they are a function by themselves that gets called at the end of the original function, and have tried using a Utilities.sleep(), all which do not work. What ends up happening for all these scenarios is the three cells will change to their expected values for a split second, and then revert to the values that were loaded from a customer’s saved sheet.

I don’t understand who this is happening, as these 3 cells are being altered only after the previous code has completed. Help please!

  function loadSnapshot(){

//Gets checkout sheet ID from Customer's profile  
  try {
  let artistName = SpreadsheetApp.getActiveSpreadsheet().getRange('Signature Sheet!F6:F6').getValue()
  let customerCheckoutSheetID = DriveApp
  .searchFiles(`title contains "${artistName} + Saved Checkout Sheet"`).next().getId();
  
  
  let customerSheetLR = SpreadsheetApp.openById(customerCheckoutSheetID).getSheets()[0].getLastRow()
  let customerSheetLC = SpreadsheetApp.openById(customerCheckoutSheetID).getSheets()[0].getLastColumn()

  let customersSheetValues = SpreadsheetApp.openById(customerCheckoutSheetID).getSheets()[0].getSheetValues(1,1,customerSheetLR,customerSheetLC)

  let mainSheetActiveRange = SpreadsheetApp.openById('xxx').getSheets()[0].getRange('Signature Sheet!A1:H41')
  let mainSpreadsheetValues = SpreadsheetApp.openById('xxx')
  .getSheets()[0].setActiveRange(mainSheetActiveRange).setValues(customersSheetValues)
  
  headerFields()
  
  }
catch(error){
  SpreadsheetApp.getUi().alert('No Saved Snapshot')
 }
}

function headerFields(){
//Header Formulas
  var spreadsheet = SpreadsheetApp.getActive()
  let checkoutTime = spreadsheet.getRange('Signature Sheet!F9:F9').setFormula('=now()')
  let hoursUsed = spreadsheet.getRange('Signature Sheet!F10:F10').setValue('')
  let timeFormula = spreadsheet.getRange('Signature Sheet!F11:F11').setFormula('=NOW()+TIME(F10,0,0)')

}