Transmit information securely to a web address using a button

I have a scenario where I have 3 buttons, and upon clicking any of them, I want to send the values within the <li></li> tags to a page called send.php. For instance, if I click on the first button, I wish to secretly send the value 1 to the send.php page. How can I monitor these buttons and retrieve the values accordingly?

<div class="cards">
    <div class="card shadow">
      <ul>
        <li id="one" class="price bottom-bar">1</li>
        <li><a class="btn" href="" >Send</a></li>
      </ul>
    </div>   
    <div class="card active">
      <ul>
        <li id="two" class="price bottom-bar">2</li>
        <li><a class="btn" href="" >Send</a></li>
      </ul>
    </div>
    <div class="card shadow">
      <ul>
        <li id="three" class="price bottom-bar">3</li>
        <li><a class="btn" href="" >Send</a></li>
      </ul>
    </div>
  </div>

Answer №1

I understand that you are referring to sending data privately to a specific URL.

Send data privately to a URL

In this context, it implies sending text using the POST HTTP method where the data is securely encrypted within the body of the request (if using HTTPS) rather than being visible in the URL itself (as with the GET HTTP method).

const buttonList = [...document.getElementsByClassName("btn")];

function handleButtonClick(event, button) {
  const valueToSend = button.parentElement.parentElement.querySelector("li").textContent;
  
  fetch("send.php", {
    method: "POST",
    body: valueToSend
  })
  .then(
    response=>console.log(`Message ${valueToSend} successfully sent! ${response.url} responded with ${response.ok ? "success" : "error"} code ${response.status}.`),
    response=>console.log("There was an error sending the message.", response)
  );
  
  event.preventDefault(); // Prevent the default link redirection
}

for (const button of buttonList) {
  button.addEventListener("click", e=>handleButtonClick(e, button));
}
<div class="cards">
    <div class="card shadow">
      <ul>
        <li id="one" class="price bottom-bar">1</li>
        <li><a class="btn" href="" >Send</a></li>
      </ul>
    </div>   
    <div class="card active">
      <ul>
        <li id="two" class="price bottom-bar">2</li>
        <li><a class="btn" href="" >Send</a></li>
      </ul>
    </div>
    <div class="card shadow">
      <ul>
        <li id="three" class="price bottom-bar">3</li>
        <li><a class="btn" href="" >Send</a></li>
      </ul>
    </div>
  </div>

It should be noted that this demo will present an error since there is no PHP script configured at stackoverflow.com/send.php to handle the messages. Feel free to run this code on your own website :)

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

Struggling to properly send props to the child component in Vue 3

Is there a way to pass data from the request through axios in the root component to the child using Vue? Currently, only the "title" field is displayed correctly, but I also need to output the "body". Note: This is my first time working with Vue and I&apo ...

Organize by the quantity of elements in an array using mongoose and MongoDB

Within my Post model, I have an array called likes that contains the ObjectId of users who liked the Post. My goal is to sort Posts based on the number of likes they have received. I've experimented with using $size, $sort, and aggregate, but so far ...

What is the best way to access the value of an HTML tag in React?

Currently in the process of developing a feature for the price tab using React. These components are designed to allow users to add price classes to their shopping cart. One challenge I'm facing is how to retrieve the HTML string of an HTML tag. Here& ...

Stop the event propagation when the back button is clicked

While utilizing ons-navigator, I am looking to customize the function of a particular element at a certain stage. Employing the onClick handler has allowed me to successfully trigger this function. However, upon exiting the onClick handler, the navigator ...

Showing the information obtained from an API request once the user submits the form without the need to reload the page

I am currently working on a form that will take search query requests from users upon submission and then display the results by making an API call. My goal is to show these results without the page having to refresh, using AJAX. The backend connection to ...

Tips for maintaining the integrity of an Array when passing it as an argument to a function in Javascript

I am working with an Array of objects called A There are 2 different drawing functions that make changes to A in their own unique ways. I want to preserve the original state of A. Are there best practices for achieving this? My current approach feels a bi ...

Optimal method for organizing individuals into teams using Google Apps Script

There are approximately 200 individuals in this particular department. Our goal is to form groups of 4, with each group consisting of members from different teams based in the same city. Each group must have one driver and three non-drivers, all sharing si ...

The changing perspective in relation to the current position of a background

I am currently working on implementing a parallax effect, which is mostly successful. However, I have encountered a minor issue. Instead of the parallax effect being relative to the element's current position, it abruptly jumps to position 0. How can ...

What is the best way to combine a javascript onclick function with php?

I'm currently facing an issue with integrating the onclick function in PHP. Can anyone lend a hand? Here are my code snippets <html> <head> <title></title> <script language="Javascript"> function delete() { val del ...

What is the best way to separate a string value with commas and send it to a controller?

Within my SQL table named Products, there is a field called AvailableSizes with a data type of NVARCHAR, which stores all the available sizes for a product. In my view, I have separated the values of the AvailableSizes field as shown below: <p> ...

Is your Z-Index failing to make an impact?

Currently, I am attempting to layer divs on top of a background image. All the elements have designated position attributes, and I have applied a 50% opacity to the background image so that what's behind it is partially visible. Despite setting the z- ...

JavaScript tip: How to disregard symbols that affect the length of text in a textbox?

I am working on a task which involves counting only the text, excluding symbols, entered in a textbox. For instance, if a user types email_ex_3/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="05374568646c692b666a68">[email ...

Extract the text enclosed by two specific symbols within a string and add it to a new array

I have a string formatted as follows: var str = "-#A This text belongs to A. Dummy Text of A. -#B This text belongs to B. Dummy Text of B. -#C This text belongs to C. Dummy text of C. -#Garbage This string should be ignored" I am looking to convert this ...

Retrieving POST data from requests in Node.js

My goal is to extract parameters from a POST request and store them in the variable postData using the request module. I found helpful information on handling post requests with Express.js here. Additionally, I came across this useful thread on how to retr ...

How can data be transferred between web pages using jQuery or JavaScript?

Imagine having two different pages on a Classified car website: The first page is the search page, which displays a list of all cars. Check out a sample search page here The second page is the details page, where you can find specific information about a ...

Updating webpage with the click of a button

How can I implement a button that refreshes the current page using JavaScript? Here is what I have so far: <button type="button" onClick="refreshPage()">Refresh</button> <script> function refreshPage() { // What should I in ...

Error Encountered in Reactjs: TypeError When Looping Through State Array to Render JSX Component

Currently in the process of constructing a gallery view showcasing cards that are populated with images fetched through an axios API call. The API call is made within a useEffect hook and the resulting object is then stored using useState. However, when ...

The PHP equivalent of converting data to a JSON string, similar to the

When working with PHP's json_encode($array), I've noticed that diacritics can sometimes get messed up. However, if I update my database column to type text and pass javascript-created JSON over HTTP, everything appears fine. The issue arises when ...

What is the best way to retrieve a value from an `<input type="number">` element and incorporate it into the script section?

Check out this code snippet <html> <head> head <title>title</title> </head> <script> var val1 = parseInt(document.getElementById('input1')); function bytton() { window.alert(val1); ...

Refreshing the Dropdown Menu with Jquery

Looking for a way to create a reusable dropdown menu using css/jquery? Check out this codepen: https://codepen.io/anon/pen/NxXXPg Is there a method to reset the 'active' status when clicking on a blank space or another html element? Here's ...