What is the best way to trigger a JavaScript function using an HTML button?

I am trying to trigger a JavaScript file from an HTML component by clicking on a button, but nothing happens when I click the button:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">

</head>
<body>

<p id="counter">Loading button click data.</p>


<button  id="buttonForScraping">begin to scrape!</button>
<script>
  function startScrape(){
    jQuery.ajax({
      type:'get',
      url:'../../../scraping.js',
      data:[],
      dataType:'json',
      success: function(rs)
      {},
      failure : function(rs)
      {}
    });
  }
</script>
</body>

</html>

The above code contains the HTML and the following is the JavaScript code:

const {exec}  = require('child_process');
const button = window.document.getElementById('buttonForScraping');
button.addEventListener('click', function(e) {

exec('scrapy crawl address', (err, stdout, stderr) => {


  console.log(`stdout: ${stdout}`);
  console.log(`stderr: ${stderr}`);

});});

Since the scrapy command is a Python command, I believe an ajax call needs to be made in order to run it on the server.

Answer №1

In order to execute code on the server side, it is essential to have a server that can handle incoming requests. The following example illustrates how this can be achieved:

const { exec }  = require('child_process');
const app = require("express")(); // To install this dependency, use "npm install express"

app.get("/address", (req, res) => { // Define the server endpoint
 exec('scrapy crawl address', (err, stdout, stderr) => {

   res.json({ // Send response back to client upon command execution
     stdout: "" + stdout,
     stderr: "" + stderr
   });

});

app.listen(8000,() => console.log("Server is up and running"));

This code snippet will launch a server on port 8000 when you run the script using node ./scraping.js. It will return a JSON response when accessed at http://localhost/address

Upon clicking the button on the front end, an AJAX request needs to be initiated towards the backend:

// Using "async" for better callback handling
button.addEventListener('click', async function(e) {
 try {
  // Fetch API offers native support for AJAX requests
  // 'await' makes asynchronous handling more efficient
  const { stdout, stderr } = await fetch("http://localhost/address").then(res => res.json());
   console.log(stdout, stderr);
 } catch(err) {
   console.error("An error occurred while communicating with the server", err);
 }
});

Answer №2

When you want a JavaScript function to run when a button is clicked, you can follow this example.

Start by adding an HTML button with the onClick() attribute:

<button onClick="executeFunction()">Click Me</button>

The onClick() attribute instructs the browser to execute a specific JavaScript function. Next, define the function in your JavaScript file:

function executeFunction() {
  alert('Function executed!');
  console.log('Function executed');
}

This example function displays an alert message and logs a message to the console when the button is clicked. However, functions can be much more intricate than this.

If you need to trigger a server-side method or a Python command from an HTML page, it may require a more advanced setup.

Answer №3

To properly integrate the js file with the html file, follow the example below. Important: Double check that the path to the js file is accurate in the src attribute within the script tag.

<script src ="myScript.js"></script>

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

Is it possible to rewrite this function recursively for a more polished outcome?

The function match assigns a true or false value to an attribute (collapsed) based on the value of a string: function match(children) { var data = $scope.treeData for (var i = 0; i < data.length; i++) { var s = data[i] for (var ...

What is the technique for accessing dynamic object properties in Javascript?

I am dealing with a dynamic object where the property values change based on different data sets. For example: MyObj = { country:"Ind", Place:"Pune"} Now, I have a data value that determines which property value I need to retrieve. var MyArr = this.Filt ...

Changing innerHTML in CoffeeScript

Are there other options instead of using the 'innerHTML' property in CoffeeScript? In JavaScript, you typically write something like this: document.getElementById('element').innerHTML = "blah_blah" Is there a different approach to ac ...

Submitting a form in Rails without refreshing the page and dynamically updating the view

Hello everyone! I am currently utilizing Rails and in my process, I would like the user to perform the following steps on the same page: Input their address Completing the form Submit the form Clicking to submit Update the view to display the add ...

Cross-Origin Resource Sharing - redirecting to the page that is being retrieved by a subsequent GET request

My web page makes AJAX requests using JQuery $.ajax to load content. However, if the user session expires, re-authentication is required. When a user is not authenticated, two GET requests are sent to the website: one with the requested URL in the AJAX (o ...

Adapting Classes in Javascript Based on Screen Width: A Step-by-Step Guide

I'm dealing with two separate menus - one for mobile version and one for PC version. However, the mobile menu seems to be overlapping/blocking the PC menu. How can I resolve this issue? I've attempted various solutions such as removing the mobil ...

How to retrieve the width of an unspecified element using JavaScript

Seeking help with a div element that adjusts its size based on the elements it contains. How can I determine the final size of this dynamic div without checking the sizes of its internal elements? I've attempted to parse all the properties of the obj ...

Obtain the index by clicking on an element within an HTMLCollection

Within my HTML code, I have 9 <div> elements with the class ".square". I am looking to make these divs clickable in order to track how many times each one is clicked and store that information in an array. For example, if the fifth <div> is c ...

What exactly do `dispatch` and `commit` represent in vuex?

Recently, I came across a Typescript project in Vue.js with a Vuex store that had the following code: async getUserProfile ({ dispatch, commit }: any) {} I found working with any cumbersome as it doesn't provide helpful autocomplete features in the ...

Implementing Do Not Track in an express application

I am trying to implement a feature named "consent" in my Nodejs express app that utilizes the Do Not Track (DNT) functionality from browsers. This function is supposed to integrate Google analytics on rendered pages only when DNT is not active or its state ...

Struggling to retrieve an element from an object received through a get request in Express

I am facing an issue with a get request that returns an array of objects retrieved from a database using Knex. I am trying to use .map to make these objects accessible, but I am struggling with accessing the final element which is a sum(). It seems like a ...

Stopping the page from scrolling back to the top when an asynchronous update occurs in Angular

Once the asynchronous request is complete, I dynamically add a new element to the top with this code snippet: Array.prototype.unshift.apply(scope.conversation, conversation.data.message); The issue arises when the added element causes the scroll position ...

Tips for transmitting one or multiple data using jquery.ajax

I found this code on stackoverflow and it is working well for uploading multiple files. However, I am facing an issue where I cannot send additional parameters along with the file upload. Despite trying various methods, I have been unsuccessful in sending ...

How to redirect to a different page within the same route using Node.js

When attempting to access the redirect on the login route using the same route, I first call the homeCtrl function. After this function successfully renders, I want to execute res.redirect('/login'). However, an error occurs: Error: Can't ...

Flipped the dimensions of an image for better responsiveness

Trying to implement this particular design on a responsive website. Wondering if there's a way to establish an inverse resizing technique using jQuery / Javascript so that as the viewport shrinks, the text size increases. Attempted to use jQuery to a ...

Limited functionality: MVC 5, Ajax, and Jquery script runs once

<script> $(function () { var ajaxSubmit = function () { var $form = $(this); var settings = { data: $(this).serialize(), url: $(this).attr("action"), type: $(this).attr("method") }; ...

What steps can be taken in Javascript to handle a response status code of 500?

I am currently utilizing a login form to generate and send a URL (referred to as the "full url" stored in the script below) that is expected to return a JSON object. If the login details are accurate, the backend will respond with a JSON object containing ...

What could be causing the null value issue when sending data to a controller via Laravel AJAX?

In my annonces table, I have multiple images and I want to update them. When I try to send the data (id, images, token) to the controller, it is returning null for the id. details.blade.php <h3 class="jumbotron" id="id">{{ $annon ...

Google Sheets displaying blank values after submission via an AJAX call

I have been working on transferring data from my web app to a Google spreadsheet and I am encountering some issues. I followed the script provided by Martin Hawksey, which can be found here: https://gist.github.com/mhawksey/1276293 Despite setting everyth ...

What methods can I use to adjust link distance while using the 3d-force-graph tool?

Exploring the capabilities of the 3D Force Graph from this repository has been an interesting journey for me. I am currently seeking ways to adjust the bond strength between nodes. I am specifically looking to modify either the link width or length, but ...