Using MVC to create dynamic JavaScript functions that call actions

Having trouble with dynamic JavaScript onchange event not firing in my application. Here's the code snippet from my action result:

public ActionResult About()
        {
            ViewBag.Script = "<input type='text' name='myName' onchange='nameChange(this)' /><br/>" +
                "<script type='text/javascript'>function nameChange(d){" +
                "$('[name=myEmail]').val('');" +
                "$.ajax({type: 'POST', url: '/Home/Search', data: '{name:d}', " +
                "contentType: 'application/json; charset=utf-8', dataType: 'html'," +
                "success: function(data) { $('[name=myEmail]').val(data.toString());            }        });" +
                "}</script>"
                + "<input type='text' name='myEmail' />";
            ViewBag.Message = "Your application description page.";

            return View();
        }

This is how my controller looks like:

public ContentResult Search(string name)
        {
            return Content("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e9818c858586a98e84888085c78a8684">[email protected]</a>");
        }

However, I'm facing an issue where the action URL is not being recognized. Can someone provide assistance with this problem?

Here's a part of the cshtml file:

@if (ViewBag.Script != null)
{

    @Html.Raw(ViewBag.Script)

}

Answer №1

By specifying

contentType: 'application/json; charset=utf-8'
, you are indicating that the data you will send with your $.ajax request is in JSON format. However, the current data being sent is not in JSON format. To rectify this, you should create a JSON object by changing the data parameter of $.ajax to:

data: JSON.stringify({name:d})

Additionally, since you have specified a POST request in your $.ajax call, the Controller Action in your code should be decorated with a [HttpPost] attribute like so:-

[HttpPost]
public ContentResult Search(string name)
{
    return Content("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88e0ede4e4e7c8efe5e9e1e4a6ebe7e5">[email protected]</a>");
}

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

Unleash the power of jQuery to leverage two different input methods

Here is the code I'm working with: $('input[type="text"]').each(function(indx){ Right now, this code targets input elements with type "text". But how can I modify it to target both inputs with type "text" and "password"? Any suggestions o ...

Sketch on canvas using vue framework

I am trying to modify a selection tool using rectangles that was created with JS and HTML in Vue.js. Here is the original version: https://codepen.io/sebastiancz/pen/mdJVJRw initDraw(document.getElementById('canvas')); function initDraw(canvas) ...

Development versions of npm libraries

Lately, I came across a library called react-3d-components that offers some d3 react components with basic charts. It's an impressive collection of components. However, when trying to access the source code due to incomplete documentation, I found my ...

Invoking vscode Extension to retrieve data from webview

One task I'm currently working on involves returning a list from the extension to be displayed in the input box of my webview page. The idea is for a JavaScript event within the webview to trigger the extension, receive the list object, and then rend ...

Using React JS to iterate over an array and generate a new div for every 3 items

It's a bit challenging for me to articulate my goal effectively. I have a JSON payload that looks like this: { "user": { "id": 4, "username": "3nematix2", "profile_pic": &qu ...

Create a custom Angular directive that allows you to replace tags while inserting the template

I have created a custom directive that can take templates based on the attribute provided. Check out the Plnkr example JS var app = angular.module('app', []); app.directive('sample', function($compile){ var template1 = '<d ...

Rendering based on conditions with a pair of values

I am trying to render my component only if the id is equal to either 15 or 12. My current approach is not working as expected, it only renders the component when I check for one id at a time, but I need to check for both. {query_estate_id === 15 || q ...

Adding data from one object to another in Javascript results in duplicated entries

Despite my efforts to find a solution for my issue, I couldn't locate a relevant topic. Being new to Javascript, I suspect my lack of understanding is hindering me from resolving the problem. After days of trying, I'm still unable to grasp it. An ...

Elevate the index of the name attribute for an input field within a dynamically generated form

In my scenario, I have created a form that includes indexed input fields for username and level: <form> <table> <tr class="trToClone"> <td> <label>Username:</label> <input type="text" name="usernam ...

A guide to incorporating external CSS files in Angular 5 components using styleUrls

I have a unique setup where my Angular 5 application resides in a subdirectory within another parent application. The parent application consists of JSP and other AngularJS applications among other things. My goal is to include a CSS file from the parent ...

Alternatives to using $.getJSON()

When utilizing jQuery within the React/Redux environment, what alternative library is typically used for handling straightforward REST calls instead of $.getJSON or $.postJSON? Is there a widely-used option that functions similarly to node's http mod ...

What is the proper method for running a script using the Selenium JavascriptExecutor?

On my test.html page, I've included the following code snippet: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> </head> <body> ...

Trigger the ontextchanged() event for an asp:TextBox using Javascript

I have a specific asp:TextBox that is structured in the following way: <asp:TextBox runat="server" AutoPostBack="True" ID="txtG1" ontextchanged="txtG1_TextChanged" onmouseout="javascript:RefreshIt(this)"/> In addition to this, there is a Javascript ...

Whenever I attempt to use .ajax to post to an MVC 4 controller, the ViewModel is consistently null

My jQuery/HTML: @using(Html.BeginForm("Create", "Home", FormMethod.Post)) { <input name="ImageName" id="ImageName" type="hidden" /> <input name="XPos" id="XPos" type="hidden" /> <input name="YPos" id="YPos" type="hidden" /> ...

Having trouble accessing the Ajax "data" parameter in Twisted

An ajax request is made using the "POST" method with these parameters: function sendDataToServer(portNumber){ console.log(portNumber) $.ajax({url: "action", dataType : 'html', type: "POST", data: portN ...

Encountering an issue while trying to create a user in Firebase

I am currently following a tutorial on Vue.js from Savvy Apps, which utilizes Firebase with Firestore. As the tutorial mentions that Firestore is still in Beta, I anticipate potential changes - and it seems like that might be happening in this case. While ...

When the if statement fails to halt the code from running

After diving into the world of coding just one or two weeks ago, I decided to create a feature where users can press a key to start playing. No matter what I try, I always end up with the same outcome. Here's my approach: I have an if statement that ...

A beginner's guide to integrating ng-class into a directive template using AngularJS

I have been attempting to achieve something similar to the following: template: "<div ng-if=\"successData\" ng-class=\"{ 'bounceInDown': successData == true,bounceInDown: successData == false}\" style=\"border-radius ...

Displaying a PHP variable on the console through the power of jQuery and AJAX

I'm attempting to display the value of a PHP variable in the browser's console using jQuery and AJAX. I believe that the $.ajax function is the key to achieving this. However, I am unsure about what to assign to the data parameter and what should ...

The data in Next.js getStaticProps does not update or refresh as expected

As I recently transitioned to working with Next.js, I have encountered several challenges. One issue that arose was related to the use of useEffect in React compared to its behavior in Next.js. In my index file, I have implemented the following code: impo ...