JavaScript

123K

Solutions

42K

Contributors

JavaScript is a dynamic, object-based language commonly used for client-side scripting in web browsers. Recently, server side JavaScript frameworks have also emerged. JavaScript runs on nearly every operating system and  in almost every mainstream web browser.

Share tech news, updates, or what's on your mind.

Sign up to Post

Hi Experts,
I am trying to implement a reservation calendar packages. I think I installed the libraries I need using npl  (although I did get some warnings as in the attached PDF "javascript calendar warnings") so maybe it

I created two files to see if I could get the calendar to work:
hello.html
booking-form.js

This does not work. I am very new to javascript (and honestly programming and computers in general) and i would really appreciate it if someone can look at these files and help me understand what I'm did wrong and how I can make this work. Thank you very much.

Alla
Javascript-calendar-warnings.pdf
hello.html
booking-form.js
0
Ensure you’re charging the right price for your IT
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

In my node app I have some configuration for local usage and some for the server usage (database). This information is stored in keys.json and keys_local.json.
Is it possible to load keys_local.json only on my local computer and keys.json running app on the server?
Currently I make this changes manual, but sometimes I miss it and problems occurred.

I was not able to find any information about identify the kind of current environment. I just found a module to identify the IP, but in case of dynamic AWS creation, the IP is dynamic.
0
In my node app I have to insert a new XMLnode for identify it later. I developed some code where I expected the right result.
It is really simple:

var xmlDoc = new DOMParser().parseFromString(dataRegelWerk);  //Incomming data
if(allok == false){
                var root = xmlDoc.documentElement;

                var varselem = xmlDoc.getElementsByTagName('vars')[0];
                var newEle = xmlDoc.createElement('TCafe');
                var att1 = xmlDoc.createAttribute("initvalue");
                att1.value = "1";
                var att2 = xmlDoc.createAttribute("type");
                att2.value = "int";
                newEle.setAttributeNode(att1);
                newEle.setAttributeNode(att2);

                root.insertBefore(newEle, varselem);
            }

var myFile = serializer.serializeToString(xmlDoc); //Put back to string to store in db

Open in new window


This is the original formatted XML

<xml xmlns:xi="http://www.w3.org/2001/XInclude">

   <vars>
....

Open in new window


I tried to insert before "vars" and the result is

<xml xmlns:xi="http://www.w3.org/2001/XInclude">

    <TCafe initvalue="1" type="int"/><vars>

Open in new window


But I expected

<xml xmlns:xi="http://www.w3.org/2001/XInclude">

    <TCafe initvalue="1" type="int"/>

       <vars>

Open in new window


Is there anything wrong with my code or do I expect a wrong thing? Maybe I have to close the new XMLNode? (I expected the last / will do it.
Any help will be great.
0
I want to add number of items per page to my Simple Pagnaition JS script..

the function is included in the script but i am at a loss on how to implement it..

this is the function

$(function() {
    $(selector).pagination('updateItemsOnPage', 20);
});

Open in new window


here is my implementation of the script

  <script Language="Javascript" type = "text/javascript">

$(document).ready(function(){
  $('#pagination').simplePagination({
    items_per_page: 25,
    cssStyle: "light-theme"
  });
});


        </script>

Open in new window


How can i make the items per page dynaimic  the site code is ASP Classic ty
0
I  have a node.js API and a next.js frontend application. The login is working for the most part. But if I open google dev tools and I change the value of the token cookie and try to access the secret page again, it still lets me. Shouldn't it kick me out because the token is no longer the same?

Here is the backend where I check login credentials and then create the token.

exports.login = async (req, res, next) => {
  // check if email exists
  const user = await User.findOne({ email: req.body.email });
  if (!user)
    return res.status(400).send({ errors: ["Invalid login credentials"] });

  //email exists, check password
  const validPass = await bcrypt.compare(req.body.password, user.password);
  if (!validPass)
    return res.status(400).send({ errors: ["Invalid login credentials"] });

  // create jwt token
  const token = jwt.sign(
    { email: user.email, _id: user._id },
    process.env.TOKEN_SECRET,
    { expiresIn: "1h" }
  );
  // add token to header
  res.header("auth-token", token).send(token);
};

Open in new window

Then here is the frontend code for the login where I set the cookie with the token value from the server:

  handleSubmit = async event => {
    const { email, password } = this.state;
    event.preventDefault();
    const user = {
      email,
      password
    };
    // client side validation
    const errors = this.validate(user);
    this.setState({ errors: errors || {} });
    if (errors) return;

    try {
      const response = await login(user);
      const token = response.data;
      cookies.set("token", token);
    } catch (ex) {
      if (ex.response) {
        const errors = ex.response.data.errors;
        this.setState({ errors });
      }
    }
  };

Open in new window

Then I created a route which you can only access if logged in:

Secret.getInitialProps = async ctx => {
  await handleAuthSSR(ctx);
  const response = await axios.get("http://localhost:8000/api/user");

  return {
    users: response.data
  };
};

Open in new window

Here is the auth function (I am using next-cookies)

import nextCookie from "next-cookies";

export const handleAuthSSR = ctx => {
  const { token } = nextCookie(ctx);

  if (ctx.req && !token) {
    ctx.res.writeHead(302, { Location: "/login" });
    ctx.res.end();
    return;
  }
  if (!token) {
    console.log("no token found");
    Router.push("/");
  }

  return token;
};

Open in new window

0
Can we create our own alert window to override the existing "alert(" xxx") in JavaScript ?
0
Hi Experts,

how do I create a link in a web page (designed in Caspio), and the link contents should come from a field/parameter.

Tried the following, didn't work.

<a href="[@field:Datapage]">Download </a>

Open in new window


Thanks
0
Hello Experts,

Here is the Ask:  How do I get the below code to run without utilizing the ‘sp_configure’ stored procedure in Microsoft SQL server 2016?  I have the ability to create new stored procedures, but I cannot use the stored procedures that natively exist in SQL Server.

Additional Context/Background:

I have about 200,000 addresses in a Microsoft SQL server that I need to geocode.  I am operating in a highly restricted environment that does not allow the use of unapproved applications.  The approval process for a new application that I might develop in Visual Studio to geocode the addresses utilizing Google’s Locations API would take about a year for approval.  


I do however have access to SQL Server Management Studio and the database itself.  Here is the kicker, in this highly restricted environment, I have the ability to create a stored procedure, but nearly all of the native stored procedures in SQL have been disabled due to security concerns.

Using the innerwebs, I created the below SQL code to geocodes my addresses.  It works like a champ in my test environment utilizing a Cursor in conjunction with the ‘Ole Automation Procedures’ stored procedure ‘sp_configure ' .  The problem I have is that in my production environment, the stored procedure ‘sp_configure’ is disabled.

I realize that I will probably be cursed up and down for using Cursors and ‘sp_configure’.  It wasn’t my first choice, I am just trying to play the hand I have been dealt in the…
0
Here's my code in full:

require("dotenv").config();
const { validationResult } = require("express-validator/check");
const mongoose = require("mongoose");
const Profile = require("../models/profile");
const ClientId = process.env.CLIENTID;
const Secret = process.env.SECRET;
const Callback = process.env.CALLBACK;

//this is the empID you're getting from AHA
const empID = 7747;

//get today's date
let date_ob = new Date();

// current date
// adjust 0 before single digit date
let date = ("0" + date_ob.getDate()).slice(-2);

// current month
let month = ("0" + (date_ob.getMonth() + 1)).slice(-2);

// current year
let year = date_ob.getFullYear();

// prints date in YYYY-MM-DD format
let today = year + "-" + month + "-" + date;

const FitbitApiClient = require("fitbit-node");
const client = new FitbitApiClient({
  clientId: ClientId, //client_id
  clientSecret: Secret, //client secret
  apiVersion: "1.2" // 1.2 is the default
});

exports.getCallback = (req, res, next) => {
  const yesterday_raw = new Date(new Date().setDate(new Date().getDate() - 1));
  const yesterday = yesterday_raw.toISOString().slice(0, 10);

  client.getAccessToken(req.query.code, Callback).then(result => {
    var requests = [
      client.get("/profile.json", result.access_token), //0
      client.get("/activities/date/today.json", result.access_token), //1
      //client.get("/sleep/date/" + yesterday + ".json", result.access_token), //2
      client.get("/sleep/date/today.json", 

Open in new window

0
Hi

I'm hoping for confirmation about this local server installation strategy for my Javascript game dev server being a good choice.

I have my newest MacBook, that is basically empty, ready to install this MAMP local server on from here

It says one-click installation. Any gotchas?
It has lots of sections for wordpress, elsewhere, but will this be good for serving files and data needed by my game?

Must I do a default install of Atom IDE? ( on the same machine?)

Thanks
0
Learn SQL Server Core 2016
LVL 19
Learn SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

Here's what I've got:

client.get("/sleep/date/2019-11-05.json", result.access_token), //2

...and this generates an array. One of the values in that array is "REM" and I retrieve it like this:

const rem_sleep = JSON.stringify(data[2][0].summary.stages.rem); //minutes in deep REM sleep

Here's my dilemma: The user may not have worn their Fitbit to bed last night and when that happens, "rem_sleep" will be returned as "undefined."

I don't want that. Especially since I need a valid digit to enter into the database this project is going to be hooked up to.

So, here's what I tried:

const deep_sleep = JSON.stringify(data[2][0].summary.stages.rem); //minutes in deep REM sleep
        if (deep_sleep > 0) {
          const rem_sleep = deep_sleep;
        } else {
          const rem_sleep = 0;
        }
        res.send(rem_sleep);

As you might suspect, "rem_sleep" comes back as undefined .

I'm learing that with JavaScript, constants stay credible within the scope of their particular "block."

That said, how can I pull this off?

I need whatever it is that I can do in Javascript that equates to an IF clause that provides me a genuine value and not something that comes back "undefined."

What do you think?
0
I have an Ienumerable object that i am storing in AngularJS $scope(say Product), i need to loop through the $scope.Product object & remove some data if it meets a particular criteria. How do i do that( let's say if $scope.Product.ID = 5 then remove it from Ienumerable object)
0
I am getting script errors when using a Webbrowser embedded in a .NET Windows forms VS19 project, using VB.
Using a simple form with just the Webbrowser control and setting the URL to a login page that works fine in Edge or an external IE window, the project immediately returns JS errors and fails. I can supress the error display, but the URL still, of course, fails.

An error has occurred in the script on this page
Line: 1
Char: 1
Error: Syntax error
Code: 0

I've tried this with all versions of VS from 10  up to 19, using a WIndows10 machine with Edge and IE installed.

Can anyone help, please?
Thanks
0
My dear experts, what is the best Javascript frameworks for Mobile App Development that can communicate with the server? I have my own server, and I used .asp as my server-side communicator between clients. I need a guide from yours so that I would not be loosing my time in studying this new project.  Thank you!
0
Hi how to know any change happen to the table form the sqlite database
So any new row added the database i got a notification, for now i can make a push notification via javascript but i don't know how to know if a new row added

This is my code a simple table with small javascript to refresh the table with new data using load

<div class="tbl-header">
<table cellpadding="0" cellspacing="0" border="0">
<thead>
        <tr>
          <th>IP</th>
          <th>Email</th>
          <th>Phone</th>
          <th>Seller</th>
          <th>Item</th>
		  <th>Code</th>
        </tr>
</thead>
</table>
</div>
<div class="tbl-content">
<table id="infos" cellpadding="0" cellspacing="0" border="0">

</table>
</div>
<script>
window.setInterval('refresh()', 1000); 
function refresh(){
$('#infos').load ('streets.php', 'update=true');
}
</script>

Open in new window


It get the data from streets.php every 1 second
and this is the PHP code of streets.php to get the the data from sql database ( data.sqlite ) and show it as a table

<tbody>
<?php
$data = new SQLite3('data.sqlite');
$result = $data->query("SELECT * FROM userdb"); //  WHERE ip ='$ip'

while ($row = $result->fetchArray()) {
    echo "<tr>
            <td>{$row['IP']}</td>
            <td>{$row['Email']}</td>
            <td>{$row['Phone']}</td>
            <td>{$row['Seller']}</td>
            <td>{$row['Item']}</td>
			<td>{$row['Code']}</td>
          </tr>";
}

?>
</tbody>

Open in new window


I need to know if it is possible to do know any update happen and call a javascript function if there is a new row added
0
I have seen example in this URL:

jQuery Sortable - drag and drop multiple items
https://stackoverflow.com/questions/23077146/jquery-sortable-drag-and-drop-multiple-items

Impressive, but I'm not satisfied with its effect.

As far as what you're familiar with, is there any better libraries or sample codes can do the similar effects?

Thanks
0
error clicking a link in java application
Nov 04, 2019 8:28:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version name:   Apache Tomcat/9.0.20
Nov 04, 2019 8:28:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built:          May 3 2019 22:26:00 UTC
Nov 04, 2019 8:28:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version number: 9.0.20.0
Nov 04, 2019 8:28:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name:               Windows 10
Nov 04, 2019 8:28:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version:            10.0
Nov 04, 2019 8:28:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture:          amd64
Nov 04, 2019 8:28:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home:             C:\Java\jdk1.8.0_111\jre
Nov 04, 2019 8:28:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version:           1.8.0_111-b14
Nov 04, 2019 8:28:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor:            Oracle Corporation
Nov 04, 2019 8:28:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE:         C:\Users\Desmond\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
Nov 04, 2019 8:28:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME:         C:\Program Files\Apache Software Foundation\Tomcat 9.0

Open in new window

0
I have a question about reactLeaflet.
in one file laControl.js, I had set a variable value in userEffect() block, I need pass this value to another component file showTitle.js. both two files are in the same folder.

Below are code:
 
laControl.js :
const { useEffect, useState, Fragment, useRef } = window.React;
const { useLeaflet } = window.ReactLeaflet;

export function tLayer({ link = ""}) {
  const { laContainer } = useLeaflet();

  const [la, setLa] = useState(null);
  useEffect(() => {
    const ti = la || Leaflet.tiLa(link);
    setLa(ti);
    laContainer.addLa(ti);
    const n = ti._url.includes("CovLOT"); // I got the value here, then I need pass this value to showTitle.js
    return () => laContainer.removeLa(ti);
  }, [link]);

  return null;
}

Open in new window


showTitle.js:

const { useState } = window.React;
const { useLeaflet } = window.ReactLeaflet;

export function LegeL() {
 
  return html`
    <div className="leaflet-bottom">
      <div className="leaflet-bar">
        Hello!   // I need based on the value of n in laControl.js to show or hide "Hello!".   
      </div>
    </div>
  `;
}

Open in new window



How can I pass the value of n from laControl.js to showTitle.js?

Any inputs will be appreciated.
0
Hi Experts, I want to develop Phone Apps using Html, Javascript, Css and .asp. Can you guide me where or how to start it?
0
OWASP: Threats Fundamentals
LVL 19
OWASP: Threats Fundamentals

Learn the top ten threats that are present in modern web-application development and how to protect your business from them.

I have ASP.NET master page with Menu Control and I need to make it 508 compliance which requires onFocus and onBlur events for keyboard equivalent to OnMouseOver and OnMouseOut event. ASP Menu control doesn't provide these events out of box.

I tried Attributes.Add on pageload but it doesn't work for MenuItems.

<asp:Menu ID="Menu1" runat="server">
  <Items>
     <asp:MenuItem Text="Files" Value="File" NavigateUrl="~/HomePage.aspx">
           <asp:MenuItem Text="Items" NavigateUrl="/ItemSelect.aspx" ></asp:MenuItem>
     </asp:MenuItem>
  </Items>
</asp:Menu>

How can I add onFocus and onBlur events for ASP Menu control?
0
I am using sequelize in node.js. At the moment I can search multiple tables and produce the the results as data.  I have done so using the following code:

router.get("/alldata", (req, res) => 

Promise.all([chemical_bays.findAll(), electricals.findAll(), fire_services.findAll(), instruments.findAll(), mechanicals.findAll(), microwaves.findAll(), tools.findAll(), water_cays.findAll(), buildings.findAll(), substations.findAll(), fences_gates_cctv.findAll(), steam_plant_other.findAll(), information_technology.findAll(), ])
.then((data) => {  res.render('gigs', {gigs: [...data[0], ...data[1], ...data[2], ...data[3], ...data[4], ...data[5], ...data[6], ...data[7], ...data[8], ...data[9], ...data[10], ...data[11], ...data[12]] }) }).catch(err => console.log(err)));

Open in new window


However, I wish now to count the results and have them displayed, however, if I use the aggregate attribute, "count", I am receiving an error. Here is the code I am trying to use:

router.get("/alldata", (req, res) => Promise.all([chemical_bays.findAll({attributes: ['id', [sequelize.fn('count', sequelize.col('id')), 'count']],
group : ['chemical_bays.id'],
raw: true,
order: sequelize.literal('count DESC')}), electricals.findAll({attributes: ['id', [sequelize.fn('count', sequelize.col('id')), 'count']],
group : ['electricals.id'],
raw: true,
order: sequelize.literal('count DESC')}), fire_services.findAll({attributes: ['id', [sequelize.fn('count', sequelize.col('id')), 'count']],
group : 

Open in new window

0
Hi Experts,

I would like to apply the following to my logic page (designed in Caspio).

Check if PWD_Date is older than 90 days, then it should redirect user to the change PWD screen.

This is the article showing how to accomplish this.

I have tried the following, but so far its not working...

<script>


var date = new Date('[@authfield:PWD_Date]');
date.setDate(date.getDate() + 90);
var dateTodate = new Date();

if (date < dateTodate) {
    alert('[@authfield:PWD_Date]'.toString());
    
alert('Please change your Password');
window.location.href = 'http://localhost/staff/profile-change-password.php';
};


	if ('[@authfield:Role_ID]' == '1234') {
		window.location.href = './admin';
	} else {
		window.location.href = './staff';
	}


</script>

Open in new window


Thanks
1
How can I jump, set the focus, on the next element with a specific class?  There will only be 2 elements with the given class and I know I can use getElementsByClassName to get a list, but how to I select the one I'm not on?

In this specific case, I'm not wanting to use jQuery, just plain javascript.

Thank you.
0
I have a rest query and I am trying to get a field from the list to be the "Title" and another field to be the URL of the Title. My code is not working.

tableContent += '<span>''<a href='"+objItems[i].bookURL+'">"+objItems[i].Title+"</a>'</span>;

Open in new window

0
I have a REST Query to my SharePoint list.  I am displaying the results in a custom table.  The problem is the data repeats.  It seems like 5 times, but maybe it keeps repeating.  Here is my code.

$(function(){
    $("#btnClick").click(function(){
        var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('ListName')/items?$select=Title%2CName%2CURL&$top=100";
           $.ajax({
              url: requestUri,
              type: "GET",
              headers: {
                  "accept":"application/json; odata=verbose"
              },
              success: onSuccess,
              error: onError
});

Open in new window

0

JavaScript

123K

Solutions

42K

Contributors

JavaScript is a dynamic, object-based language commonly used for client-side scripting in web browsers. Recently, server side JavaScript frameworks have also emerged. JavaScript runs on nearly every operating system and  in almost every mainstream web browser.