What is the best way to send data into functions?

I'm trying to avoid using global variables and I'm facing some difficulties in figuring out how to pass the database variable into the addTrain function. Do I necessarily need to use global variables for the database?

$(document).ready(function(){

function mainProgram(){
    var config = {};        // Initialize Firebase
    var db;           // Variable to reference the database

    config = {
    apiKey: "#",
    authDomain: "#",
    databaseURL: "#",
    projectId: "#",
    storageBucket: "",
    messagingSenderId: "#"
  };
    firebase.initializeApp(config);

    db = firebase.database();

    $("#train-submit").click(addTrain);
}

//calls the main function
mainProgram()


// add train function
function addTrain(event){
    event.preventDefault();
    console.log("clicked");

    var name;           // Train name
    var destination;    // Train destination
    var arrivalTime;    // inputted arrival time
    var frequency;      // How often train arrives
    var timeStamp;      // FB timestamp

    var formatTime;     // Format for moment.js
    var convertedTime;  // converted time
    var displayTime;    // converted time for displaying in DOM
    var timeLeft;       // time left until next train


    name = $("#train-name").val().trim();
    destination = $("#train-destination").val().trim();
    arrivalTime = $("#train-time").val().trim();
    frequency = $("#train-frequency").val().trim();
    formatTime = "HH mm";
    convertedTime = moment(arrivalTime, formatTime);
    displayTime = moment(convertedTime).format("HH:mm")
    timeLeft = moment(convertedTime).fromNow();


    db.ref("/train-data").set({
        name: name,
        destination: destination,
        frequency: frequency,
        arrivalTime: arrivalTime,
        timeStamp: firebase.database.ServerValue.TIMESTAMP
    })

    console.log("input captured: " + name);
    console.log("input captured: " + destination);
    console.log("input captured: " + frequency);
    console.log("input captured: " + arrivalTime);
    console.log("converted convertedTime: " + convertedTime);
    console.log("converted displayTime: " + displayTime);
    console.log("converted timeLeft: " + timeLeft);

 }  
});

Should I include the database parameter in the mainProgram() call? Like mainProgram(database)? Or something similar? I feel like I've structured this incorrectly. I'm currently enrolled in a coding bootcamp and I'm really struggling with grasping the concept of passing in variables and scope. Any assistance would be greatly appreciated.

Answer №1

To make use of this technique:

$("#submit-button").click({param1: "example", param2: "another example"}, processForm);

In the function definition, you can retrieve the values like so:

function processForm(event){
    event.data.param1;
    event.data.param2;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The slideshow feature on W3 Schools does not start automatically when the page loads

After following the W3Schools tutorial to create a slideshow, I found that the animations are working correctly. However, only three dots appear on the screen and I have to manually click on one of them to view the pictures. var slideIndex = 0; sh ...

How to pass the Node environment to layout.jade in Express without explicitly specifying the route

Passing parameters to Jade files seems like a piece of cake: app.use('/myroute', function (req, res) { res.render('myview', {somevar: 'Testing!'}); }); But, I have my layout.jade file that is automatically read and rendere ...

How can I effectively save data to a session using connect-redis?

I am looking to save the username of an account into session storage. I am currently using node.js with the expressjs framework and have attempted to utilize connect-redis for storing sessions, following a tutorial on expressjs. Can someone please guide ...

The tabbing feature in bxslider disrupts the alignment of slides, making it

After encountering accessibility issues, I upgraded the bxslider library to version 4.2.3 for better support. Check out this example of bxslider where you can easily tab through the controls: http://jsfiddle.net/qax7w8vt/2/embedded/result/ The problem a ...

Creating multiple React applications using shared configuration files: A step-by-step guide

I am in the process of developing a React app, and my goal is to create multiple React apps that share the same configurations - including modules and configuration files like tailwind.config.cjs. How can I modify my environment to achieve this? My plan i ...

Encountering an issue with retrieved items upon refreshing the webpage

My usual approach to fetching data from an external API involves the following steps: Using Fetch API: const [tshirts, setTshirts] = useState([]); const fetchData = () => { fetch('apiEndpoint') .then((response) => ...

The underscore convention for defining members in Typescript allows for clear and concise

Let's talk about a class called Email class Email { private _from: string; private _to: Array<string>; private _subject: string; } When an email object is created, it will look something like this: { _from:'', _to:'&apo ...

The function `canvas.toDataURL()` does not produce an image as output

When I expect the image to return mirrored, it instead shows up as a black image. <!DOCTYPE html> <html> <head> <style> body { margin: 0px; padding: 0px; } </style> </head> <bo ...

When using Selenium WebDriver in Java, we noticed that despite initially failing with JavascriptExecutor, the element click method with WebElement performed successfully

Within the code snippet below, it is evident that using the WebElement.click() method successfully triggers an element, while the JavascriptExecutor.executeScript method encounters issues (although it works in most cases). WebElement e = driver.findElemen ...

Javascript text validation is malfunctioning as the alert message fails to appear

Looking for a simple form validation script: <script language=”javascript”> function checkForm(register) { if (""==document.forms.register.FNAME.value){ alert("Please fill out this field!"); document.forms.register.FNAME.focus( ...

Transforming Javascript code using regular expressions into C#

Currently, I am facing a challenge while trying to translate some Javascript code into .NET. Despite my efforts, I have not been able to get it right. The task at hand involves converting paths like /test/:value1/:value2 in Express for NodeJS to a regular ...

Issue with parsing JSON data for heatmap in Mapbox

Here's the code I'm using: heat = L.heatLayer([], { maxZoom: 12 }).addTo(map); $.getJSON("js/example-single.geojson", function(data) { var geojsosn = L.geoJson(data, { onEachFeature: function (feature, layer) { console.log(f ...

Perform simple arithmetic operations between a number and a string using Angular within an HTML context

I'm stuck trying to find a straightforward solution to this problem. The array of objects I have contains two values: team.seed: number, team.placement: string In the team.placement, there are simple strings like 7 to indicate 7th place or something ...

Exploring various queries in Firestore

Does anyone know if there is a way to create a sentence similar to this one: return this.db.collection('places', ref => ref.where("CodPais", "<>", pais)).valueChanges(); I have tried using != and <> but neither seem to be valid. ...

Tips for dynamically updating an HTML value with Javascript

Summary of My Issue: This involves PHP, JS, Smarty, and HTML <form name="todaydeal" method="post"> <span id="fix_addonval"></span> <input type="radio" name="offer" id="offer_{$smarty.section.mem.index+1}" value="{$display_offe ...

Unlocking the Secrets of Laravel Blade Integration in a Script File

I am attempting to create a customized store locator application using the guidance provided in this useful tutorial on Google Maps and Laravel 5. While going through various queries related to integrating Google Maps with Laravel, I came across these info ...

What is the best way to retrieve the transpiled string from babel-core?

I've been attempting to utilize babel with npm and it seems like the necessary package is babel-core. My goal is to provide it with a string of ES6 code and receive a transpiled code string in return. It sounds simple enough, but I'm having troub ...

Switching styles in AngularJS without using ng-class

My goal is to allow users to switch the class from incomplete to complete when they click a button and the function(response) returns 1. I have attempted to use ng-class, but it is not effective because the HTML elements are generated with a PHP loop. This ...

The Material UI React radio buttons have the ability to modify the value of previous buttons

I'm facing an issue with my Material UI React Stepper Component that contains a group of radio buttons. The problem is that changing the radio button in one step affects the selected value in previous and future steps. I've experimented with diff ...

The HTML code as content

While working on an AJAX project, I ran into this issue: http://jsbin.com/iriquf/1 The data variable contains a simple HTML string. After making the AJAX call, I noticed that the returned string sometimes includes extra whitespaces. I attempted to locat ...