My wordpress cache plugin won’t save in cache all the js css files just before the closing body tag

I create my own caching plugin, but I dont succeded to save in cache correctly the full entire page

function checkCache() {
    $getFile = str_replace('/', ",", $_SERVER['REQUEST_URI']);
    if( is_user_logged_in() ) {
       
        $user = wp_get_current_user();
        $roles = ( array ) $user->roles;
        if(in_array('customer-pro', $roles)) {
            $role = 'pro';
        } else if ($roles[0] == 'customer' && count($roles) == 1) {
            $role = 'club';
        } else if ($roles[0] == 'naya_client' && count($roles) == 1) {
            $role = 'naya';
        } else if ($roles[0] == 'administrator' && count($roles) == 1) {
            $role = 'admin';
        }
    } else {
    $role = 'invite';
    }
    $isCached = file_exists(WP_PLUGIN_DIR."/supercache/files/".$role."/".$getFile.'.html');
    
    if($isCached === true) {
        echo '<!--already in cache-->';
        readfile((WP_PLUGIN_DIR . "/supercache/files/".$role."/".$getFile.'.html'));
        exit;
    } else {
        echo '<!--putting in cache-->';
        ob_start();
    }
}

function saveCache() {
    $getFile = str_replace('/', ",", $_SERVER['REQUEST_URI']);
    if( is_user_logged_in() ) {
        $user = wp_get_current_user();
        $roles = ( array ) $user->roles;
        if(in_array('customer-pro', $roles)) {
            $role = 'pro';
        } else if ($roles[0] == 'customer' && count($roles) == 1) {
            $role = 'club';
        } else if ($roles[0] == 'naya_client' && count($roles) == 1) {
            $role = 'naya';
        } else if ($roles[0] == 'administrator' && count($roles) == 1) {
            $role = 'admin';
        }
    } else {
        $role = 'invite';
    }
    file_put_contents(WP_PLUGIN_DIR . "/supercache/files/".$role."/".$getFile.".html", ob_get_contents());
    ob_end_clean();
    header("Refresh:0");
}


add_action('wp_head', 'checkCache');


add_action('wp_footer', 'saveCache');

I wanna save the page in a cache file, but it does not work as expected, all the JS and CSS files just before the tag are not saved in my cache file, why ?

Thanks in advance

Receiving “You need to enable JavaScript to run this app.” error with my Firebase API

I’m making an API with firebase, however, whenever I try and call it through Postman, I receive a “You need to enable JavaScript to run this app.” error.

Here’s a bit of my index.js. I set it to a basic one for now.

//Functions
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const express = require('express');
const cors = require('cors');
const app = express();


//Routes
app.get('/api/test', (req, res) => {
  return res.status(200).send("Hello! You have reached my Test API. All it does is this!")
});



//Export the api to Firebase cloud functions
exports.app = functions.https.onRequest(app)

It’s being hosted with localhost for now. I can provide more info if needed.

I’ve proofread the code, and nothing seems to be wrong.

I’ve tried many other instances of this question, and have had no success. I’m happy to share some other documents

Why does this function not work when i call it to check the win?

When i call my checkWin() function it does not display my win message after the click event. I have a playerChoice() event when clicking each cell with X or O then i have called the checkWin function outside this function. What am i missing here?

let currentPlayer = 'X';

const xScore = document.querySelector('#X-score');
const oScore = document.querySelector('#O-score');
const cellElements = document.querySelectorAll('.cell');
const resultMessage = document.querySelector('#results');
const playerTurn = document.querySelector('.player-turn');

// array of possible win combinations  
const winningMoves = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6]   
];

for (const cellElem of cellElements) {
    cellElem.addEventListener('click', playerChoice);
}

function playerChoice(event) {
    const clickedCell = event.target;
    clickedCell.textContent = currentPlayer;

        playerTurn.textContent = currentPlayer === 'X' ? 'O turn' : 'X turn';
        
        currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
    
    }

    checkWin();

function checkWin() {
   for (const winningMove of winningMoves) {
     const [a, b, c] = winningMove;
    if (currentPlayer[a].textContent !== '' && currentPlayer[a].textContent === currentPlayer[b].textContent && currentPlayer[a].textContent === currentPlayer[c].textContent) {
        resultMessage.textContent = `${currentPlayer} wins`
return true;
   }
}
return false
}

what is the most efficient and recommended way to stop forEach iteration in javascript [duplicate]

I am here to know what is the best and what is the worst approach to use. I were asked by an interviewer and at that time I has only one solution to write which was try-catch and return statement (try-0 in below example) and i am sure she was not expecting the one I wrote.

So am here to get the guidance from the expert of JavaScript filed. and will appreciate it.

Try-0. usage of return

array = [1,2,3,4,5,6]

array.forEach(function loop(number){
    if(loop.stop){ return; }

    if(number==3){ loop.stop = true; }
     console.log("Number: "+ number)
});

Try-1. Use of try-catch:

const array = [1, 2, 3, 4, 5, 6];

try {
  array.forEach((number) => {
    if (number === 4) {
      throw new Error("Stopping the loop with try-catch.");
    }
    console.log("Number:", number);
  });
} catch (error) {
  console.log("Caught an error:", error.message);
}

Try-2. Use of Array.prototype.some

var ar = [1,2,3,4,5,6];

ar.some(function(item){
  if(item == 4){
     return true;
  }
  console.log("Number:", item);
});

Try-3. Use of Array.prototype.every

let array = [1,2,3,4,5,6];
array.every(function(item, index) {
  console.log("Number: "+item)
  if (item==3) return false
  else return true
})

Thank you for your insights and guidance!

JSDoc, DocDash, @typedef does not appear in table of contents

I am trying to get my table of contents to list constants, functions, and typedefs for each of my modules, allowing for searchable documentation. I am using DocDash with JSDoc. JSDoc appears to be recognizing the types nicely, but the type defs do not appear in the table of contents.

Code definition example


/**
 * @typedef ActivityOptions
 * @memberof module:CardSession
 * @property {boolean} quiz ...yada yada...truncated.
 */

//Using JSON Schema compatible constant as the type definition.
export const ActivityOptions = {
    type: 'object',
    properties: {
        quiz: {type: 'boolean'},
        canSkip: {type: 'boolean'},
        repeat: {type: 'boolean'},
        timeLimit: {type:'number'},//in percent
        questionLimit: {type: 'number'},
        passingProps: PassingProps,
        prereq: {
            type: 'array',
            members: {type: 'string'}
        },
        completion: {
            type: 'array',
            members: {type: 'string'}
        },
        rules: EnumActivityRules
    },
    required: ['quiz','canSkip','repeat','passingProps','prereq','completion','rules'],
    additionalProperties: false
};

Here is my jsdoc.json. Could provide full file if relevant, but here is the ‘docdash’ member only.

{
    "docdash": {
        "static": true,
        "sort": true,
        "sectionOrder": [
            "Classes",
            "Tutorials",
            "Modules",
            "Externals",
            "Events",
            "Namespaces",
            "Mixins",
            "Interfaces"
        ],
        "disqus": "musicards.io",
        "search": true,
        "commonNav": false,
        "collapse": true,
        "wrap": false,
        "typedefs": true,
        "navLevel": 1,
        "private": true,
        "removeQuotes": "none",
        "scripts": [],
        "ShortenTypes": false,
        "scopeInOutputPath": true,
        "nameInOutputPath": true,
        "versionInOutputPath": true
  }
    
}

screenshot
On the menu, the typedef is correctly listed in the module, but it is buried under all the functions and not shown in the table of contents. Furthermore, the quick search bar does not reveal the typedef as a result because of this.

screenshot

How to store new items in localstorage or sessionstorage in javascript?

I am really new and total lame in javascript. I am trying to learn it but if you will see the code I made you’ll probably facepalm yourself because of how I put html tags in the innerHTML >:D anyway… to the problem.

I would like to built a chat without php (don’t ask why).

Without database I made a thing that if you click “send message” your message will only show until you refresh the page and I get an e-mail with the message (for later to add it inside the embed code; yes it is dumb).

Here is an working example without local or sessionstorage (screenshot)

Here is a code without implemented the storage function(screenshot)

However I would like to store the message from the user for at least one session. I was searching for some time and discover the sessionStorage. Wow that is exactly what I needed. But as I am extremely bad I am still getting the only one last input you put there

as you can see on this image here…

And if I am not typing anything, like only open the chat on a new session I am getting the “null” message. Yes I understand that if there is no data inserted into a textbox I will get a result such as null… But I saw some people can make it that if there was no message inserted the null was hidden somewhere. And also that it can save newer messages aswell and store them.

I would really be extremely thankful if someone can help me to figure this out… As I am extreme beginner… thank you guys, love you!

Here is my lame *** code so take a laugh and then help me please ♥

var storeditem = localStorage.getItem("storeditem");

function pridat() {
                    
                    var item = document.sample.message.value;
                    var msg = document.sample.message.value;
    
                    var obal = document.createElement('div');
                    obal.setAttribute("class", "you");
    
                    var tr = obal.appendChild(document.createElement('div'));
                    tr.setAttribute("class", "message");
    
                    var td1 = tr.appendChild(document.createElement('div'));
                    td1.setAttribute("class", "text");
                    td1.textContent=msg;
                    localStorage.setItem("storeditem", item);
                    document.getElementById("chat").appendChild(obal);

                }

window.onload = function get(){
localStorage.getItem("storeditem");

document.getElementById("chat").innerHTML = "<div class='message'><p class='text'>hey</p>
</div><div class='time'>13:28</div><div class='you'><div class='message'>
<p class='text'>" + storeditem + "</p></div></div>";

}

Display X, Y coordinate of a click position at the Sankey plot created by plot_ly in R?

Below is a sample program to create a Sankey plot using plot_ly in R Shiny. I prefer it to display the X, Y coordinates when I click at any position within the plot. But the program does not work well. It generates the diagram but unable to display the X, Y coordinates of the click position.

Can anyone provide a solution? Thanks a lot!

library(shiny)
library(plotly)

ui <- fluidPage(

tags$head(
  titlePanel("Draggable Text on Sankey Diagram"),
  sidebarLayout(

      plotlyOutput("plot"),
verbatimTextOutput("click")
  )
))

server <- function(input, output, session) {

    js <- "
    function(el, x){
      var id = el.getAttribute('id');
      var gd = document.getElementById(id);
      var d3 = Plotly.d3;
      Plotly.update(id).then(attach);
        function attach() {
          gd.addEventListener('mousemove', function(evt) {
            var xaxis = gd._fullLayout.xaxis;
            var yaxis = gd._fullLayout.yaxis;
            var bb = evt.target.getBoundingClientRect();
            var x = xaxis.p2d(evt.clientX - bb.left);
            var y = yaxis.p2d(evt.clientY - bb.top);
            Plotly.relayout(gd, 'xaxis.title', 'x: ' + parseFloat(x).toFixed(2));
            Plotly.relayout(gd, 'yaxis.title', 'y: ' + parseFloat(y).toFixed(2));
            // Plotly.relayout(gd, 'title', ['x: ' + x, 'y : ' + y].join('<br>'));
          });
        };
    }
"

  
  output$plot <- renderPlotly({
    # Sample Sankey diagram
    fig <- plot_ly(
      type = "sankey",
      orientation = "h",
      node = list(
        label = c("A", "B", "C", "D", "E")
      ),
      link = list(
        source = c(0, 1, 0, 2, 3),
        target = c(2, 3, 4, 4, 4),
        value = c(8, 4, 2, 8, 4)
      )
    ) %>% onRender(js, data = "clickposition")
  })

output$click <- renderPrint({
    input$clickposition
  })
}

shinyApp(ui, server)

Image slider issue with margin-left

I am trying to create an image slider with 4 buttons, each sliding in a different div as a slide.
I want to add some animation to it and slide over the top with a margin on the left side of 400px and animate it to 0px once its visible.

However when the slide is not visible, it throws the page off and still adds the width to it. There is a scroll bar on the bottom where the page can be scrolled over with 400px showing the slide that is actually not visible.

I don’t know how to figure out this issue, but I don’t want just to disable the scroll on the X.
Any suggestions how to make this work?

https://jsfiddle.net/v6g5zs9t/

$(document).ready(function() {

  $("#content-slide-dot-1").click(function(){
    $("#content-slide-1").css({"z-index": "100"},"300");
    $("#content-slide-1").animate({opacity:1, "margin-left": "0px"},"300");
    $("#content-slide-controls").css({"z-index": "200"},"100");

    $("#content-slide-dot-1").addClass("active");
    $("#content-slide-dot-2").removeClass("active");
    $("#content-slide-dot-3").removeClass("active");
    $("#content-slide-dot-4").removeClass("active");

    $("#content-slide-2").css({"z-index": "1"});
    $("#content-slide-3").css({"z-index": "1"});
    $("#content-slide-4").css({"z-index": "1"});

    $("#content-slide-2").delay("400").animate({opacity:0, "margin-left" : "400px" },"300");
    $("#content-slide-3").delay("400").animate({opacity:0, "margin-left" : "400px" },"300");
    $("#content-slide-4").delay("400").animate({opacity:0, "margin-left" : "400px" },"300");
  });


  $("#content-slide-dot-2").click(function(){
    $("#content-slide-2").css({"z-index": "100"},"300");
    $("#content-slide-2").animate({opacity:1, "margin-left": "0px"},"300");
    $("#content-slide-controls").css({"z-index": "200"},"100");

    $("#content-slide-dot-2").addClass("active");
    $("#content-slide-dot-1").removeClass("active");
    $("#content-slide-dot-3").removeClass("active");
    $("#content-slide-dot-4").removeClass("active");

    $("#content-slide-1").css({"z-index": "1"});
    $("#content-slide-3").css({"z-index": "1"});
    $("#content-slide-4").css({"z-index": "1"});

    $("#content-slide-1").delay("400").animate({opacity:0, "margin-left" : "400px" },"300");
    $("#content-slide-3").delay("400").animate({opacity:0, "margin-left" : "400px" },"300");
    $("#content-slide-4").delay("400").animate({opacity:0, "margin-left" : "400px" },"300");
  });


  $("#content-slide-dot-3").click(function(){
    $("#content-slide-3").css({"z-index": "100"},"300");
    $("#content-slide-3").animate({opacity:1, "margin-left": "0px"},"300");
    $("#content-slide-controls").css({"z-index": "200"},"100");

    $("#content-slide-dot-3").addClass("active");
    $("#content-slide-dot-1").removeClass("active");
    $("#content-slide-dot-2").removeClass("active");
    $("#content-slide-dot-4").removeClass("active");

    $("#content-slide-1").css({"z-index": "1"});
    $("#content-slide-2").css({"z-index": "1"});
    $("#content-slide-4").css({"z-index": "1"});

    $("#content-slide-1").delay("400").animate({opacity:0, "margin-left" : "400px" },"300");
    $("#content-slide-2").delay("400").animate({opacity:0, "margin-left" : "400px" },"300");
    $("#content-slide-4").delay("400").animate({opacity:0, "margin-left" : "400px" },"300");
  });


  $("#content-slide-dot-4").click(function(){
    $("#content-slide-4").css({"z-index": "100"},"300");
    $("#content-slide-4").animate({opacity:1, "margin-left": "0px"},"300");
    $("#content-slide-controls").css({"z-index": "200"},"100");

    $("#content-slide-dot-4").addClass("active");
    $("#content-slide-dot-1").removeClass("active");
    $("#content-slide-dot-2").removeClass("active");
    $("#content-slide-dot-3").removeClass("active");

    $("#content-slide-1").css({"z-index": "1"});
    $("#content-slide-2").css({"z-index": "1"});
    $("#content-slide-3").css({"z-index": "1"});

    $("#content-slide-1").delay("400").animate({opacity:0, "margin-left" : "400px" },"300");
    $("#content-slide-2").delay("400").animate({opacity:0, "margin-left" : "400px" },"300");
    $("#content-slide-3").delay("400").animate({opacity:0, "margin-left" : "400px" },"300");
  });

});

If you have an idea on how to make the JS part better, I would appreciate that as well 🙂

Thanks!

Uncaught TypeError after using button

// ... created frameUp, frameDown, frameRight, frameLeft using createElement("DIV")

const button = document.getElementById("button")
button.addEventListener("click", addBorder); <---- error occurs on this line

// draws the top, bottom, right, left edges of the border
function addBorder() {
    document.body.appendChild(frameUp);
    document.body.appendChild(frameDown);
    document.body.appendChild(frameRight);
    document.body.appendChild(frameLeft);
}

border.js^

 ...
    <button id="button">Click me to add border!</button>
    <script src="border.js"></script>
...

taken from HTML^

I am trying to make a border around the chrome screen using a chrome extension, which works fine if I don’t try to incorporate a button. When I change it to incorporate a button event listener, it is telling me that it cannot read properties of Null. My goal is to press the button->the border appears on screen.

enter image description here

My goal is: press the button –> the border appears on screen.

Without the button, it works fine: drawing a border upon the extension booting up.

With the button, it throws an error: “Uncaught TypeError: Cannot read properties of null (reading ‘addEventListener’)”

I read numerous other posts but none of their solutions helped me solve the problem. I checked that the button id name was correct, rearranged the order of my code, etc.

Also, if I wrap the whole javascript code within a:

addEventListener("DOMcontentLoaded", function ()) {

It draws a border around the extension popup window instead of the browser, which is not what I want.

How to solve the problem of GEE computation time out?

The overall code is the same. At first, I used more than 1,000 sample points to classify the land in study area A. At this time, the code was completely normal; then I replaced more than 1,000 sample points with more than 10,000 sample points, and changed study area A into study area B. The code The result cannot appear, and it displays: computation time out!

I expect to be able to solve the calculation timeout problem of GEE.

I need to add a user in express

I have a user model, which has a table in the db:

/* eslint-disable import/no-extraneous-dependencies */
import Sequelize, { Model } from 'sequelize';
import bcryptjs from 'bcryptjs';

export default class User extends Model {
  static init(sequelize) {
    super.init(
      {
        username: {
          type: Sequelize.STRING,
          defaultValue: '',
          validate: {
            len: {
              args: [3, 40],
              msg: 'User must have between 3 and 40 characters',
            },
          },
        },
        email: {
          type: Sequelize.STRING,
          defaultValue: '',
          unique: {
            msg: 'Email already exists',
          },
          validate: {
            isEmail: {
              msg: 'invalid email',
            },
            isUnique(value, next) {
              User.findOne({ where: { email: value } })
                .then((user) => {
                  if (user) {
                    return next('email already exists, try another');
                  }
                  return next();
                })
                .catch((err) => next(err));
            },
          },
        },
        password_hash: {
          type: Sequelize.STRING,
          defaultValue: '',
        },
        password: {
          type: Sequelize.VIRTUAL,
          defaultValue: '',
          validate: {
            len: {
              args: [6, 8],
              msg: 'The password must be between 6 and 8 characters long',
            },
          },
        },
      },
      { sequelize },
    );

    this.addHook('beforeSave', async (user) => {
      if (user.password) {
        user.password_hash = await bcryptjs.hash(user.password, 8);
      }
    });

    return this;
  }

  passwordIsValid(password) {
    return bcryptjs.compare(password, this.password_hash);
  }

  static associate(models) {
    this.belongsToMany(models.Photo, models.Message, models.Contact, { foreignKey: ['user_id', 'user_idm', 'userId'] });
  }
}

I have a contacts model, which has a table in the db, where a logged in user will need to add another user with their name and email:

/* eslint-disable import/no-extraneous-dependencies */
import { Model, DataTypes } from 'sequelize';

export default class Contact extends Model {
  static init(sequelize) {
    super.init(
      {
        userId: {
          type: DataTypes.INTEGER,
          allowNull: false,
          references: {
            model: 'users',
            key: 'id',
          },
        },
        userEmail: {
          type: DataTypes.STRING,
          allowNull: false,
        },
        userUsername: {
          type: DataTypes.STRING,
          allowNull: false,
        },
      },
      {
        sequelize,
        tableName: 'contacts',
      },
    );
  }

  static associate(models) {
    this.belongsTo(models.User, { foreignKey: 'userId' });
  }
}

I have to join one user to another, but when I use the function it only returns this: “Internal server error”, look at the controller here:

import Contact from '../models/Contact';
import User from '../models/User';

class ContactController {
  async store(req, res) {
    try {
      const { username, email } = req.body;

      const user = await User.findByPk(req.userId);

      if (!user) {
        return res.status(400).json({
          errors: ['User does not exist'],
        });
      }

      const isContactAdd = await Contact.findOne({
        where: {
          userId: user.id,
          userEmail: email,
        },
      });

      if (isContactAdd) {
        return res.status(400).json({
          errors: ['User already added'],
        });
      }

      const contact = await User.findOne({
        where: {
          email,
        },
      });

      if (!contact) {
        return res.status(404).json({
          errors: ['Contact not found'],
        });
      }

      await Contact.create({
        userId: user.id,
        userEmail: email,
        userUsername: username,
      });
      return res.json({ message: 'Friend added successfully' });
    } catch (e) {
      return res.status(400).json({
        errors: ['Internal server error'],
      });
    }
  }
}

export default new ContactController();

How do I replace the text label of a button using javascript and without having to click?

I am trying to change the label of the ‘Save’ button to ‘Next’ using javascript and without having to click on Save first.

Save button

<input type="button" name="ctl01$SaveButton" value="Save" onclick="if(this.disabled)return false;accountCreatorInstance_ctl01_TemplateBody_WebPartManager1_gwpciNewContactAccountCreatorCommon_ciNewContactAccountCreatorCommon.ShowErrors();if(!RunAllValidators(new Array('52503d2c-d362-4864-a72d-5f883619889d'), true)) return false;this.disabled='disabled';WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl01$SaveButton&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, true))" id="ctl01_SaveButton" title="Save" class="PrimaryButton TextButton Save" data-ajaxupdatedcontrolid="ContentDiv" translate="yes">

I’ve tried many different versions but nothing seems to work. I’m no JS expert so any help is appreciated.

document.getElementById(‘ctl01_SaveButton’).innerHTML = ‘Next’;

I just want the Save button to show ‘Next’ instead of Save.

JavaScript | Imported module breaking inside for loop

I am writing a program which performs Eratosthenes’ Sieve up to a given limit. This is the current code:

const { isPrime } = require(`./numPropFuncs.js`);

const limit = 30;
const primes = [];

const eratosthenesSieve = num => {
    for (let i = 0; i <= num; i++) {
        if (isPrime(i)) {
            primes.push(i);
        };
    };
};

eratosthenesSieve(limit);

console.log(primes.join(`, `);

It imports the following module to test whether a number is prime:

const resources = require(`./factorList.js`);

const isPrime = num => {
    resources.factorList(num);
    if (resources.factors.length === 2) {
        return true;
    } else {
        return false;
    };
};

Which in turn imports the following module which provides an array of all factors of a given number:

const factors = [];

const factorList = (num) => {
  for (let i = 0; i <= num; i++) {
    if (num % i === 0) {
      factors.push(i);
    };
  };
};

Both modules have been tested to ensure they work and have been imported properly. The issue is that when isPrime() is called inside the for loop of eratosthenesSieve() it returns false for every iteration, including when prime numbers are passed as the argument.

I am testing eratosthenesSieve() using 30 as the limit as it’s easy to verify the result. The logged output should be the string: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29. Instead it either logs nothing, or in the case of logging primes without .join(), []. After having the loop log ${i}: ${isPrime(i)} on each iteration I realized isPrime() was returning false for every number (i.e logging “0: false” … “30: false”). I tested isPrime() outside of eratosthenesSieve() and inside eratosthenesSieve() but outside the for loop and both times it worked properly.

I thought maybe it was a scope issue, and so I tried using a seperate variable, declared inside eratosthenesSieve() but outside the loop, as the test number instead of i:

const eratosthenesSieve = num => {
    let testNumber = 0;
    for (let i = 0; i <= num; i++) {
        if (isPrime(testNumber)) {
            primes.push(testNumber);
        };
        testNumber++;
    };
};

This had solved a different problem I was having with another program’s loop, though that program didn’t use isPrime(), (I don’t remember what that program’s issue was). However this solution did not work for the Eratosthenes’ Sieve program.

I tried simply logging ${7}: ${isPrime(7)} on every iteration while commenting out the rest of the code inside eratosthenesSive() just to see what would happen. Oddly enough, it logged 7: true on the first iteration (the correct output, obviously), but logged 7: false on every one of the 29 successive iterations.

Finally, I tried refactoring to have the loop start at 1 in case starting at 0 was causing problems. This also did not help.

I am at a loss as to what is going on here and how to fix it. Thank you so much in advance for your help. (My runtime environment is Node.js in VS code on MacOS Sonoma)

React Web app update page won’t get the id

i’ve been trying to make an update page for a web app page that has values from a database.
i go to the update page from the student page where i have 20 different students listed , let’s say that i chose student 3, the page link is supposed to be something like localhost:3000/update/3 but it returns as localhost:3000/update/undefined. When i try updating the update button doesn’t send me back to the student page (or any page at all) so basically i’m stuck at the update page.

Here are my codes for some of the pages (also i’m using a Navbar as well at which at first made me think maybe that’s the issue but i don’t think it’s relevant to the case so it’s not included.)

Studetn.js (http://localhost:3000/Studetn)

import React, { useEffect , useState} from 'react'
import axios from 'axios'
import { Link } from 'react-router-dom'


function Studetn() {
       const [student, setStudent] = useState([])
       useEffect(()=>{
           axios.get('http://localhost:8081/')
           .then(res => setStudent(res.data))
           .catch(err => console.log(err));
       }, [])


       // Function to format the date
       const formatDate = (dateString) => {
        // Assuming dateString is now in the 'YYYY-MM-DD' format
        return new Date(dateString).toLocaleDateString('en-GB', {
            year: 'numeric',
            month: 'short',
            day: '2-digit',
            timeZone: 'UTC'
        });
    };


  return (
    <div className='d-flex v-100 bg-primary justify-content-center '>
        <div className='w-50 bg-white rounded p-3'>
            <Link to="/create" className='btn btn-success'>Add +</Link>
            <table className='table'>
                <thead>
                    <tr>
                    <th>Student ID</th>   
                    <th>Name</th>
                    <th>Surname</th>
                    <th>Department</th>
                    <th>Date of Birth</th>
                    <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    {
                        student.map((data,i)=> (
                            <tr key={i}>
                                <td>{data.student_id}</td> 
                                <td>{data.first_name}</td>
                                <td>{data.last_name}</td>
                                <td>{data.department}</td>
                                <td>{formatDate(data.date_of_birth)}</td>
                                <td>
                                {console.log("Generated Link:", `/Studetn/update/${data.ID}`)}
                                    <Link to={`/update/${data.ID}`} className='btn btn-primary'>Update</Link>
                                    <button className='btn btn-danger ms-2'>Delete</button>
                                </td>
                            </tr>
                        ))
                    }
                </tbody>
            </table>

        </div>
    </div>
  )
}

export default Studetn

server.js (my backend)

const express = require("express");
const cors = require("cors");
const mysql = require("mysql");

const app = express();
app.use(express.json())
app.use(cors());

 const db = mysql.createConnection({
    host:"localhost",
    user: "root",
    password: "AGad-dags4",
    database: "students"
 })

 app.get("/", (req, res) => {
    const sql = "SELECT student_id, first_name, last_name, DATE_FORMAT(date_of_birth, '%Y-%m-%d') AS formatted_date, department FROM student";
    db.query(sql, (err, data) => {
        if (err) return res.json(err);
        
        // Process data and send response with formatted dates
        const formattedData = data.map(student => ({
            ...student,
            date_of_birth: student.formatted_date, // Replace date_of_birth with the formatted date
        }));

        return res.json(formattedData);
    });
});

 app.get("/concessionscholarship", (req, res) => {
    const sql = "SELECT * FROM concessionscholarship";
    db.query(sql,(err, data) => {
        if(err) return res.json(err);
        return res.json(data);
    })
 })

 app.get("/fee", (req, res) => {
    const sql = "SELECT * FROM fee";
    db.query(sql,(err, data) => {
        if(err) return res.json(err);
        return res.json(data);
    })
 })

 app.get("/marks", (req, res) => {
    const sql = "SELECT * FROM marks";
    db.query(sql,(err, data) => {
        if(err) return res.json(err);
        return res.json(data);
    })
 })

 app.get("/stream", (req, res) => {
    const sql = "SELECT * FROM stream";
    db.query(sql,(err, data) => {
        if(err) return res.json(err);
        return res.json(data);
    })
 })

 app.post('/create', (req,res)=>{
    const sql = "INSERT INTO student(first_name,last_name,date_of_birth,department) VALUES (?)";
    const values = [
        req.body.first_name,
        req.body.last_name,
        req.body.date_of_birth,
        req.body.department
    ];
    db.query(sql,[values], (err,data)=> {
        if(err) return res.json("Error");
        return res.json(data);
    })
 })

 app.put('/Studetn/update/:id', (req,res)=>{
    const sql = "update student set first_name = ?, last_name = ?, date_of_birth = ?, department = ? where ID = ?";
    const values = [
        req.body.first_name,
        req.body.last_name,
        req.body.date_of_birth,
        req.body.department
    ];
    const id = req.params.id;
    
    db.query(sql,[...values, id], (err,data)=> {
        if(err) return res.json("Error");
        return res.json(data);
    })
 })

app.listen(8081, () => {
    console.log("listening");
})

App.js (my routes)

import React from "react";
import 'bootstrap/dist/css/bootstrap.min.css'
import{BrowserRouter, Routes, Route} from 'react-router-dom'
import Student from './pages/Studetn';
import Scholarship from "./pages/concessionscholarship";
import Fee from "./pages/fee";
import Marks from "./pages/marks";
import Stream from "./pages/stream";
import Navbar from "./components/Navbar";
import Home from "./pages/";
import CreateStudent from "./pages/CreateStudent";
import UpdateStudent from "./pages/UpdateStudent";

function App() {
  return (
    <div className="App">
      <BrowserRouter>
      <Navbar />
       <Routes>
         <Route exact path='/' element={<Home />}></Route>
         <Route path="/Studetn" element={<Student />} />
         <Route path="/create" element={<CreateStudent />} />
         <Route path="/update/:id" element={<UpdateStudent />} />
         <Route path="/concessionscholarship" element={<Scholarship />} />
         <Route path="/fee" element={<Fee />} />
         <Route path="/marks" element={<Marks />} />
         <Route path="/stream" element={<Stream />} />
       </Routes>
      </BrowserRouter>
    </div>
  );
}

export default App;

UpdateStudent.js (my “update” page that is supposed to be working)

import axios from 'axios';
import React, { useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom';

function UpdateStudent() {
    const [first_name,setfirst_name]= useState('')
    const [last_name,setlast_name]= useState('')
    const [date_of_birth,setdate_of_birth]= useState('')
    const [department,setdepartment]= useState('')
    const{id} = useParams();
    const navigate = useNavigate();

    function handleSubmit(event){
        event.preventDefault();
        axios.put(`http://localhost:8081/update/${id}`, {first_name,last_name,date_of_birth,department})
        .then(res=>{
            console.log(res);
            navigate('/');
        }).catch(err=> console.log(err));
    }


  return (
    <div className='d-flex vh-100 bg-primary justify-content-center align-items-center'>
        <div className='w-50 bg-white rounded p-3'>
            <form onSubmit={handleSubmit}>
                <h2>Update Student</h2>
                <div className='mb-2'>
                   <label htmlFor="">Name</label>
                   <input type="text" placeholder='Enter Name' className='form-control' 
                   onChange={e=> setfirst_name(e.target.value)} ></input>
                </div>
                <div className='mb-2'>
                   <label htmlFor="">Surname</label>
                   <input type="text" placeholder='Enter Surname' className='form-control'
                   onChange={e=> setlast_name(e.target.value)} ></input>
                </div>
                <div className='mb-2'>
                   <label htmlFor="">Date of Birth</label>
                   <input type="date" placeholder='Enter DoB' className='form-control'
                   onChange={e=> setdate_of_birth(e.target.value)} ></input>
                </div>
                <div className='mb-2'>
                   <label htmlFor="">Department</label>
                   <input type="text" placeholder='Enter Department' className='form-control'
                   onChange={e=> setdepartment(e.target.value)} ></input>
                </div>
                <button className='btn btn-success'>Update</button>
            </form>
        </div>
    </div>
  )
}

export default UpdateStudent

i just want to update the data on my Student page which in return will update the value in my database.

i have tried changing, checking :id to :ID trying to send id to the console and seeing if it is displayed there correctly or trying to press update button while on network page to see if the ip is pulled and vice versa maybe i did something wrong? i don’t know.