The onclick functionality is not functioning properly within email communications

My JavaScript code contains an AJAX call within Datatables, and this snippet of code is causing an issue:

{   "data": null, 
    "width": "10%",
    "render": function(data){
        icon2 = '<center><button type="button" class="btn btn-info m-btn m-btn--icon m-btn--icon-only btn-sm" ' +
            'data-toggle="m-tooltip" title="" onclick="sendEmail('+data.email+')" data-placement="top" data-original-title="' + 'Send Email' + ' "> <i class="la la-envelope"></i></button>';
        icon2 += '</center>';

    return icon2; }
}

In addition, I have a function defined as follows:

function sendEmail(email){
   console.log("email: ", email);
}

However, upon clicking the button, I encounter the following error message: **Uncaught SyntaxError: missing ) after argument list**.

I am curious if there are any alternative solutions to resolve this issue.

Answer №1

When dealing with literals, it's important to remember that they need to be quoted.

You cannot simply write:

onclick="sendEmail(<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4f2d202d0f2a372e223f232a612c2022">[email protected]</a>)"

A quick workaround is to add a few ' to the data, but this assumes there are no other issues with the data (like containing ', ", or new lines).

The recommended approach is to:

  1. Encode the data as JSON to make it a valid JavaScript literal
  2. Encode special characters in HTML to prevent parsing issues

For example:

const email = data.email;
const js_safe_email = JSON.stringify(email);
const html_safe_email = js_safe_email
     .replace(/&/g, "&amp;")
     .replace(/</g, "&lt;")
     .replace(/>/g, "&gt;")
     .replace(/"/g, "&quot;")
     .replace(/'/g, "&#039;");
icon2 = '<center><button type="button" class="btn btn-info m-btn m-btn--icon m-btn--icon-only btn-sm" ' +
        'data-toggle="m-tooltip" title="" onclick="sendEmail('+html_safe_email+')" data-placement="top" data-original-title="' + 'Send Email' + ' "> <i class="la la-envelope"></i></button>';

While this method may seem messy, it is better than combining strings of data within JS embedded in HTML. It's generally recommended to use DOM methods instead.

Answer №2

Upon closer inspection, the issue seems to lie within the "render": function(data){ segment. While the function itself is properly closed, it appears that the enclosing hash is not.

{   "data": null, 
    "width": "10%",
    "render": function(data){
        icon2 = '<center><button type="button" class="btn btn-info m-btn m-btn--icon m-btn--icon-only btn-sm" ' +
            'data-toggle="m-tooltip" title="" onclick="sendEmail('+data.email+')" data-placement="top" data-original-title="' + 'Send Email' + ' "> <i class="la la-envelope"></i></button>';
        icon2 += '</center>';

    return icon2; }
}

Please take note of the extra } present at the end of the code snippet.

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

Unreliable Raycasting with Three.js

I am attempting to identify clicks on my Plane mesh. I have established a raycaster using provided examples as instructions. Below is the code snippet: http://jsfiddle.net/BAR24/o24eexo4/2/ Clicks made below the marker line do not register, even if they ...

Transferring data securely via URLs

I need advice on securing a JavaScript function that passes values into URLs in order to navigate to another page. What precautions should I implement to prevent manipulation of this process? This is the code snippet I am currently using: window.location ...

Generate a JSON structure from HTML with the help of jQuery

Issue Overview Imagine a scenario where there is a delivery of assorted candies. The delivery consists of multiple boxes, each containing various types of unique candies. Each box and candy type has its own distinct identifier. Moreover, every candy comes ...

The Bootstrap CDN is malfunctioning and displaying errors in the console

I attempted to incorporate Bootstrap 4.5 using the CDN provided on their main website. However, after adding all the code lines to my project, I encountered numerous issues with my custom CSS and the Bootstrap carousel failing to function. Upon inspecting, ...

Looking to display database information using javascript

Currently, I am working on a project involving PHP code where I retrieve variables from an input and utilize AJAX. Here is the code snippet: $.ajax({ type: "GET", url: "controller/appointment/src_agenda.php", data: { function: "professional", ...

generating a new item using Mongoose searches

How can I generate an object based on queries' results? The table in the meals operates using database queries. How do I handle this if the queries are asynchronous? const getQueryResult = () => { Dinner1300.count().exec(function (err, count) ...

Avoiding URL images on 404 errors in frontend applications

My goal is to dynamically implement images (from image_url_1.jpg to image_url_5.jpg) based on a specific URL. While everything works fine, I encounter an issue when a particular image, like "image_url_4.jpg," is not available and results in a 404 Error cau ...

The code "Grunt server" was not recognized as a valid command in the

I recently set up Grunt in my project directory with the following command: npm install grunt However, when I tried to run Grunt server in my project directory, it returned a "command not found" error. Raj$ grunt server -bash: grunt: command not found ...

after ajax post, enhance original object by merging with the latest server values

After making a call to the server and successfully saving some data, I need to update the JSON array object that I have with new values. Here is a snippet of my code: [ { "id": 1, "uuid": "ce54acea-db20-4716-bceb-2f3deb1b2b86", "name": null, ...

Display a thumbnail image using a v-for loop

Looking for help with implementing a photo preview in my code using BootstrapVue. The Vue devtools show that the form-file contains the image, but my 'watch' isn't functioning properly. Any assistance would be greatly appreciated! Here is ...

What is the best way to retrieve a document from a collection in a Meteor application?

My experience with mongodb is very limited, so I need help on how to retrieve a document from a meteor collection. I am trying to check if a document exists for the user and update it with an object. if (Saves.find({_id: Meteor.userId()}).fetc ...

I'm currently learning about things that never change and struggling to grasp their meaning

I'm currently delving into the world of immutable.js record and trying to wrap my head around it. However, this particular piece of code is really throwing me for a loop. Here's my Question: I understand [import, export,const], but what ex ...

NodeJS presents a potential maze of confusion with its promises

I've been struggling to grasp the concept of asynchronous code execution in NodeJS. My goal is to fetch the output of ip a on a Linux machine and extract the IP Subnet manually. Once that is done, I simply want to use console.log() to display the IP S ...

perform the directive function following the ng-cloak execution

I am having an issue with my content using the ng-cloak directive, as I would like to retrieve the height of an element using innerHeight() within a directive. However, when I use innerHeight(), the element is hidden by ng-cloak so the result is always 0. ...

Accessing HTML elements that are created dynamically in AngularJS

I am facing an issue where I cannot access a function within a newly created DOM element. Despite my best efforts, I can't seem to figure out what is causing this problem. $scope.createCustomHTMLContent = function(img, evtTime, cmname, evt, cust, ser ...

Pass along a variable with either "&" or "%" to a PHP file utilizing JavaScript

I have a JavaScript script that is sending 4 variables to a PHP page. The issue arises when one or more of these variables contain special characters like "&" or "%". The script ends up only sending the content before those characters. For example, if ...

Determining the minimum and maximum values of a grid using props in a React component

I have created a code for a customizable grid screen that is functioning perfectly. However, I am facing an issue where I want the minimum and maximum size of the grid to be 16 x 100. Currently, when a button is clicked, a prompt window appears asking for ...

The new pop-up window appears smaller than expected in Internet Explorer

There has been a bug report regarding the course opening in a smaller popup window. The JavaScript code used to open the popup is: course_window=window.open(urlString,"", "toolbar=0,directories=0,location=0,status=0, menubar=0,fullscreen=0,scroll ...

The property 'scrollHeight' is undefined and cannot be read

I've created a messaging system using javascript and php, but I'm facing an issue. When new messages are received or the chat log grows longer, it creates a scrollbar. The problem is that when a new message arrives, the user has to manually scrol ...

"Enjoying the convenience of a stationary header while browsing on your smartphone

Hey there! I'm currently facing an issue with my website's fixed horizontal nav bar when zooming in on a mobile device. After doing some research, it seems the only solution is to implement some javascript. I came across a jquery fix (see below) ...