File Upload and Email Trigger through Bootstrap Modal Window

I'm currently working on a modal window that includes a file upload feature. Within this modal, there is a button labeled "send to email." I'm looking for guidance on how to create a function that will successfully send the uploaded file to an email address.

<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
  Launch Modal
</button>

<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-fullscreen-lg-down">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="file-loading">
          <input id="input-b9" name="input-b9[]" multiple type="file">
        </div>
        <div id="kartik-file-errors"></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Send to email</button>
      </div>
    </div>
  </div>
</div>
<script>
$(document).ready(function() {
    $("#input-b9").fileinput({
        showPreview: false,
        showUpload: false,
        elErrorContainer: '#kartik-file-errors',
        allowedFileExtensions: ["pdf", "doc", "docx"]
        //uploadUrl: '/site/file-upload-single'
    });
});
</script>

https://codepen.io/PineappleBros/pen/KKoENrN

Answer №1

As mentioned by @icecub, sending emails directly from client-side JS is not possible. Instead:

  • Integrate a <form> element into your modal (preferably with
    enctype="multipart/form-data"
    and
    action="path/to/backend/script"
  • When the "send to email" button is clicked or the form is submitted, gather the values of the <form> in a FormData object. The simplest way is to pass the complete <form> element into the FormData constructor:
formEl.addEventListener('submit', (e) => {
  e.preventDefault(); // <-- prevent browser from reloading on form submission
  fetch(e.target.action, // <-- points to backend script
        {
          // ... elided ...
          body: new FormData(e.target) // <-- create FormData object from <form>
          // ... elided ...
        }
  ).then(
     // ... elided ...
  );
});
  • Send the FormData object via
    XMLHttpRequest/Fetch/whatever-you-use
    to a backend script (which could be PHP, Python, NodeJS, Ruby, etc.)
  • The backend script should read the FormData, then assemble and send an email
  • Return a success or failure message to the client (using JSON/XML/whatever-you-prefer)

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

Identifying AJAX scripts within JavaScript content

Is there a way to identify the specific code in javascript returned by the web server that enables the client Web to initiate AJAX calls? Essentially, I am looking for any existing libraries that can extract the URL embedded within the javascript code sent ...

Using AJAX to retrieve model objects

In my Django application, I have a Customer model where new users are constantly being added in the background. I am trying to dynamically list these customers using AJAX, but I am having trouble figuring it out. Can someone help me with this? def ajax_vie ...

I'm feeling stuck trying to iterate through this array, especially when the console keeps saying it's actually an object

As I embark on a personal project to fetch and display information from Reddit, I find myself confused by an error that keeps popping up. There are two main points of confusion for me. The issue arises when the page fails to render due to the message ...

responding with a value of undefined for the get request

My current project involves URL shortening, but I keep encountering an 'undefined' result in my GET request. Additionally, sometimes I also receive a blank page as a result. Despite everything appearing to be correct based on my knowledge, I&apos ...

Verify authenticity through JavaScript

I've come across several discussions about a similar issue, but I'm not sure how to apply those solutions to my specific situation. Here's the login form I'm working with: <form action=do_login.php?id= method=post> ...

ajax rendering in Ruby on Rails

After creating a Recipient, I want to display a success confirmation message but I keep encountering a missing template error: ActionView::MissingTemplate - Missing partial recipients/_recipient with {:locale=>[:fr], :formats=>[:js, :html], :v ...

Sometimes the AngularJS scope is refreshed only intermittently

I am encountering an issue with a list of cards retrieved from an API and displayed in a table using ng-repeat. The problem arises when I attempt to delete a card - sometimes it remains in the view, while other times it disappears as expected after confirm ...

What is the best way to confirm only one click per browser?

Is there a way to limit rating functionality to allow users to rate only once per browser session? I am looking to implement validation for a rating component in React where users can only submit their rating once per browser. Below is an example of the ...

Developing a TypeScript NodeJS module

I've been working on creating a Node module using TypeScript, and here is my progress so far: MysqlMapper.ts export class MysqlMapper{ private _config: Mysql.IConnectionConfig; private openConnection(): Mysql.IConnection{ ... } ...

Guide on Generating a Response Object in Node.js/Express

My current situation involves needing to execute a res.redirect('/signin'), however, I have already utilized my res object for a res.render. Is there a feasible method for me to create a new Response Object (res) so that I can carry out the redi ...

Tips for utilizing the chosen characteristic to display the selected choice in a dynamic table dropdown menu

Here is the code snippet that sends data for editing a model in a table called 'student details'. The goal is to display the selected option in a dropdown list passed through an AJAX request. Although the value is being passed to the table, the s ...

Executing a WebMethod in C# codebehind without the need for a server form on the ASPX page

Having encountered issues with styling and the need for multiple forms on a single web page, I currently have a form that is placed outside of the normal runat=server form. I am wondering if it's possible to still invoke a WebMethod in the C# codebeh ...

Is it possible to manipulate the carousel image within the div element?

I am working on a Bootstrap code snippet that showcases an image using the w-100 class to span the full width of the page. However, the challenge I'm facing is making sure the image is visible to users while keeping it small enough so they won't ...

Failing to establish a state on schedule

Hey there, I'm currently in the process of learning react and have come across a function that I need some assistance with: async function onSubmit(){ try{ const url = `https://maps.googleapis.com/maps/api/geocode/json?address=${value.label} ...

Tips for utilizing FileReader in a synchronous manner within the context of react/redux

Struggling to design a solution that integrates with the FileReader API in a react/redux application due to its asynchronous nature. Despite researching, I haven't found a suitable approach just yet. In my react component, I utilize react-dropzone to ...

Is there a way to send an ajax post request when the nextpage button is clicked on jqgrid in order to fetch a fresh batch of data

Is there a way to use an ajax post request when the next page button is clicked on jqgrid in order to load a new set of data? I need to send the id of the last row to retrieve the following set from the database. ...

What purpose does the dollar sign symbol serve in the JavaScript programming language?

I've been diving into JavaScript and trying to understand the significance of the $ symbol beyond just its use in regular expressions. Despite my research efforts, I haven't been able to uncover much information on this topic. If anyone has any r ...

Tips for positioning buttons in a row below dynamic text using Bootstrap 3

Is there a way to align buttons under a variable piece of text in Bootstrap 3? Currently, when the code example is viewed in full screen, the three buttons do not align horizontally. Current Behavior: https://i.sstatic.net/lEQ7o.png My goal is to have t ...

Exploring the possibilities of PhoneGap, leveraging the power of jQuery getJSON

I'm currently working on a mobile application using PhoneGap that requires AJAX functionality with jQuery. However, I've encountered an issue when trying to retrieve a JSON from a PHP web service with CORS enabled. The strange thing is that the c ...

Retrieving information within a Vue component

I am struggling to access some data I have bound to a component without success. How can I achieve this? Below is my component: export default { name: 'component-vallingby', data() { return { } }, created() {}, methods: {} } And h ...