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

When pickle dumps result in producing nonsensical output

Hey there! I've run into a strange issue with my JSON Encoder. When using pickle.dumps(), the output is appearing as: "cdecimal Decimal p0 (S'2097369' p1 tp2 Rp3 .", Instead, it should display: 2097369 This is the code snippet causing the ...

What other methods are available to verify null and assign a value?

Is there a more efficient approach for accomplishing this task? theTitle = responsesToUse[i]["Title"]; if(theTitle == null) theTitle = ""; ...

What is the correct RegEx pattern I should use to properly match the provided test case without including the ending period?

Regular Expression: /@([\S]*?(?=\s)(?!\. ))/g Given String: 'this string has @var.thing.me two strings to be @var. replaced'.replace(/@([\S]*?(?=\s)(?!\. ))/g,function(){return '7';}) Expected Result: ...

What is the process for updating a particular div element?

I am currently developing a webpage that allows users to select an item, and the relevant information will be displayed. On this page, I have incorporated two buttons: btnBuy0 and btnBuy1. The functionality I am aiming for is that when BtnBuy0 is clicked ...

How can I pass props from a page to components in Next.js using getServerSideProps?

Struggling to fetch the coingecko-api for accessing live bitcoin prices. Trying to pass return props of getServerSideProps to my <CalculatorBuy /> component within the <Main /> component. Facing issues when importing async function in calcula ...

Invoke a component and initiate a click event from within the App.vue component

Within my template, there is a click event: <span v-on:click="showGalery()"> This event is linked to the following method: export default { name: 'osaka', data: function () { return { galery: false, } }, methods: { ...

Using a javascript variable in php within the Laravel framework

I am trying to retrieve an id from a button for use in my ajax request. Below is the code snippet for the button: <form> <div class="form-group"> <button class="btn btn-primary" name="deletecar" id="{{$car->id}}">Delet ...

Transferring values with jQuery

I attempted to customize the appearance of the select dropdown options, but unfortunately, the value of the options is not being transferred to the new jQuery-created class. Due to this issue, I am unable to achieve the desired outcome. The expected behavi ...

Generate a flexible JSON array in VB.NET

Looking to generate a flexible array that can be converted into a JSON array for visualization with Morris charts. The usual approach in VB.NET is as follows: Dim xArray(2) xArray(0) = New With {Key .TradingDay = "Day1", .Seller1 = 1500, .Seller2 = 160 ...

Tips on incorporating jQuery cross-domain functionality

Attempting to retrieve and display the firstName data from this URL: http://www.w3schools.com/jquery/demo_ajax_json.js, as part of a test for another project. Encountered the error message: Origin null is not allowed by Access-Control-Allow-Origin, prompt ...

Infinite scrolling with Jquery: Loading dynamic content seamlessly from external websites

Hey there! I recently started using this cool jQuery plugin called jquery-endless-scroll. Here's a snippet of my code: $(function() { $('#list').endlessScroll({ pagesToKeep: 10, fireOnce: false, insertBefore: "#list div:first ...

Moving a window in Pyqt5 using QtWebChannel

My goal is to enable the mousePressEvent and mouseMoveEvent events in order to move my app window using QtWebChannel. To achieve this, I am utilizing self.setWindowFlags(QtCore.Qt.FramelessWindowHint) to eliminate the default window flag and create a cust ...

Removing the element generated by Angular from the DOM

I've hit a roadblock with this issue. Here is the delete function in my mainController. $scope.delete = function($posts) { $http.delete('/api/posts/' + $posts._id) .success(function(data) { // remove element from DOM ...

The EJS is throwing an error because it cannot define the property "round" on an undefined object

I'm currently delving into the realm of Node.js, using the "Secrets of Ninja" book as my guide. I've come across an EJS program in the book that I copied verbatim to run, but I encountered an error despite not making any modifications to the code ...

How do I retrieve the id of an event using a class descriptor within a JQuery Dialog constructor in Javascript?

As someone who is relatively new to JavaScript and jQuery, I must apologize in advance if my question seems basic. :) In a straightforward webpage, I am utilizing JQuery UI's Tabs and attempting to implement a double-click feature on the Tab names th ...

Passport.socket.io cannot resolve the issue of a missing session

The Issue I am facing a problem with the failed connection to socket.io: No session found using passport.socketio.js and I am unable to identify the root cause. Despite checking similar posts, the configuration seems fine to me. However, it appears that ...

Tips for mentioning 'subdocument' during transformations using jq

Currently, I am attempting to transform an OpenAPI specification file using jq. My goal is to identify a specific pattern: "status": { "allOf": [ { "$ref": "#/components/schemas/Status" }, { ...

Is it possible to return a promise after utilizing .then() in AngularJS?

As someone who is still getting the hang of Angular and promises, I want to make sure I'm on the right track. Right now, my data layer service uses Restangular to fetch data and returns a promise. Here's how it looks... dataStore.getUsers = fun ...

An error occurs even before any Components are rendered, with a TypeError stating that the property 'type' cannot be read because it is undefined

I'm facing an issue with my Redux App where the first component (App.js) is not rendering due to continuous errors. The reducer mentioned below is being triggered at some point without any action, causing the compiler to interpret action as null and f ...

How can I incorporate the "onClick()" function within an ajax call, while still utilizing the data returned in the success message?

After successfully making an Ajax call, I would like to implement an on-click function while still utilizing the original data retrieved. $.ajax({ URL: ......, type: 'GET', success: function (res) { var Ob ...