Utilizing JSON strings within an onclick function

Hey there, currently I am working on sending an encoded JSON through the onclick attribute. However, I am facing a challenge because the JSON contains strings with a lot of apostrophes and quotes which end up closing the quotes in the onclick attribute.

Update 1

This particular situation is within a "return" of jquery DataTables that are loaded by ajax. Since the JSON varies for each item, I am unable to use addEventListener (please correct me if I'm mistaken).

I specifically require the getJsonObj() function to trigger a modal displaying all the information inside.

{data: null,
        render: function (data, type) {
          const json = JSON.stringify(data);
          console.log(json);
          return `<a onclick="event.preventDefault();getJsonObj(${json})"style='cursor: pointer' id='modalApp' class='orange-link uk-text-bold uk-text-uppercase'>${data.full_name}</a>`;
        },
}

The current output looks like this:

https://i.stack.imgur.com/Sxcci.png

Any suggestions on how I could resolve this issue and successfully send the JSON without any complications?

Update 2

To clarify, I am not utilizing any frameworks apart from javascript, jquery, and Jquery datatables in this scenario.

Answer №1

It is important to HTML escape any strings that are being inserted into an HTML document. The issue in your case arises from the quotes in the JSON string conflicting with the quotes in the HTML onclick attribute. To resolve this, you can utilize the following function which will replace the JSON quotes with &quot;

function escapeHtml(unsafe) {
  return unsafe
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;");
}

<a onclick="event.preventDefault();getJsonObj(${escapeHtml(json)})"style='cursor: pointer' id='modalApp' class='orange-link uk-text-bold uk-text-uppercase'>${data.full_name}</a>

For more information on escaping HTML special characters in JavaScript, you can refer to this Stack Overflow post

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

Adding numbers to a textbox using a JavaScript algorithm

There are two textboxes in this scenario. The first box should always contain 4 digits when you leave it, while the second box should always contain 10 digits. A javascript function needs to be implemented so that when a user leaves one of the textboxes, ...

Struggling to effectively use XPath to target LI elements that contain specific text

Below is the HTML code for the list item in question: <li class="disabled-result" data-option-array-index="1" style="">4" (0)</li> Here is my attempt at using JavaScript to hide this list item, but it's not working as expected: var xpat ...

GM Unable to Establish Cross-Domain Ajax Connection

Attempting to populate a form on a client's website with data from our database using a Greasemonkey script, but struggling with the same origin policy. I have tried using GM_xmlhttpRequest and even specified @grant GM_xmlhttpRequest but without succ ...

Triggering blur event manually in Ionic 3

Is there a way to manually trigger the blur event on an ion-input element? The ideal scenario would be with an ionic-native method, but any javascript-based workaround will suffice. My current configuration: Ionic: ionic (Ionic CLI) : 4.0.1 (/User ...

The functionality of sending a response to a client in Node.js Express seems to be malfunctioning

I am facing an issue with sending a response back to the client. Despite not receiving any errors, it seems like the response is not working as expected. Can anyone help me figure out why? Below is my code snippet: exports.login = function (req, res, next ...

Exclude the map entry from displaying in a JSON document

I am currently working with the following endpoint: @RestController @RequestMapping(value = "/info") public class InfoEndPoint { .... @Autowired public InfoEndPoint(....) { .... } @RequestMapping(method = RequestMethod.GET) ...

What is the process for implementing Sequelize to manage and modify multiple tables simultaneously?

I am currently working on developing the back-end with DB using Sequelize ORM. My main challenge is creating or updating data in multiple tables simultaneously. Below are some examples of what I am trying to achieve: //Tables const main = sequelize.define ...

The back button fails to refresh the page on a website utilizing Ajax technology

Recently, I implemented AJAX on a client's website to introduce some smooth animations for page transitions. When navigating from the homepage of firedogcreative.com to the edit page, and then to one of the work pages, we see a history like this: fir ...

retrieve JSON object from deferred response of AJAX request

After utilizing Ajax to send an item to a SharePoint list, I aim to incorporate the jsonObject received in response into a list of items. Located in AppController.js $scope.addListItem = function(listItem){ $.when(SharePointJSOMService.addListIte ...

Comparison between Mobile Phone's innerWidth and innerHeight Versus Resolution

My test phone, the Galaxy S3 Mini, has a resolution of 800x480 according to its specs. Strangely, when I run the following code in my HTML game: window.innerWidth window.innerHeight The width appears as 533 and the height as 295. I recently discovered ...

Try out a Vue.js Plugin - A Comprehensive Guide

Currently, I am delving into the world of Vue.js. In my journey, I have crafted a plugin that takes the form of: source/myPlugin.js const MyPlugin = { install: function(Vue, options) { console.log('installing my plugin'); Vue.myMetho ...

MUI Alert: Encountered an Uncaught TypeError - Unable to access properties of undefined when trying to read 'light' value

After utilizing MUI to create a login form, I am now implementing a feature to notify the user in case of unsuccessful login using a MUI Alert component. import Alert from '@mui/material/Alert'; The code snippet is as follows: <CssVarsProvide ...

Is there a way to hide a button on this virtual keyboard after it has been clicked?

After creating a virtual keyboard using HTML and CSS, I am looking to implement JavaScript code that will hide a button after it is clicked. Here is the code I have tried so far: function hideButton() { var button = document.getElementById("simple_butto ...

Contact form repair completed - Messages successfully delivered

I am facing an issue with the contact form on my HTML landing page. Currently, when you click the 'Submit' button, it redirects to a new PHP page displaying 'Success'. Is there a way to make it so that upon clicking 'Submit' a ...

Returning null from parsing a dynamic key

I am attempting to parse a dynamic string key in this model. { "6665": [ "3", "1", "", "3", "1" ] } I have set up the model like so: struct PrivaciesResponseModel: Codable { typealias privacyID ...

There seems to be a problem with the output when trying to display the message "You said ${reply}"

In the following code snippet, vanilla.js is being used with ATOM as the text editor and running on nodejs via terminal: 'use strict'; const Readline = require('readline'); const rl = Readline.createInterface({ input:process.stdin, ...

The functionality of the slick slider seems to be malfunctioning

I've been trying to integrate the slick slider into my website, but it just won't work. I've double-checked everything multiple times, but I can't seem to find the issue. It's driving me crazy! If anyone can help me identify the pr ...

The alert box is failing to open

When I click the button, I expect an alert box to appear but nothing happens. I'm unsure whether I need to include var before the identifier in the function signature like this: function popup(var message) <!DOCTYPE html> <html lang="en-ca"& ...

Struggling to retrieve the header in Angular 6

When setting headers from an Express server written in NodeJS, I use the following code: app.use('/routes', function(req, res, next) { res.setHeader('test', 'test'); next(); ); The headers are successfully sent to th ...

Using jQuery, you can utilize the $.when() function with both a single deferred object and an

In my current jquery setup, I am working with two variables. trackFeatures - representing a single ajax request, and artistRequests - an array of ajax requests. I am looking for a way to create a condition that triggers when both trackFeatures and artist ...