Javascript ‘start’ and ‘pause’ countdown buttons

I am a beginner at Javascript and I am creating a Pomodoro timer and the buttons are as seen in the image.

When the user clicks on either of the 3 top buttons I want the timer to switch to 25:00, 5:00 or 15:00, respectively. However, when clicked on, the timer initiates. I only want the timer to initiate once the ‘start’ button is clicked [Problem 1].

Secondly, when the pause button function is called, the timer display stops however it keeps running in the background [Problem 2] and to be honest I have little idea as how to resume the timer from where it was paused – despite searching the internet. Please can someone help me with this, I am really struggling here! Thank you!


var timer = {
  pomodoro: 25,
  longBreak: 15,
  shortBreak: 5
}
var currentTimerType = timer.pomodoro;

function timer_pomodoro() {
   currentTimerType = timer.pomodoro;
   timer_start();
}
function timer_short() {
  currentTimerType = timer.shortBreak;
  timer_start();
}
function timer_long() {
  currentTimerType = timer.longBreak;
  timer_start();
}

var minutesToAdd = 0;

function timer_start() {
  switch(currentTimerType) {
    case timer.pomodoro:
      minutesToAdd=25;
      break;
    case timer.shortBreak:
      minutesToAdd=5;
      break;
    case timer.longBreak:
      minutesToAdd=15;
      break;
  }
  var currentDate = new Date();
  var futureDate = new Date(currentDate.getTime() + minutesToAdd*60000);
  countDownDate = futureDate;
  var now = new Date().getTime();

  document.getElementById('seconds').innerHTML = '00';
  document.getElementById('minutes').innerHTML = minutesToAdd;
  x = setInterval(myTimer, 1000);
}



  function myTimer() {
  var currentDate = new Date();
  var futureDate = new Date(currentDate.getTime() + minutesToAdd*60000);
  var now = new Date().getTime();
  var distance = countDownDate - now;

  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);

  document.getElementById('seconds').innerHTML = seconds;
  document.getElementById('minutes').innerHTML = minutes;

  if (seconds == 0 & minutes == 0) {
    clearInterval(x);
  }
}

function pause() {
  clearInterval(x);
  }

I need one async function to wait for another one

I have 2 async functions – one gets ids of towns, and the second one takes these ids and gets {towns} objects. I am importing an API which is also async.

The first function works fine, but the second one returns

LOG catchTowns [Error: Not found]

code:

import { getTown, getTownIds } from "./api/towns" 

//getting IDs from API

const getTownIdsAsync = async () => {
  const asyncids = await getTownIds()
  return(asyncids.ids)
}

let idcka = new Promise((resolve, reject) => {
  resolve(getTownIdsAsync())
})
.then(result => {
  idcka = result
  for(i=0; i < idcka.length; i++){
  }
})
.catch(err => {
  console.log('catchIdcka', err)
})

//getting Towns from API
const getTownsByIdsAsync = async (ajdycka) => {
  const asyncTowns = await getTown(ajdycka)
  return(asyncTowns)
}

let towns = new Promise((resolve, reject) => {
  resolve(getTownsByIdsAsync())
})
.then(result => {
  towns = result
  console.log(towns)
})
.catch(err => {
  console.log('catchTowns', err)
})

Why I can’t loop array in javascript

I have such result which I want to include in the array

(2) [{…}, {…}]
   0: {id: 1, title: 'learn English fluently'}
   1: {id: 2, title: 'find job'}
   length: 2

When I pushed this in “result” array with this way

results.push(...snap.docs[0].data().lists)

I received array which one looks like this in console

[]

when I click this array looks like this

[]
  0: {id: 1, title: 'lorem ipsum'}
  1: {title: 'lorem ipsum random text', id: 2}
  length: 2

and when I try get single item for example

results[0]

I have message undefined

same problem when looping this array for example

results.forEach(item => {
 console.log(item)
})

In this case there is an empty console without any errors and messages

What is the Response of ‘DeleteUser’ Graphql mutation in sequelize?

In these parts of code bellow I wanna delete a user with specific id as I made it a primary key, However. I Know that the input is id but what makes me confused is what should I pass in the deleteUserResponse?

Here is schema/user.js file:

     input deleteUserInput {
        id: Int!
        }
    
        type deleteUserResponse {
        //What can I do Here 
        //to inform the user that record is deleted?
        }

and here is resolver/user.js file:

async deleteUser(root, { input: { id } }) {
        const user = await User.findOne({ where: { id } });
        user.destroy();
        }

When I run the code it delete the record but returns null and I wanna to return msg ,So any help?

Enable/Disable button based on password input length with Javascript

Trying to enable/disable a form button based on password input length but my code doesn’t work. If the length is less than 15 characters button should be disabled.

So far my simple html form

<form class="form" id="form1" method="POST" action="submit.php" accept-charset="UTF-8" autocomplete="off">
   <input type="password" placeholder="Password" id="passfield">
   <button type="submit" id="form-submit">CONNECT</button>
</form>

No username field needed in my case

and so far my Javascript code

function submit_btn() {

  var field = document.getElementById("passfield");
  var button = document.getElementById("form-submit");

  if (field.value.lenght < 15){
    button.setAttribute("disabled", "");
  }else{
    button.removeAttribute("disabled");
  }
};

React dropdown state updates on the second click [duplicate]

I’m actually facing an issue where the setQuery is updating on the second click whereas the selected is updating instantly. I tried to use the prevState idea but still the issue persists.

interface queryProps {
  intensity: string;
  categoryId: string;
  coachId: string;
  minDuration: number;
  maxDuration: number;
}

const Filter=()=>{
const [selected, setSelected] = useState<any>(undefined);
const [query, setQuery] = useState<queryProps>({
    intensity: '',
    categoryId: '',
    coachId: '',
    minDuration: 0,
    maxDuration: 1000,
  });

useEffect(() => {
    setQuery(prev => ({
      ...prev,
      intensity: selected?.intensity || prev.intensity,
      categoryId: selected?.categoryId || prev.categoryId,
      coachId: selected?.coachId || prev.coachId,
      minDuration: selected?.minDuration || prev.minDuration,
      maxDuration: selected?.maxDuration || prev.maxDuration,
    }));
    console.log('selected ', selected);
    console.log('query ', query);
  }, [selected]);

return(
<>
 <Dropdown
          label="Intensity"
          data={intensityItem}
          onSelect={setSelected}
        />

</>
)

}

How to use insertBefore and appendChild with a jQuery AJAX server side rendered html result

I basically need to use insertBefore and appendChild with a Server Side rendered HTML page jQuery AJAX result. I get the error: “Failed to execute ‘inserBefore’ on ‘Node’: parameter 1 is not of type ‘Node’.”

$.ajax({
    type:'POST',
    url:'example.com/my_ajax_call',
    data: {"my_data":my_data},
    success:function(data){
        parent_elem.prepend(data); //THIS IS THE JQUERY SOLUTION BUT I NEED PURE JS WHILE USING JQUERY AJAX REQUEST
    },
    fail:function(data){
        console.log(data);
        console.log('failed to load page');
    }
});

what I am trying to do is this:

$.ajax({
    type:'POST',
    url:'example.com/my_ajax_call',
    data: {"my_data":my_data},
    success:function(data){
        parent_elem.inserBefore(data, parent_elem.firstChild); //THIS IS WHAT I NEED BUT IT THROWS ERROR "Failed to execute 'inserBefore' on 'Node': parameter 1 is not of type 'Node'."
    },
    fail:function(data){
        console.log(data);
        console.log('failed to load page');
    }
});

Add server side jsp/php code to Google blogger website

I have a blog on Google’s blogspot.com and I want the page content to appear to the viewer/visitor depending on what he enters in a text field on the blog..e,g if he enters a particular interest/person then I want to show me only the related info. However I do not want to do it(hide/show) content based on client-side javascript..since anybody can do “View page source” and access/view the content. For this, I will have to write a server-side script(jsp) to send content back for display once the user enters something in an input field on his visit to the page. How can I achieve this while creating content via the blogger’s editing interface? I know there are gadgets that allow you to insert HTML/javascript(i assume is client-side javascript) content, but how do I achieve this on the server side of blogger website. Is there a sample code I can look at to achieve such design behavior?

Note: I do not want a full-fledged session/authentication management system. I can do with just taking some input from the text field and evaluating that input on the server-side.

adding variable to url with ajax

I’m sending dates using buttons and ajax in an html page.

        <input type="date" id="start_date" name="start_date">
        <input type="date" id="end_date" name="end_date">
        <button onclick="send()">Search</button>

    <script>
    

        function send() {
            var start_date = document.getElementById('start_date').value
            var end_date = document.getElementById('end_date').value
            $.ajax({
                url: '/page/hello.php?ctl=asd&act=bcd&start_date=' + start_date + '&end_date=' + end_date,
            });
        }
    </script>

When I check the data from here in my php page and look at the log, the dates come and I put these dates in my query. It works in query.

 $start_date = $_REQUEST['start_date'];
 $end_date = $_REQUEST['end_date'];

if ($start_date && $end_date) {
                $sql = "select * from table where user_id=" . $user_id . " and end_date>='" . $start_date . "' and end_date<='" . $end_date . "'";
            } else {
                $sql = "select * from table where user_id=" . $user_id . "  order by create_time desc limit 4";
            }

No problem so far. The problem is that at first I am fetching the 4 most recently created data with my sql query. When I select the dates and click the “search” button, the sql query works, but my html table does not change. So even though the dates are running in the background, I can’t reflect them on the table, why?

<table class="styled-table">
        <tbody>
            {if $data.video}
            {foreach from=$data.video item=item key=key}
            <tr class="active-row">
                <td>{$item.create_time}</td>
                <td>{$item.end_time}</td>
                <td>{$item.diff}</td>
                <td>
                    {$data.values[$key]}
                </td>

            </tr>

            {/foreach}
            {else}
            <tr class="active-row">
                <td>-</td>
                <td>-</td>
                <td>-</td>
                <td>
                    
                </td>

            </tr>
            {/if}

        </tbody>
    </table>

How to solve Messaging Error occuring Background Script to another script?

I am trying to send some selected text from the current page to an HTML page. Since, I can not do it directly, I am using message passing: content script to background script, then background script to the HTML page. But get error if the HTML is not open already, even then I get an error first time:

background.js:1 Uncaught (in promise) Error: Could not establish
connection. Receiving end does not exist.

If I close the page, then run again, this error will keep happening.

What is the solution ?

My code is given below:

popup.js

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
console.log("from popup = n"+request.bg);
})  

background.js

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {

chrome.tabs.create({url: 'popup.html'});
chrome.runtime.sendMessage({bg: request.exc})
                                                                              })

content.js

string=[];
function doc_keyUp(e) {
if (getSelectionText() != "")  {
if (e.key === '1') {
    string=getSelectionText();
    chrome.runtime.sendMessage({exc: string});
            
                   } 
                                }
                      } // doc_keyUp(e)
console.log('The program has started!!!');  
// register the handler 
document.addEventListener('keyup', doc_keyUp, false);                              

function getSelectionText() {
    var text = "";
     text = window.getSelection().toString();
    if (window.getSelection) {
        text = window.getSelection().toString();
    } 
    else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    return text;    
}

popup.html

<html>
<script src="popup.js">
</script>
</html>

I am doing this to buid a chrome extension, so if required then:

manifest.json

{
  "name": "",
  "version": "1.0",
  "description":"",
  "manifest_version": 3,
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ],
  "action": {
    "default_title": "T"
  },
  "background":{
    "service_worker": "background.js"
  },
  "permissions": ["tabs"]
}

Post Script:

  1. Is there an alternative way to send data directly from content script to script of an HTML (e.g. here popup.js is such script) without going through background script?
  2. Is there a to get a variable from background script without message passing to any other script? I saw solutions using chrome.extension.getBackgroundPage() but it does not work anymore after manifest v3. Is there anything else?

JavaScript, fetch, API

i want to do the following: get a random name with fetch from this website https://swapi.dev/api/people/, which i did and i can see it in my html page then i want also to get a random planet, here i need to access the homeworld key, and to return the link, before returning the link i formatted to get a random url and from this one i also have to show the name of the planet on my page. The first fetch works fine, at least i think but the 3rd .then() is not working or at least i don’t know how to access the information from the homeworld url. This is my first time trying fetch() and it will be nice if you guys can help me telling where i did wrong in code and maybe different solutions but not so complicated 😀 tnks

let randomNumber = Math.floor(Math.random()*9)


const fetchPromise = fetch("https://swapi.dev/api/people/");

let test
let test2
fetchPromise
    .then((response) => {
        if (!response.ok) {
            throw new Error(`Http error: ${response.status}`);

        }
        return response.json();
    })
    .then((json) => {
        console.log(json.results[randomNumber].name)
        showRandomUserData(json)
        test = json.results[0].homeworld
        test = test.slice(0, -2)
        // console.log(test + randomNumber + "/");
        // console.log(test + "/" + randomNumber + "/");
        test = test + randomNumber + "/";
        return test
        // return fetch("https://swapi.dev/api/planets/2/");
    })
    .then((test) => {
        console.log(test.results[0].name);
        // console.log(json.results[0].name);

        // console.log(json)
        // console.log(json.results[randomNumber].name);
    })

showRandomUserData = (randomUser) => {
    document.querySelector("#name").innerHTML =
        randomUser.results[randomNumber].name;
    document.querySelector("#age").innerHTML = test.results[randomNumber].name;
   
}


Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client using Express

On the server part, I have the following code:

app.post("/getdevicesjson", (req, res) => {
    var username = req.body.username;
    var password = crypto.createHash('sha256').update(req.body.password).digest('hex');
    try {
        db.all(
            `SELECT * FROM Users WHERE username='${username}';`, 
            function(err, row) {
                if(err) {
                } else if(row.length == 0) {
                    res.status(404).end();
                    return;
                } else {
                    if(password == row[0].password) {
                        db.all(
                            `SELECT * FROM Users WHERE username='${username}';`,
                            function(err, row) {
                                if(err) {
                                    res.status(404).end();
                                    return;
                                } else {
                                    return res.json(json);
                                    
                                    //res.json(row[0].devices_json);
                                }
                            }
                        );
                        res.status(200).end();
                        return;
                    } else {
                        res.status(404).end();
                        return;
                    }
                }
            }
        );
    } catch(e) {
        console.log(e);
    }

});

The following error:

node:internal/errors:465
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:372:5)
    at ServerResponse.setHeader (node:_http_outgoing:576:11)
    at ServerResponse.header (/home/bred/Documents/Projekat/Backend/node_modules/express/lib/response.js:794:10)
    at ServerResponse.json (/home/bred/Documents/Projekat/Backend/node_modules/express/lib/response.js:275:10)
    at Statement.<anonymous> (/home/bred/Documents/Projekat/Backend/server.js:78:48)
    at Statement.replacement (/home/bred/Documents/Projekat/Backend/node_modules/sqlite3/lib/trace.js:25:27) {
  code: 'ERR_HTTP_HEADERS_SENT'
}

Occurs on the line

return res.json(json);

If I return something that is not a json object on that line, everything works fine.
Json object that is used looks like this:

var json = 
[
    {
        name:'Prozor kuhinja',
        id:'542123',
        triggers:
        [
            {
                time:'1655646074815',
                state:'low'
            },
            {
                time:'1654644074815',
                state:'high'
            }
        ]
    },
    {
        name:'Prozor dnevna soba',
        id:'542124',
        triggers:
        [
            {
                time:'1655646074815',
                state:'low'
            },
            {
                time:'1654644074815',
                state:'high'
            }
        ]
    }
];

I’m pretty stuck on this one… Most of the replies here said I should use returns, which I did, but it didn’t help.
Thanks!

What is the best practice method to fetch GraphQL data within a Magento Module?

I wish to pull in filtered product data via JavaScript from within a Magento module? Using graphql to only retrieve the data I want.

I can do this using the various graphql endpoints, however, I’m currently doing this by converting the HTTP calls to jQuery in Postman (for the moment). This feels messy.

It’s a much simpler task when calling from a React or other SPA as I’d just use axios, Apollo etc.

From what I have read, the Magento dev docs do not include any specific approach to calling graphql endpoints within classic Magento 2 modules.

What would the most efficient way to approach this?