Bootstrap Modal On Php Submit using Ajax

Here I’m working on a simple withrawal page where users can select the amount they want to withdraw and submit afterwhich a bootstrap modal pops up confirming to the user that the request has been sent whilst updating the section in the db with the amount selected.

So far im facing no issues when user selects the amount and click on submit, the modal pops up but unfortunately the database is not updated, I can’t fathom where i’m getting it wrong.

Here is the Php


<?php

// Define variables and initialize with empty values
$withraw = "";
$withraw_err = "";
 
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
 
      // Validate Withrawal
    if(empty(trim($_POST["withraw"]))){
        $withraw_err = "Please Choose a Amount.";     
    } else{   
            $withraw = trim($_POST["withraw"]);
            }

    // Check input errors before inserting in database
    if(empty($withraw_err)){
        
        // Prepare an insert statement
        $sql = "UPDATE users SET withraw = (?) WHERE id = ".$id;

        if($stmt = mysqli_prepare($link, $sql)){
            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt, "s", $param_withraw);
            
            // Set parameters
           
            $param_withraw  = $withraw;
           
            
            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
               echo "";
            } else{
                echo "Something went wrong. Please try again later.";
            }

            // Close statement
            mysqli_stmt_close($stmt);
        }
    }
    
    // Close connection
    mysqli_close($link);
}
?>

Here is the code for the form im using.

<form  onsubmit="openModal()" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" id="myForm" >
           

              <div class="form-group <?php echo (!empty($withraw_err)) ? 'has-error' : ''; ?>">
               

                <div  style='width:50%;' class='selectt'><select name="withraw" class="form-control" value="<?php echo $withraw; ?>"><option >Choose Amount</option>
        <option value="500">500</option>
        <option value="1000">1,000</option>
        <option value="1500">1,500</option>
        <option value="2000">2,000</option>
        <option value="2500">2,500</option>
                <option value="3000">3,000</option>
        <option value="3500">3,500</option>

</select>
        
        </div>
                <span class="help-block"><?php echo $withraw_err; ?></span>
            </div>    
        
        
    


          <div class="form-group"  >
               <button type="submit"  class="btn btn-info btn-lg"   value="Submit">
                    Withraw  <i class="fa fa-check-circle"></i> </button> 
                <button type="reset" class="btn btn-default"  value="Reset"><i class="fas fa-redo"></i> Reset </button>
            </div>

        </form>

And I’ve added some javascript to load the bootstrap modal after the form is Submitted

<script>$('#myForm').on('submit', function(e){
     e.preventDefault();
     $('#myModal').modal('show');
                  });</script>

Here is where I’m completely lost as, when I remove the e.preventDefault() the form Updates the database row called withraw but the bootstrap does not load at all and I’ve been trying to set so that the bootstrap loads and the database row is updated as well I do not have more knowledge on how to tackle this situation as I read similar questions and some suggestions are to use Ajax but I have limited knowledge on how to do that.

I didn’t post the bootstrap because i don’t see it necessarily its a normal Bootstrap modal setup

Using delay in for loop, then i becomes undefined [duplicate]

Title says all. My code basically looks like this:

for (i = 0; i < tickers.length; i++){
   console.log(i)//returns number from 1 to 10
   delay(15000)
   console.log(i)//returns undefined

Do you have any idea why this happens? I need a for loop that runs code every 15 seconds without making i undefined. By the way the delay function uses the npm delay function

How to convert european date format to Date Object in react native and/or javascript?

Given a date such as November 23, 2021 in this European format: 23/11/2021. I try converting it to a date object like this:

const dateString =  '23/11/2021'
const dateObj = new Date(dateString)

However, this is giving me an error saying this is an invalid date. I don’t want to just convert it to the US date format, since I am trying to see if I can sort the dates given the European format. Anyone know how I can convert this to a date object given the european date format?

Set element max length

searching here for an answer I found the following question:

Answer for similar issue

I’m trying to replicate this answer but in a different scenario and seems that it doesn’t work when I call a function instead of jQuery key events on document.ready().

This is what I have:

function maxLenght(event) {
  var input = $('p[data-id="111"]').get(0);

  if (parseInt(input.textContent.length) >= 10) {
    event.preventDefault();
  } else {
    $(input).outerHeight(32).outerHeight(input.scrollHeight + 4);
  }
        
  $('span').text('Total chars:' + (input).textContent.length);
}
p {
    height: 100px;
    width: 300px;
    border: 1px solid grey;
    outline: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p contenteditable="true" data-id="111" onkeyup="maxLenght(event)"></p>
<span></span>

Also I should be able to paste text using right click or ctrl + v, navigate the text using arrow keys, backspace, delete key, etc.

So my question is if is possible to do it keeping this functionallity (calling a function) and how can I do it and what’s wrong from what I have right now?

How to store a favourite pet for a logged in user?

Using React and Express, how can I store a favourite pet for a logged in user? Currently pulling the pets from an API and then using PostgreSQL for the DB

const favPetDetails = {
    id,
    name,
    media,
    breeds,
    location,
    distance,
    sort,
    url,
    tags,
    type,
    gender,
    contact,
    environment,
    attributes,
  };
  const addFavouritePet = (Pet) => {
    const newFavList = [...favourites, Pet];
    setFavourites(newFavList);
  };


 <button onClick={() => addFavouritePet(favPetDetails)} </button>

use mongodb data with mongoose on google map API on node js

Hello and Welcome to my question!

I want to make a fairly simple website

I have some data in my database and I want to use them on a google maps API
Basically, I want for each place that I have stored, in my db, to have a marker at it’s coordinates

My mongoose schema is this:

const mongoose = require('mongoose')

const placeSchema = new mongoose.Schema({
    _id: String ,
    name: String,
    address: String,
    types:[ String ],
    coordinates:{ lat: Number, lng: Number },
    rating: Number,
    rating_n:Number,
    current_popularity: Number ,
    populartimes:[
        {
            name: String ,
            data: [ Number ]
        }
    ],
    times_spent: [ Number ]
})

module.exports = mongoose.model('place', placeSchema)

I have read the google API docs and I am trying to do it as they say but I cannot get my data in my js file that my function initMap() is in.

The path is like this:
/login/user

And the user.ejs file is:

<script type="text/javascript" src="js/user.js"></script>

<div class="container">
<div class="form-uheader">
    <h1>Welcome <%if (typeof user != 'undefined'){%> 
        <%= user.username %> 
        !
    <% } %> </h1>
        <h2>Let's evaluate your choices.</h2>
</div>
</div>
<div class="container">
    <div class="dropdown">
        <button onclick="openDropdown('map')" class="drop_btn"><img src="images/map.png" alt="#"><h1>What is next to you?</h1></button>
        <button onclick="openDropdown('search')" class="drop_btn"><img src="images/search.png" alt="#"><h1>Points of Interest</h1></button>
        <button onclick="openDropdown('verify')" class="drop_btn"><img src="images/verify.png" alt="#"><h1>Register a Visit</h1></button>
        <button onclick="openDropdown('nervous')" class="drop_btn"><img src="images/nervous.png" alt="#"><h1>Possible contact with a covid case</h1></button>
        <button onclick="openDropdown('patient')" class="drop_btn"><img src="images/patient.png" alt="#"><h1>Do you have Covid?</h1></button>
        <button onclick="openDropdown('edit')" class="drop_btn"><img src="images/edit.png" alt="#"><h1>Edit your profile</h1></button>
    </div>
    <div id = "data">
        <% if(typeof place != 'undefined'){ %> 
            <%var places = place %>
        <% } %> 
    </div>
</div>   

<div class="container">        
    <div id="menu" class="dropdown-menu">
        <div class="dropdown-item" id = "item-map">
            <div id="map"></div>
            <% //script for maps API %> 
            <script
              src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAPmkodwFVGpcTcpFyUbeDxaAwYYlUJjnM&callback=initMap&v=weekly"
              async
            ></script>
            <script src="js/map.js"></script>
            <% //END script for maps API %>
            <span class="closebtn" onclick="this.parentElement.parentElement.style.display='none';">&times;</span>
        </div>
        <div class="dropdown-item" id = "item-search">
            <div id = 'search'>
                search
            </div>
            <span class="closebtn" onclick="this.parentElement.parentElement.style.display='none';">&times;</span>
        </div>
        <div class="dropdown-item" id = "item-verify">
            <div id = 'verify'>
                verify
            </div>
            <span class="closebtn" onclick="this.parentElement.parentElement.style.display='none';">&times;</span>
        </div>
        <div class="dropdown-item" id = "item-nervous">
            <div id = 'nervous'>
                nervous
            </div>
            <span class="closebtn" onclick="this.parentElement.parentElement.style.display='none';">&times;</span>
        </div>
        <div class="dropdown-item" id = "item-patient">
            <div id = 'patient'>
                patient
            </div>
            <span class="closebtn" onclick="this.parentElement.parentElement.style.display='none';">&times;</span>
        </div>
        <div class="dropdown-item" id = "item-edit">
            <div id = 'edit'>
                edit
            </div>
            <span class="closebtn" onclick="this.parentElement.parentElement.style.display='none';">&times;</span>
        </div>
    </div>
</div>

Basically, there are 6 buttons and when 1 of them is pressed a different dropdown menu appears.

I have tried to pass my data to user.ejs, but I could not use my variable between tags
I cannot connect to mongo schema in static js file (As it was expexted)

Lastly I will present you my login route:

const express = require('express')
const router = express.Router()
const User = require('../models/user')
const Place = require('../models/place')

// Main Route
router.get('/', (req, res )=> {
    const fromReg = req.query.valid

    console.log(fromReg)
    res.render('login',{
        'page':'login',
        fromReg
    })
})

router.get('/user', (req, res) => {
    res.render('login/user',{
        'page' : 'user'
    })
})

router.get('/admin', (req, res) => {
    res.render('login/admin',{
        'page' : 'admin'
    })
})

//Create About Route
router.post('/', async (req, res) => {

    User.findOne({ email : req.body.email }).then( async (user) => {
        if(user){
            if (user.password === req.body.password) {
                if (user.admin){
                    //login admin
                    res.render('login/admin',{
                        'page' : 'admin',
                        user
                    })
                }else{          
                    const place = await Place.find({})    
                    res.render('login/user',{
                        'page' : 'user',
                        user,
                        place
                    })
                    
                }
            }else{
                const alert = [];
                alert.push({ msg: 'Email or Password is not correct'})
                res.render('login', {
                    'page' : 'login',
                    fromReg : false,
                    alert
                })
            }
        }else{
            const alert = [];
            alert.push({ msg: 'Email or Password is not correct'})
            res.render('login', {
                'page' : 'login',
                fromReg : false,
                alert
            })
        }
    })
})

module.exports = router 

And I have to tell you that I have 1 javascript file called user.js, that does the animations on the page
and 1 more that is called map.js that basically is copied and pasted from google API documentation

Just to sum up, I would like to know how (but firstly, if) I can use my data in a client-side js file (at least I think this is client-side), or else how can I achieve the end result that I want

Plus this is how my user page looks like:
enter image description here

Microsoft Word API – how to I from Word.RequestContext.document to Office.Document

I am starting the “Build your first Word task pane add-in” tutorial.

Basically I want to make a Button on the Panel that will send this document as a PDF to my web service.

There is a function in the API called Office.Document.getFileAsync which seem to be an excellent way to save data to a PDF, which I can then send to my web service.

How do I access that part of the API. In the tutorial it seem that we should use the context object, but context.document.getFileAsync does not appear to exist. I think I need to get to the Office.Document object and I think context.document is Word.RequestContext.document.

export async function run() {
  return Word.run(async (context) => {
    /**
     * Insert your Word code here
     */

    {{Office.Document then use getFileAsync  }}

    await context.sync();
  });
}

Displaying images from array of objects fails when mapping

I’m learning ReactJS and I’m trying to display a list of socials from an array of objects just like so :

const baseUrl = "./";
export const SocialData = [
    {
        platform: "Linkedin",
        link: "https://www.linkedin.com/in//",
        icon: baseUrl + "linkedin.png",
    },
    {
        platform: "Github",
        link: "https://github.com/",
        icon: baseUrl + "github.png",
    },
];

Then in my component I would display it like this :

import { SocialData } from "../../data/social";
import "./socials.css";

function Socials() {
  const data = SocialData;
  return <div className="social-contact"> 
{/*     <img src={require('./linkedin.png')}/>
 */}  {
      data.map((item) => {
          return (
          <a href={item.link} key={item.platform}>
            <div className="social-icon-div">
              <img src={ require(item.icon) } className="social-icon" />
            </div>
          </a>
          )
      })}
    </div>;
}

The commented image works just fine, yet when I’m trying to do the same in my map it says and throw this error:

Uncaught Error: Cannot find module ‘./linkedin.png’
at webpackEmptyContext (socials|sync:2:1)
at Socials.js:14:1
at Array.map ()
at Socials (Socials.js:7:1)
at renderWithHooks (react-dom.development.js:14985:1)
at mountIndeterminateComponent (react-dom.development.js:17811:1)
at beginWork (react-dom.development.js:19049:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
at invokeGuardedCallback (react-dom.development.js:4056:1)

I’ve tried to put the require in the data directly, it does the same.
I also tried

<img src={require( “” + props.src )} alt={props.imageAlt} />

As explained here but nothing did the job.
Thanks for your help!

How to expose an Environment Variable to the front end in Next.js?

The Problem

I am trying to pass an environment variable to the front end to display a map from MapBox.

My Attempts

  1. I have place the API Key into the root of my directory:
//.env.local
MAPBOX_KEY="abc123"
  1. In the front-end, client side, I am trying to load that ENV to render a map:
// components/MapBox.js
export default function MapBox(){
  const MAPBOX_TOKEN = process.env.MAPBOX_KEY

  return (
    <MapGL mapboxApiAccessToken={MAPBOX_TOKEN} />
  )
}

The above code does not seem to recgonize the API KEY.

  1. When I console.log(process.env.MAPBOX_KEY) in this component, I can see the API Key in the terminal while i’m running yarn dev

Is there a way to load this env to the front end?

Note: I am using the react-map-gl package built on top of MapBox

Not a function TypeError when trying to split a user input inside a function

I created two functions and a global object data. I am trying to split what a person inputs inside a text area into individual strings and push them in the global object. The Error I have says userInputParam.split is not a function.

let data = {
  userInput: [],
  splittedInput: [],
  slicedInput: [],
};


function updateUserInput(data) {
  if (data.userInput.length == 0) {
    //   console.log("You can do this Panda!")
    data.userInput.push(input.value);
    //input.value is what a user inputs in a textarea. 
    splitUserInput(data.userInput)
  }
}

function splitUserInput (userInputParam){
    let splittedInput = userInputParam.split(/([*/+-])/)
    //console.log(splittedInput)
}

Problems displaying new div when onMouseOver event fires

I’ve made a CSS grid displaying a <p>{name}</p> element on each grid item. When an onMouseOver hover events I want to display a new div (contained within the react fragment), but in the same position.
Instead of using CSS, I’ve used JavaScript to code the logic for this – when a user hovers on the grid item, it flips a boolean (saved as state variable isMouseHovering) from false to true.
I have a conditional statement that displays the ‘new’ div, when this state value is truthy.

The problem is that this logic applies for grid item container element, and not for the elements inside the grid container. So when I over over grid, it does what it’s supposed to do and displays the new div. However when I hover over the p-tag within the grid item container element, it flickers between states.

How do I structure this so that the div changes on hover, no matter where on the grid item the user hovers the mouse?

Project.js

import { useState } from 'react'

const Project = ({name,url,techStack,image,blurb}) => {

  const [isMouseHovering, setMouseHovering] = useState(false);

  const handleOnMouseOver = () => setMouseHovering((isMouseHovering) => !isMouseHovering);  
  const handleMouseOut = () =>  setMouseHovering(false);
  
  return(
    <div className = 'grid-item' onMouseOver={handleOnMouseOver} onMouseOut = {handleMouseOut}>
      {
        isMouseHovering ? (
        // element I want to display when mouse hovering, in same position as <p>{name}</p> element
        <>
          <a href='https://xxxxxxxxxxxxxxxx'>
            <p>website</p>
          </a>
        </>
        )
        : 
        <p>{name}</p>
      }
    </div>
  )
}


export default Project

Mocha and Import Syntax: Cannot find module

Maintainer of multiple npm packages here. Been using mocha with the require syntax and wanting to migrate to the import syntax.

The error I am getting is

Cannot find module '<project>/src/index' imported from <project>/test/index.spec.js

Steps to Reproduce

With the following three files

  • src/index.js
export const sum = (a, b) => a + b;
  • test/index.spec.js
import { sum } from '../src/index';

const expect = require('chai').expect;

describe('Testing Index', () => {
    it('Testing sum', () => {
        expect(sum(7, 13)).to.equal(20);
    });
});
  • package.json
{
  "name": "mocha-debug",
  "type": "module",
  "main": "index.js",
  "scripts": {
    "test": "mocha "./test/**/*.spec.js""
  },
  "license": "ISC",
  "devDependencies": {
    "chai": "4.3.4",
    "mocha": "9.1.4"
  }
}

and using node v14.18.2, run yarn install and

yarn test

> `Cannot find module '<project>/src/index' imported from <project>/test/index.spec.js`

Notes

I’ve found a related issue that recommends using babel with --require @babel/register, but wasn’t able to get over the error.

I’ve set up a test repo to make it easy to reproduce the issue

https://github.com/simlu/mocha-debug

Question

What am I doing wrong here? How do I get the tests to run successfully?

Is creating element and set innerHTML more efficient or add HTML directly?

Please forgive confusing question above…

I have a dashboard that will fetch json data with ajax for every couple seconds. The current solution is it will clear the dashboard, and get the json data and combine them with html, so is kind of like this:

$.ajax({
    ....
}).done((res) => {
    $mainBody.html('');
    for (let i = 0; i < res.length; i++){
        let ele = '<div class="...">  with adding the json data  </div>';
        $mainBody.append(ele);
    }
})

Each ele will contain around 55 lines of html code, and most of time will loop for more than 20 times to finish adding all elements.

And now I want to take a more object-oritented approach to this dashboard and considering to use document.createElement() for all elements, and then to set their innerHtml directly after every fetch. But I’m not so sure on efficiency wise and speed, which solution should I use.