Guide on passing a variable from AJAX response to a JavaScript function when a user clicks

I need to send the value of a variable as a parameter to a javascript function when clicking on a link. The value is obtained from an AJAX response. However, I am encountering an error in the console stating that 'test' is not defined.

var test = data.fileName;

alert('Hello world ' + test); // outputs Hello world download/15__Priority____4x6__Label.JPEG
var lbDownHtml = '';
lbDownHtml += "<div><a href='" + data.functpath + "' ><span>Download Label</span></a>";
lbDownHtml += "</div>";
lbDownHtml += "<div><a id='print_Link' onclick='print_funct(test);return false;'><span>Print Label</span></a>";
lbDownHtml += "</div>";

function print_funct (test) {
    alert('Hello world '+test);
}

Is there a way for me to successfully pass the 'test' variable to my function?

Answer №1

To combine the test variable with the given string, you can follow this code snippet:

htmlOutput += '<div><a id="print_Link" onclick="printer_function(' + test + ');return false;"><span>Print Label</span></a></div>';

Answer №2

Your code treats test as a string, but it would be better to assign it to a variable like this:

lbDownHtml += "<div><a id='print_Link' onclick='print_funct(" + test + ");return false;'><span>Print Label</span></a></div>;"

By doing this, the value that test holds will be correctly passed into the function call.

EDIT: per your request, when test should be a string

lbDownHtml += "<div><a href='" + data.functpath + "' ><span>Download Label</span></a>";
lbDownHtml += "</div>";
lbDownHtml += "<div><a id='print_Link' onclick='print_funct(\"" + test + "\");return false;'><span>Print Label</span></a>";
lbDownHtml += "</div>";

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

Can access parent refs when exporting a child component with withStyles by following these steps:

For example: Child Component Code // Assume there is a styles object 's' being used in this component class Child extends Component { render() { return ( <h1 ref={(ref)=>{this.ref = ref}}>Hello</h1> ); } } export defau ...

What sets apart $document from $window.document in Angular?

After experimenting with the code on JSBin, I noticed that the first snippet successfully retrieved the canvas object, while the second one did not. JSBin: http://jsbin.com/natavejasa/1/edit?html,js,output var canvas = $window.document.getElementById(&ap ...

Ways to determine cleanliness or filthiness in an Angular 5 modal form?

I have a form within a modal and I only want to submit the form if there are any changes made to the form fields. Here is a snippet of my form: HTML <form [formGroup]="productForm" *ngIf="productForm" (ngSubmit)="submitUpdatedRecord(productForm.value) ...

Remove the Prisma self-referencing relationship (one-to-many)

I'm working with this particular prisma schema: model Directory { id String @id @default(cuid()) name String? parentDirectoryId String? userId String parentDirectory Directory? @relation("p ...

Using Grails to create remote functions with multiple parameters

Currently, I am able to send one parameter to the controller using the code snippet below in Javascript: <g:javascript> var sel = "test"; <g:remoteFunction action="newExisting" method="GET" update="updateThis" params="'sel='+s ...

Complete the modal window form

I'm currently facing an issue with populating a modal window form. To provide some context, when I click on a grid row to edit a user, I make an ajax call which fetches specific data related to that user. Here is the existing code snippet: <modal ...

The HTML grid is causing an irritating excess space on the right side of my website

After brainstorming an idea, I decided to create this website for testing purposes. However, the grid layout seems to be causing an unwanted margin on the right side of the page that is not associated with any HTML tag, disrupting the zoom functionality. ...

The onClick event cannot be triggered within a div that is generated dynamically

I am having an issue with a jquery code that dynamically generates a div. The problem I'm facing is that the onclick function for the anchor tag is not calling the required function. Below is the code snippet: $("#new").append(' <ul cla ...

Issue: Unable to assign type 'FormDataEntryValue' to type 'string'. Type 'File' cannot be assigned to type 'string'

After retrieving data from the formData, I need to pass it to a function for sending an email. Error: The error message states that 'FormDataEntryValue' is not compatible with type 'string | null'.ts(2322) definitions.ts(119, 3): The e ...

Replicating a tag and inputting the field content

Scenario: An issue arises with copying a label text and input field as one unit, instead of just the text. Solution Needed: Develop a method to copy both the text and the input field simultaneously by selecting the entire line. Challenge Encountered: Pre ...

What is the best way to create a "check all" feature in React using child components?

I have come across a few questions here that somewhat address the issue, select all managed state of controlled checkboxes but none of them provide a solution for rendering a component with a checkbox. What I want is something like this, render: funct ...

Utilizing a form on numerous occasions prior to its submission

As a newcomer to JavaScript, I am exploring the best approach for a specific task. The task involves a form with checkboxes representing different music styles and a selector for names of people. The goal is to allow users to select music styles for mult ...

What methods can I use to prevent caching of XMLHttpRequest requests without relying on jQuery?

I am currently working on a web application that refreshes a table every minute from an XML file. However, I have noticed that when I make edits to the content of the XML file, I see a "304 Not Modified" message in the script log when trying to retrieve th ...

How come the use of a timeout causes the this variable to seemingly lose its reference?

What is the reason why this: myelements.mouseenter(function() { clearTimeout(globaltimeoutvar); globaltimeoutvar = setTimeout(function() { var index = myelements.index(this); console.log(index); // -1 }, 150); }); Returns -1, while this: m ...

Updating views with AJAX after database updates without the use of jQuery via PHP

Learning MVC and Ajax has been quite an adventure for me. I decided to build a site using PHP and MySQL, where I successfully implemented a new controller method to handle ajax requests. With the help of Ajax HTTPRequest, I am now able to update my databas ...

Enter the Kannada language into the HTML text box or input field

My html form consists of about 15 - 20 input and textarea fields. As a user, how can I enter information in Kannda or any other local language? https://i.stack.imgur.com/60PVT.png ...

Despite correctly declaring jquery-ui.js and numeric.js, the jQuery datepicker and numeric plugins are not working as expected

element, it's strange that I am not receiving any error messages. However, despite this, the jquery datepicker function and numeric plugin are not working on the intended input fields they are supposed to be linked to. This particular page is a simpl ...

Prevent typing in text box when drawer is activated by pressing a button

update 1 : After removing unnecessary files, I need assistance with https://codesandbox.io/s/0pk0z5prqn I am attempting to disable a textbox. When clicking the advanced sports search button, a drawer opens where I want to display a textbox. The toggleDra ...

Error: The use of "let" as a lexically bound identifier is not permitted

Currently working with vue.js and encountering the error message "Uncaught SyntaxError: let is disallowed as a lexically bound name". When trying to troubleshoot, I'm faced with a blank screen and this error appearing in the console. I've search ...

After clicking the create button in AngularJS, the ngModel values become empty

My form has been simplified by using ngRepeat to create the input fields. The attributes for each item are defined in my controller. Below is the code for the ModalCtrl: ... $scope.form = [ { label: 'First Name', fieldType: 't ...