After the use of app.use sendFile, it is crucial to ensure the jquery

I'm experiencing difficulty loading my jQuery library in my 'server.js' file. Currently, I have a file named 'route.js' which sends a file called 'home.html' on 'localhost:port/'. The home.html page displays fine, but I have a jQuery CDN/library and a link to server.js included. When I run node route.js, I keep getting an error message saying '$' is not defined, indicating that my JavaScript file is running before the HTML finishes loading. How can I resolve this issue?

//server.js

exports.path = require('path');
var express = require('express');
exports.app = express();

$(document).on('click', '.btn', sendSurvery);

function sendSurvey(){

    var myQueryUrl = "http://localhost:10003/survey";

    $.ajax({url: myQueryUrl, method: 'GET'});
}

//route.js

var library = require('../../server.js');

library.app.use(function(request, response){
    // response.sendFile(__dirname + '/../public/home.html');
    response.sendFile(library.path.resolve(__dirname + '/../public/home.html'));
})

library.app.get('/survey', function(request, response){
    response.sendFile(library.path.resolve(__dirname + '/../public/survey.html'));
})

library.app.listen(10003, function(){
    console.log('connected on 10003')
})

//home.html

<!DOCTYPE html>
<html>
<head>
    <title>Friend Finder Home Page</title>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
    <div class="rowOne">
        <div class="jumbotron col-lg-6">
          <h1>Hello, world!</h1>
          <p>Click the button NOW!</p>
          <p><a class="btn btn-primary btn-lg" href="#" role="button">CLICK NOW!</a></p>
        </div>
    </div>
<script src="https://code.jquery.com/jquery.js"></script>
<script type="text/javascript" src="../../server.js"></script>
</body>
</html> 

Answer №1

It seems like you're attempting to run your server code directly in the browser.

To fix this, try moving your JavaScript code into a separate static file within your public folder. You can then reference this file in your HTML like so:

// custom.js

$(document).ready(function(){

    $(document).on('click', '.btn', submitForm);

    function submitForm(){

        var formUrl = "http://localhost:10003/form";

        $.ajax({url: formUrl, method: 'POST'});
    }
})

//index.html

<!DOCTYPE html>
<html>
<head>
    <title>My Homepage</title>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
    <div class="rowOne">
        <div class="jumbotron col-lg-6">
          <h1>Welcome!</h1>
          <p>Click the button below!</p>
          <p><a class="btn btn-primary btn-lg" href="#" role="button">CLICK ME!</a></p>
        </div>
    </div>
<script src="https://code.jquery.com/jquery.js"></script>
<script type="text/javascript" src="/custom.js"></script>
</body>
</html> 

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

Uploading files using node.js with the help of express, multer, fast-csv

Currently, I am attempting to implement a file upload functionality using pug, multer, and express. The structure of the pug form used for uploading a file is as follows: form(method='POST' enctype="multipart/form-data") div.form-group ...

Access all the properties of an object within a mongoose record

My database contains a collection of documents that are structured using the mongoose and express frameworks. Each document follows this schema: const userSchema = new Schema({ firstName: { type: String }, lastName: { type: String }, email: { t ...

Enable scrolling feature for the table

I have integrated a bootstrap table into my React application, but I am facing an issue where the table is not scrollable. Whenever new content is loaded, it increases the height of the table instead of making it scrollable. Below is the code for my table ...

calling requestAnimationFrame from within a freshly created instance

I'm encountering an issue with executing an animation. Specifically, this problem arises within var ob1 = function() {};. Once triggered, the animation runs for a brief period before I receive the error message Uncaught RangeError: Maximum call stack ...

Add a jQuery script to the admin panel of a custom WordPress plugin for sending emails through ajax

I've been working on integrating a form into an admin page on WordPress. The goal is to allow users to input their email address and trigger an email to be sent to that address. To achieve this, I'm utilizing a jQuery Ajax function to transmit th ...

The Next.js API endpoint is struggling to process cross-domain POST requests

Dealing with a POST request in my NextJS application has been challenging. This particular post request is originating from a different domain. To address this issue, I included a receptor.ts file in the /pages/api directory: import { NextApiRequest, Next ...

Choose from the options provided to display the table on the screen

One of the challenges I am facing involves a table with two columns and a select option dropdown box. Each row in the table is associated with a color - green indicates good, red indicates bad, and so on. My goal is to have all values displayed when the pa ...

Is there a way for me to utilize request outside of router.get in order to assign socket.username to req.user.username, which corresponds to the logged-in user?

Can anyone assist me with this issue? I am trying to set the login username as the username in socket.username, but I am unable to access req.user.username. How can I define req in Socket.IO and is it feasible to achieve it this way? router = expres ...

Is it possible to update a URL in PHP without having to refresh the entire page by utilizing JavaScript?

Below is the JavaScript function I am using to create a URL: function reload(form){ var val1=form.dav.options[form.dav.options.selectedIndex].value; var val2=form.pathogen.options[form.pathogen.options.selectedIndex].value; var val3=form.topicF.options[for ...

Achieve the appearance of a galloping horse using JQuery

I am looking for a way to create the illusion of a horse running by displaying a sequence of images quickly. Each image in my folder shows the horse in motion, and I want to make it appear as if the horse is actually moving. Can anyone recommend a librar ...

The test is failing to execute the service mock promise due to an issue with the `

A problem has arisen while creating a mock for the BoardService. It appears that the .then function is not executing in the controller during testing, even though it works perfectly fine in the live application. Below is the test snippet: beforeEach(inje ...

A specialized Discord bot designed to capture and forward all direct messages to a designated webhook

I am looking to develop a bot using discord js v13 that can intercept all DM messages and send them to a webhook. Additionally, I want the bot to send a reply back to the sender once the admin gives the command '/reply [text]'. I am unsure of how ...

Issue with October CMS: Radio button selection triggers an Ajax call, but clicking twice in quick succession causes the content

I am currently utilizing October CMS and materializecss to develop a form with options on one of my pages. The form functions correctly as it dynamically loads content when different options are clicked. However, I have identified a problem where clicking ...

What could be the reason for the body-parser.json() not functioning properly? An error message has appeared stating "SyntaxError: Unexpected token } in JSON at position 100 at JSON.parse (<

I need assistance in understanding why my body is not being parsed in JSON format. Currently, I am using Postman for my POST request with the following header type: [{"key":"Content-Type","name":"Content-Type","value":"application/json","description":"", ...

`When you extend a $resource object, it effectively removes the prototype from the

Here's the current code snippet I'm working with: // Factory angular.factory('Student', function() { var defaults = { StudentId: null }; var Student = function(params) { angular.extend(this, angular.copy(de ...

Add a static line of names to a JavaScript file

Looking for a way to generate data with the following javascript snippet: for (var l = 0; l < table.length; l +=1) { fs.appendFile('results/Test'+ username +'.csv', var1+i, var2 , function(err) { if(err) { return c ...

The issue with Angular JS is that it fails to refresh the select and input fields after selecting a date

Currently utilizing Angular JS and Bootstrap, I have a query regarding updating the input for a datepicker calendar and a select from a function. The values are being successfully updated, however, they do not reflect on their respective inputs. It seems ...

Utilizing multiple optional key values in Vue Router

When working with vue-router, I am faced with the challenge of creating a route that can handle multiple optional parameters. For example, the route needs to be able to handle scenarios like: /something/a/1/b/2/c/3 /something/a/1/b/2 /something/a/1/c/3 /s ...

Puppeteer is unable to detect the node.js handlebars helpers

I'm utilizing puppeteer in NodeJs to generate a PDF file. I use handlebars to render the template and pass variables during compilation for handlebars to access them. Here is the current code snippet: const browser = await puppeteer.launch({ he ...

Leveraging the power of jQuery to capture and recycle a dynamically generated date

Using a jQuery plugin, a list of dates is generated. Implementing moment.js works perfectly fine as shown in this fiddle (http://jsfiddle.net/UJ9z4/). However, when attempting to apply it to the live file with the plugin running, an undefined error is enc ...