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

A solution for accessing computed properties within a v-for loop

Currently, I am facing a challenge with the code provided below. It seems that computed properties do not support parameters. Do you happen to have any suggestions on how to overcome this issue? I am considering using watchers on functions but I am also ...

Triggering an event upon completion of ng-repeat's execution

I am facing a challenge in updating the style of a specific element after ng-repeat has finished changing the DOM. The directive I have implemented for triggering ng-repeat works perfectly fine when adding items to the model, but it does not get called whe ...

Ways to make nodejs return a different value instead of an object promise

Within my user.js file, I have an async function designed to retrieve the avatar's location from the database. The code for this operation is as follows: async findavatar(username) { const sql = `SELECT image FROM users WHERE user = "${userna ...

The Trouble with Vue.js 2 and Axios Scopes

I previously encountered this "problem" but can't recall the correct approach to achieve the desired results. My current setup involves using Vue 2 to load data into variables that are then displayed on the HTML side: window.Vue = require('vue&a ...

Using Sinonjs fakeserver to handle numerous ajax requests

I utilize QUnit in combination with sinon. Is there a way to make sinon's fakeserver respond to multiple chained ajax calls triggered from the same method? module('demo', { beforeEach: function(){ this.server = sinon.fakeServer. ...

In vue, pagination links are displayed as dots instead of numbers

Struggling to integrate pagination in vue. Facing an issue where the pagination links are appearing as dots, depicted in the attached image. The correct number of pagination links display and I can navigate through different pages using the side navigation ...

What is the best way to retrieve the values of various input fields using their numbered IDs and then store them in a MySQL

I attempted to design a form that allows for multiple inserts, where users can add as many titles and languages as they desire by entering a number. The display of titles and languages is functioning correctly, but I am struggling to retrieve the individua ...

HTML stubbornly resists incorporating Javascript [UIWebView]

Currently, I am facing an issue while trying to animate a color property using jQuery 1.7.1 and the jquery color plugin downloaded from this link. I have ensured that all necessary files are included and part of the build target. Here is a simplified versi ...

Adjust the size of an element using the jQuery library's knob.js

There is a page Once the button is pressed, a circle element from the library jquery.knob.js appears. I am trying to change the size of the circle and have written this code: <div style="float:left; width:255px; height:155px"> <input ...

hold on for the arrays to be populated with data from the ajax calls

Currently, I am facing an issue on my page where I need to wait for all data to be loaded and stored in the appropriate arrays before proceeding with any actions. The data retrieval involves three separate AJAX calls, but sometimes the loading process take ...

Having trouble finding module: Unable to locate 'fs' - yet another hurdle with NextJS

Trying to access a JSON file located one directory above the NextJS application directory can be tricky. In a standard JavaScript setup, you might use the following code: var fs = require('fs'); var data = JSON.parse(fs.readFileSync(directory_pat ...

Modifying the attribute of an element inside an array

Presented below is an object: { "_id" : ObjectId("5a8d83d5d5048f1c9ae877a8"), "websites" : [ "", "", "" ], "keys" : [ { "_id" : ObjectId("5a8d83d5d5048f1c9ae877af"), "name ...

At what point does the promise's then function transition to being either fulfilled or rejected?

When dealing with promises in JavaScript, the then() method returns a promise that can be in one of three states: pending, fulfilled, or rejected. You can create a promise using the resolved and rejected methods to indicate when it should be fulfilled or r ...

React function failing to utilize the latest state

I'm facing an issue with my handleKeyUp function where it doesn't seem to recognize the updated state value for playingTrackInd. Even though I update the state using setPlayingTrackInd, the function always reads playingTrackInd as -1. It's p ...

In the world of node.js, functions almost always have a tendency to

As a beginner in the world of nodejs, I am diving into various guides and screencasts to grasp the basics. One aspect that has caught my attention is the handling of async/sync operations, reading files, and understanding how nodejs deals with callbacks/re ...

Is there a maximum number of window.open() calls that can be made in JavaScript?

Can the use of window.open("URL"); in JavaScript be limited? Upon attempting to open three windows using window.open("URL"), the third window did not open separately. Instead, it refreshed the contents of the first window and displayed the contents of ...

Creating a Node API that can patiently listen for external data

My current project involves building a server that fetches data from an external API and returns it to the endpoint localhost:3000/v1/api/. However, I'm facing a challenge where the data retrieval process takes approximately 2 seconds, leading to empt ...

Django enables anonymous Ajax requests to reach a Generic View

Here is the current progress I have made: from django.views.generic import View from django.views.decorators.csrf import csrf_exempt class ConfigurationView(View): @csrf_exempt def dispatch(self, *args, **kwargs): return super(Configurati ...

Isolating an array from an object?

I am working with a component that receives props: The data received is logged on the console. What is the best way to extract the array from this object? Before I pass the array to my component, it appears like this: ...

AngularJS/Ionic: Issue with HTTP GET requests not completing within a specified timeframe

Attempting to populate options with specific values instead of undefined, but encountering a delay in retrieving the values after the select box has finished loading. https://i.stack.imgur.com/SpEFP.jpg To illustrate, here is the HTML code snippet: < ...