Error encountered when passing arguments from code-behind to a JavaScript function

When working in the code behind:

    string func = "displaySuccessMessage("+name+");";
    ClientScript.RegisterStartupScript(this.GetType(), "success", func, true);

If in a separate JavaScript file:

   function displaySuccessMessage(user)
   {
        $("#box").dialog({
            title:"User Registration",
            html: user.toString() + " Successfully Registered", 
            modal: true,
            buttons: {
                   Ok: function () {
                    $(this).dialog("close");
                    var s = "../Pages/main.aspx";                
                    window.location = s;
                   }
        }
   });
 } // end function 

Everything works fine when passing the function string with no arguments.

However, adding an argument to the function string results in a browser error:

"Uncaught ReferenceError: john is not defined"

(Here, "john" represents the value of name)

I suspect that this issue arises because of how the function is registered, causing it to misunderstand between a variable and its value, resulting in an undefined type like john.

This leads to the question:

How can one successfully send arguments to a JavaScript function from code-behind?

Thank you in advance, eran.

For related information, check out this similar question:

similar question

Answer №1

Your writing style makes it seem as though you are passing in the variable john, not a string. This is similar to calling

showSuccessMessage(john); // how you're currently implementing it in JavaScript
showSuccessMessage('john'); // how you should be doing it

To correct this issue, consider using

string func = "showSuccessMessage('"+name+"');";

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

Opening a controller in a dialog using AngularJS with dynamically loaded templates

Experimenting with AngularJS has been a fun experience for me. I've been using a controller and a templateUrl to handle everything seamlessly :) At the moment, my layout consists of just the <div ng-view></div> directive where all content ...

Running JavaScript when the radmenu is clicked in an ASP.NET application

On my website, I am utilizing a rad menu from Telerik. The menu items are being bound to the menu in the code behind. Sometimes, the navigate URL I retrieve from the database is a JavaScript function like: js=OpenSupportWin(); Instead of a page URL. Wh ...

Exploring the Power of Two jQuery Ajax Functions in Your Script

Is it possible to provide guidance on how I can successfully execute two separate Ajax calls within a single script without encountering conflicts? A sample of the current script structure is as follows: <script type="text/javascript"> $(document).r ...

Tips for changing between two texts within a button when clicked

Seeking a solution for toggling between two different texts inside a button when making an ajax call, with only one text displayed at a time. I'm facing difficulty in targeting the spans within the button specifically. Using 'this' as conte ...

How to create a unique string array in C# without any duplicates

I'm diving into the world of C# and I'm looking to tackle a permutation challenge without repetition for arrays. Let's take a look at two string arrays as an example. string[] str1 = String[]{"E1","E2","E3"}; string[] str2 = String[]{"E1"," ...

Where can the Path be found for Json inside App Phonegap?

Having some trouble with my Phonegap App! Everything seems to be working fine when I test it in my browser. However, once I compile it into an APK and install it on my phone, it's unable to find the JSON data. I'm a beginner in programming and a ...

Methods that are static and defined within the Promise constructor

While examining the static methods of the Promise constructor, I noticed that there are two methods called resolve and reject: console.log(Object.getOwnPropertyNames(Promise)) // Array(7) [ "all", "race", "reject", "resolve", "prototype", "length", "name" ...

What is the best way to defer the instantiation of a particular controller (not a route) in your

What I'm looking for is a directive that functions like a typical ng-controller, but I need it to be invoked only after a promise has been resolved. To achieve this in HTML, it could be implemented as such: <div ng-controller="myCtrl" ctrl-promise ...

Interacting between React and Express with CKEditor 5: How to send a request

import React, { Component, useState, useEffect } from 'react'; import { CKEditor } from '@ckeditor/ckeditor5-react'; import ClassicEditor from '@ckeditor/ckeditor5-build-classic'; import axios from 'axios'; import pa ...

The functionality of .NET Math.Log10() can vary depending on the specific hardware configuration

Upon further investigation, it was discovered that when running Math.Log10(double.Epsilon) the result was -324 on machine A, but -Infinity on machine B. Initially, both machines yielded the same result of -324. Both machines initially had the same OS ( ...

Is there a way to update the state for a specific location on a map?

I have a requirement to update the quantity of a product by using setCount. let [product.quantity, setCount] = useState(product.quantity); Implementing increment and decrement functions for product.quantity const increaseQuantity = () => { setCoun ...

I'm having trouble getting onClick to function properly in CodeIgniter

While attempting to utilize onClick in the PHP page as shown below: <a href="javascript:void(0);" onClick="deleteCourse('<?php echo $row->courseId;?>');" class="delete">Delete</a> And in the JavaScript page, the function is ...

Unveiling the significance behind the utilization of the.reduce() function in conjunction with Object.assign()

After consulting the method/object definitions on MDN, I am attempting to create a simplified step-by-step explanation of how the script below (referenced from a previous post) is functioning. This will not only aid in my understanding but also help me ada ...

Unable to execute JavaScript on Node.js

I recently installed Node.js so I could run some JavaScript codes on LeetCode, but unfortunately, I encountered an issue. I then tried installing the Code Runner extension on VS Code to see if that would help, but this is the output I received: [Running] n ...

Tips for optimizing iframe loading times using the onload event

I am facing an issue with the timing of iframe loading while using a list of URLs as sources. I have created a child iframe and appended it to the DOM, then run the onload function for further processing. However, the time recorded for each iframe seems in ...

I encountered an issue while making customizations to my default next.config.js file. Despite attempting various solutions, I consistently encountered an error regarding the invalid src property

I'm currently trying to introduce some custom configurations into the next.config.js file. However, I keep encountering an error regarding an invalid src prop. Despite my attempts to troubleshoot in various ways, the error persists. // ...

Guide to sending data from an HTML page to a MVC Controller using WebApi

How can I fix the issue with my HTML button not calling the API properly? function saveclickdata() { var allData = { InvNo:document.getElementById('TbInvNo').value, GrossSale:document.getElementById('Tb ...

Tips for successfully transferring a concealed value within a form

<p>{{item.name}}</p> // This part is functioning properly and displays correctly <form #f="ngForm" (ngSubmit)="onSubmit(f.value)" novalidate> <div *ngIf="editMode"> <input name="name" type="hidden" ngModel val ...

execute a series of asynchronous functions one after another

async function cancelUserSubscriptionHandler() { const unsubscribe = await fetch("/api/stripe-sessions/cancel-subscription", { method: "PATCH", body: JSON.stringify(), headers: { "Content-Type": "appli ...

Guide on Sending a POST Request via HTTPS in Websites

I am developing a browser extension for Chrome that requires sending a post request to a server using standard HTTP. However, this is causing a mixed content error when I'm on a website that uses HTTPS, and the browser refuses to process my request. ...