Sending multiple variables to an onClick function using Javascript and AJAX

I'm currently facing a challenge in sending multiple variables as parameters to a function called redi on an onClick event. Right now, I am only able to send one variable (id) and struggling to find a way to pass multiple variables (specifically id, nome, cognome). I attempted using onclick='redi(this.id, nome, cognome)', but it appears there is an issue with the quotes since nome and cognome are strings.

$.ajax({

   url: "<URL to backend script>",
   dataType: 'jsonp',
   jsonp: 'jsoncallback',
   timeout: 5000,
   success: function(data, status){
       $.each(data, function(i,item)
       { 
         var id = item.registrationID;
         var nome = item.registrationName;
         var cognome = item.registrationSurname;
         var id_referenza = item.registrationUsername;

         document.getElementById('divPaziente').innerHTML += "<a href='"+nome+"'><button class='button button-block button-positive' id='"+id+"' onclick='redi(this.id)'>"+nome+' '+cognome+' - '+id_referenza+"</button></a>";

         window.redi = function(elem)
         {
           alert("elem: "+elem);
           localStorage.setItem("id", elem);
         }
        });
        },
        error: function()
        {
          output.text('There was an error while loading data.');
        }
    }); 

Answer №1

Consider incorporating 'data-' attributes into your code for improved organization.

<a href='"+name+"'><button class='button button-block button-positive' id='"+identifier+"' data-name="'+name+'" onclick='redirect(this.id,this.getAttribute("data-name"))'>"+name+' '+surname+' - '+reference_id+"</button></a>

Please remember to use appendChild() instead of innerHTML for better practice.

Answer №2

Sending the additional data as a single string by using special characters for escaping

loadData(this.id, \'' + firstName + '\',\'' + lastName + '\')

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

Simple Express Path Challenge

I've hit a roadblock in my JavaScript tutorial on Mozilla and could really use some assistance. Below are excerpts from 3 different files: a) In the app.js file, I am trying to locate Router handlers and then present them: //app.js //the fol ...

Asynchronous operations in Node.js with Express

Hey, I'm still pretty new to using async functions and I could really use some help understanding how to pass callbacks in async.each for each item to the next level (middleware). Here's the logic: I want to iterate through all items, and if an ...

Is it advisable to employ jQuery(this) in this specific scenario?

My PHP script generates HTML a:link divs with different $linkname and $pageid values. It also creates corresponding jQuery scripts for each link: $output = '<a class="sig_lightbox_link" id="' . $pageid . '">' . ...

Iterate over a collection of objects to find connections between the starting and ending points, and retrieve the number of occurrences

My challenge involves analyzing an array of objects containing origin and destination data, and the total volume of objects moving between locations. I am specifically looking to compare flow counts between two cities. For example, when the origin is Vanco ...

retrieving the element's height results in a value of 'undefined'

I am attempting to get the height of a specific element, but unfortunately I keep getting undefined. Here is what I have tried: var dl; $(window).load(function(){ dl = $("#dashboard_left").height(); }); $(document).ready(function(){ alert(dl); } ...

"execute loop in a strange and peculiar manner using JavaScript

Implement a loop to place markers on the map: for (i = 0; i <= 6; i++) { _coord = prj_markers[i]; alert(i); instance.set_marker(instance, provider, i, _coord, divBlock); } This code displays "0" in an alert once and executes instance.set_m ...

Triggering an event through a shared messaging service to update the content of a component

I'm looking for a simple example that will help me understand how I can change the message displayed in my component. I want to trigger a confirmation box with *ngIf and once I confirm the change, I want the original message to be replaced with a new ...

What are the top methods for interacting between Server APIs and Client-Side JavaScript?

Presently, I am utilizing setTimeout() to pause a for loop on a vast list in order to apply some styling to the page. For example, For example: How I utilize setTimeOut: I use setTimeout() to add images, text and css progress bars (Why doesn't Prog ...

What is the process for sending an image via xhttp using the POST method?

I am attempting to accomplish the following: var http = new XMLHttpRequest(); var url = "saveImage.php"; var params = $('#form').serialize(); http.open("POST", url, true); http.setRequestHeader("Content-type", "multipart/form-dat ...

What is the best way to hide a <tr> element when its child <td> elements are empty?

I am facing an issue with a dynamically generated table that may have 'n' rows. If all <td> elements within a <tr> are empty, I want to hide or delete the entire row. My challenge lies in parsing through each <td> element to ch ...

The countdown feature is failing to update despite using the SetInterval function

My goal is to develop a countdown application using Atlassian Forge that takes a date input and initiates the countdown based on the current date. For instance, if I input "After 3 days from now," I am expecting the result to continuously update every seco ...

Issue with React hook state persistence in recursive function

I implemented a recursion custom hook that utilizes a setTimeout function to provide 3 chances for an operation. Once the chances run out, the recursion should stop. However, I encountered an issue where the setTimeout function is not properly decrementin ...

Using AJAX to transform octet-stream into typed array (Float64Array)

I can't seem to figure out where I'm going wrong here. My attempt involves converting a binary stream obtained from an AJAX request into an array of doubles using JavaScript. Here is some of my code: The PHP script on my server returns an octet-s ...

Retrieve the current date and time in JSON format using moment.js for the local

Below is the code snippet I am working with: var startTime = moment("2020-09-08 16:00:00").toDate(); console.log(startTime) const data = {start: startTime} console.log(JSON.stringify(data) After running it, the result is as follows: Tue Sep 08 ...

Centering <th> elements is key for achieving a visually appealing print layout

Is there a way to center align the header and body of a table when printing it? I am using datatable. Here is how it currently looks: Check out this screenshot I have tried adding classes to the th tags in the HTML table, but they still appear aligned t ...

Using `preventDefault()` will also block any text input from being entered

Note: I am looking for a way to clear the text box using the enter key after typing some text. My apologies for any confusion caused. Update 2: The missing event parameter was causing all the issues. I feel like a failure as a programmer. I am trying to ...

What advantages does NextJS offer that set it apart from other frameworks that also provide Server Side Render solutions?

I'm diving into the world of NextJS and as I explore this topic, one burning question arises: "What is the necessity of utilizing NextJS?" From what I understand, NextJS excels in rendering pages from the server and is heavily reliant on ReactJS. Howe ...

The Ajax functionality encountered issues when used in the MVC4 webgrid

Having trouble with Ajax paging and sorting in MVC4 WebGrid Check out the code snippet below: @{ WebGrid grid = new WebGrid(rowsPerPage: Model.PageSize, canPage: true, canSort: true, ajaxUpdateContainerId: "Grid"); grid.Bind(Model.List, rowCount: Model. ...

Handling data type switching effectively for pairs in JavaScript

Imagine I have the following list: 1: Peter, 2: Mary, 3: Ken ... I am looking to create a function called switch that would return values like this: let value1 = switch("Peter") // returns 1 let value2 = switch(3) // returns "Ken" I ...

The AJAX request successfully retrieves data, but the page where it is displayed remains empty

I have come across similar questions to mine, but I have not been successful in implementing their solutions. The issue I am facing involves an AJAX call that is functioning correctly in terms of receiving a response. However, instead of processing the re ...