Leverage JavaScript variables within JSON when making API calls

Utilize this code to integrate the Mandrill API for sending emails from a website. The issue at hand is incorporating HTML input into the JSON format required to send the email to the correct address. Take a look at the following code snippet:

<head>
    <script type="text/javascript" src="https://mandrillapp.com/api/docs/js/mandrill.js"></script>
    <script type="text/javascript" src="send-email.js"></script>
</head>

<body>
    <input type="text" value="email" id="maila"/>
    <button onclick="sendTheMail(); return false;">Send Email</button>
    <pre id="response"></pre>
</body>

The above code contains HTML where users can input an email address to which they want to send an email.

Next, we have a JavaScript (.js) file as follows:

function log(obj) {
  $('#response').text(JSON.stringify(obj));
}

var m = new mandrill.Mandrill('API-KEY');

var mailaddress = document.getElementById("maila").value;

var params = {
  "message": {
      "from_email":"example@example.com",
      "to":[{"email":"recipient@example.com"}],
      "subject": "Sending you an email",
      "html": "Body of the email goes here"
  }
};

function sendTheMail() {
  m.messages.send(params, function(res) {
      log(res);
  }, function(err) {
      log(err);
  });
}

In the above JavaScript, the variable `mailaddress` fetches the user-entered email address. To include this dynamic email address in place of `"recipient@example.com"`, modifications are needed since directly inserting the variable won't work due to incompatible data types.

I've tested and verified the program's functionality by manually inserting an email address, and it successfully sends out emails. Although I’ve scoured forums and search engines for solutions on this issue, unfortunately, no clear-cut solution has been found.

UPDATE I have managed to resolve the issue with your valuable input. I believe the getElementById function needs to be encapsulated within a specific function, leading me to make slight adjustments to the code structure. Here’s the updated and functional code:

function log(obj) {
    $('#response').text(JSON.stringify(obj));
}

var m = new mandrill.Mandrill('API-KEY');

function sendTheMail() {
    var mailaddress = document.getElementById("maila").value,
        recipient = [{"email": String(mailaddress)}];
    
    var params = {
        "message": {
            "from_email": "sender@example.com",
            "to": recipient,
            "subject": "Sending an email using Mandrill API",
            "text": "Learning Mandrill API through practical exercises.",
            "autotext": true
        }
    };

    m.messages.send(params, function(res) {
        log(res);
    }, function(err) {
        log(err);
    });
}

Answer №1

let
  emailAddress = document.getElementById("email").value,
  mailRecipients = [],
  mailRecipient = { "email": emailAddress };

mailRecipients.push(mailRecipient);

let mailParams = {
  "message": {
    "from_email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7af8e5eceea1b3c0e9fbd9a4bda894833ff1fdff">[email protected]</a>",
    "to": mailRecipients,
    "subject": "Reaching out to you",
    "html": "Content for the email body",
  }
};

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

What is the best way to add an element while preserving its original placement?

I need a solution to duplicate the code of an element and transfer it to another element without removing it from its original position. Currently, I have a JavaScript function that allows you to move a picture to a box when it's clicked. However, th ...

A React component that exclusively renders component tags

After successfully loading index.html with no JavaScript errors, I ran into an issue where nothing was rendering on the page. Upon inspecting the webpage, all I could see was a tag and nothing else. It turns out that I have a component called "list". The ...

Sending a collection of JSON data objects to a PHP page using AngularJS

Let me illustrate the structure of my JSON data: $scope.a = [{ "email": "keval@gmail", "permissions": { "upload": "1", "edit": "1" } }, { "email": "new@aa", ...

Error: Module 'fs' does not export the function 'existsSync' as requested

When I simulate the behavior of the fs module jest.mock('fs', () => { return { default: { readFileSync: () => { return CONTENT_DATA; }, existsSync: () => {}, }, }; }); Then I attempt to dynamically ...

Struggling with rendering components in REACT?

I'm encountering an issue with rendering the Butcher Shop component. I can't seem to pinpoint what's causing it to be null or undefined. Can someone help me identify the mistake? Nothing is showing up on the DOM and I keep getting this error ...

Nothing is in the Laravel array when using `$request->all()`

In the process of developing a shopping cart using Laravel. Here are the details : Routes : Route::post('/cart/add', 'CartController@store')->name('cart.store'); Route::patch('/cart/{product}', 'CartContro ...

Embed JavaScript locally within an iframe HTML

When attempting to add HTML code within an iframe to showcase data, everything works as expected. However, the issue arises when trying to include any JavaScript within the iframe, as it doesn't seem to be recognized locally. Below is the example cod ...

The event emitted doesn't appear to be caught by EventBus.$on in Vue.js

Currently trying to trigger an event from router.beforeEach and listening for it in another component. Although the vue devtool confirms that the event is being triggered, my component seems unable to capture it. Thank you for your help. This is how I dec ...

Angular is throwing a RangeError due to exceeding the maximum call stack size

Encountering a stackOverflow error in my Angular app. (see updates at the end) The main issue lies within my component structure, which consists of two components: the equipment component with equipment information and the socket component displaying conn ...

Guide to activating text entry following selection of a related radio button in Bootstrap 4

I am currently utilizing Bootstrap 4 to create a mock item submission form for my web application. Within the transaction row, the text input field for price is initially disabled by default. What steps should I take in order to enable the text input field ...

Is there a way to continuously submit a form in React every 10 seconds, even if it includes events?

I have a form with input fields where I collect data upon form submission. However, I want the form to submit automatically every 10 seconds without the need to click a button or press enter. I tried using useEffect to create an interval, but it resulted i ...

Unleashing the power of JavaScript: A guide to dynamically generating nested arrays

Can you take a look at the code below and help me find the mistake? function pair(str) { // Function to pair specific letters in a string for (var i = 0; i < str.length; i++) { // Check and pair letters based on certain conditions if (s ...

moment.js incorrectly interprets the month as the day instead of the actual day

I am currently using moment.js (moment-with-locales.js - v.2.14.1) in my project. My goal is to extract only the date from a datetime string and remove the time. However, when I use the .format() method of moment.js, I receive an incorrect date. The datet ...

Extract data from JSON and append it to a new column within an already established CSV file

I am attempting to extract data from a JSON object (provided below) and insert it into a new column in an existing CSV file. Currently, when I run my code (also shown below), the only thing being added to the new column is the word "Array" repeatedly. How ...

Displaying content conditionally in Vue JS upon the initial page load

I am currently working on a Vue component that is supposed to render the first time a page is opened. However, I am facing some confusion regarding the logic behind this. My approach involves using localStorage to check for an item called 'wasVisited& ...

Remove the initial section of the text and provide the rest of the string

I am a beginner in the world of Javascript and unfortunately I have not been able to find an answer to my current problem. Here is the situation. On a webpage, I am receiving a URL that is sometimes presented in this format: http://url1.come/http://url2.c ...

Setting up dynamic routing in AngularJS for links

I am facing some confusion regarding routing in AngularJS. Normally, we can configure routes in angular.config() when the angular module is loaded. At that time, we define static information such as routePath, templateUrl, and controller. However, I am u ...

Is there a way to programmatically switch a mobile device to desktop view using HTML or JavaScript code?

I recently made some updates to my website, but the mobile view is not as polished as I would like it to be. I attempted to modify the code myself, but it has been challenging, especially since I did not originally develop the front-end. Does anyone know ...

Generate projectiles within a game periodically

I've created a game that features a main character and enemy soldiers who shoot back. I'm facing an issue where only one enemy soldier shoots at intervals, even though I initially used setInterval for both of them. Any suggestions on how to fix t ...

translating python's color function to javascript

Can anyone help me convert the Python function below into JavaScript? Thank you! def coloring(a): #takes an integer number, returns rgb color a = a % 255 akM = a // 43 ypD = a % 43 if akM == 0: color = (255, ypD*255/43, 0) elif akM ...