Guide to directing a user through an Ajax call to a particular Controller and action

Here is a custom JavaScript function that updates data when the Update button is clicked.

function UpdateData() {

    var obj = {
        "testData": $("#hdn_EditdsVal").val(),
        "feature": $("#hdn_EditdsVal").val()
    };
    $.ajax({
        url: '@(Url.Action("UpdatePlanFeatVal", "SuperAdmin"))',
        type: "POST",
        dataType: "json",
        data: JSON.stringify(obj),            
        contentType: "application/json",
        success: function (result) {
            // Want to redirect the user using ControllerName/ActionMethod
        },
        error: function (err) {

        }
    });
}

And here's my controller:

public ActionResult UpdatePlanFeatVal(string testData, string feature)
{
    var cmd = (object)null;
    testData = testData.Trim();
    string[] words = testData.Split(':');

    XDocument _xdoc = new XDocument(new XElement("Pricing"));

    foreach (string word in words)
    {
        if (!string.IsNullOrEmpty(word))
        {
            string[] wor = word.Split('_');

            _xdoc.Root.Add(
                new XElement("row",
                new XElement("FeatureId", wor[1]),
                new XElement("PlanId", wor[2]),
                new XElement("Unit", wor[3])
                ));
        }

    }
    using (StoredProcedureContext sc = new StoredProcedureContext())
    {                    
        cmd = sc.EditPricing(_xdoc);             
    }

    return View("ManageSubscriptionPlan");
}

The redirection to the view is not happening as expected. After some research, I found that I may need to handle it in JavaScript itself and call the URL using the OnSuccess option. Any tips on how to achieve this postback using JavaScript in my current situation?

Also, please note that the code has been modified before posting. I just want to ensure that the redirection occurs after the update.

Answer №1

Kindly make necessary updates to your JavaScript function for the success callback of the Ajax request.

function UpdateData() {

var testData= $("#hdn_EditdsVal").val();
var feature= $("#hdn_EditdsVal").val();
};
$.ajax({
    url: '@(Url.Action("UpdatePlanFeatVal", "SuperAdmin"))',
    type: "POST",
    dataType: "json",
    data: { testData: testData, feature: feature },       
    contentType: "application/json",
    success: function (result) {
        window.location.href = '@Url.Action("Action", "Controller")';
    },
    error: function (err) {

    }
});
}

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

Cannot trigger a click event on nginclude in AngularJS

I have a question regarding including a new page using the nginclude directive. The click event defined in the included page is not working properly. Main Application: <div ng-app=""> <input type="text" ng-model="ss"/> <div ...

What could be the source of the "Uncaught Error: write after end" error occurring in my test cases?

Below is the code I am working with: var Promise = require('bluebird'); Promise.longStackTraces(); var path = require('path'); var fs = Promise.promisifyAll(require('fs-extra')); var clone = require('nodegit').Clone ...

How can I use HTML and jQuery to send a button click event to a .py file using AJAX and cgi in web development?

I have encountered a challenge with posting data from button clicks on an HTML page to Python CGI for insertion into a PostgreSQL database. My script seems to be struggling with this task. Here is the structure of my HTML, ajax, and javascript: '&ap ...

Activate Bootstrap datetimepicker by using the enter key to automatically populate the initial date

Check out the Bootstrap datetimepicker on this page: I'm trying to make it so that when the datetimepicker is first shown, pressing the enter key will hide the widget and insert the current date into the input field. I've experimented with a few ...

Revamp your array elements with MongoDB - Substring replacement

Having some difficulty replacing a substring within various documents. Below is an example of one such document: { "images" : [ { "url" : "https://example/1234" }, { "url" : "https://example/afaef" }, { "url" : ...

What strategies can I use to optimize the code for the function provided?

This function allows for the dynamic display of select tags for location selection based on employee designation. The current code functions correctly, but I believe it can be optimized further. // Function to activate different location options based on e ...

The jQuery AJAX response consistently comes back empty

Hello, I'm currently working on creating an HTML form and I need to validate it before submitting the form action. However, when I use AJAX to respond, I keep receiving a blank message. Can anyone help me with this issue? $(function(){ $("#ajax-p ...

Tips for displaying images dynamically in HTML using AngularJS

src={{logo}} var logo = 'localhost:3000/modules/images/default.png' I'm trying to display the image path dynamically, but it's not showing up in the HTML. Do I need to use quotes for src? Can someone please assist me with this issue? ...

Encountering an issue while invoking the helper function in Vuejs

Main view: <script> import { testMethod1 } from "../helper"; export default { methods: { init(){ console.log("Res:", testMethod1()); } } } </script> Helper: import DataService from "../services/data. ...

Establish a connection to a regular socket by utilizing WebSocket technology

I am attempting to connect a client interface to a hardware device using WebSocket in a browser like Chrome. The code snippet I have been using for connection is as follows: var ws = new WebSocket("ws://127.0.0.1:13854"); ws.onopen = function() ... Howev ...

Proper Structure for Node System (BASIC)

Overview Recently, I entered the world of Node.js and built some basic back end functionality. However, I realized that everything was clustered in one file (index.js) which led me to explore tutorials on using express router middleware and adapting a mod ...

Ways to remain on the same page even after submitting a form

I've been searching for a solution to my specific issue for days, but haven't had any luck. Can anyone provide assistance? I have a form on my website that is supposed to send an email when clicked, while also converting the div from a form to a ...

What could be causing the TypeError in my pg-query result?

In the process of creating a node function to add a user to a PostgreSQL database, I am utilizing node.js, pg, and pg-query for communication between the application and the database. Prior to inserting a new record, I am attempting to verify that the ema ...

JavaScript: function that operates asynchronously

I am new to JavaScript and encountered some issues with async functions. I have a function that fetches data from MongoDB by creating a promise, but it returns a collection with an empty object. async function getRating(item, applicant) { let arr = await ...

In what ways can you toggle the visibility of table rows and data dynamically with the onchange event in HTML?

I'm dealing with an HTML code that can dynamically change table data based on user selection. Here's the snippet of my HTML code: Select an option: <select name='set' id="set" class="selectpicker" onchange='displayFields(this. ...

Merging two distinct arrays of objects in JavaScript can be achieved by utilizing various methods and

I have a challenge where I need to merge two arrays of objects in a nested way. var array1=[{ PersonalID: '11', qusetionNumber: '1', value: 'Something' }, { PersonalID: '12', qusetionNumber: '2& ...

Converting Blob to File in Electron: A step-by-step guide

Is there a way to convert a Blob into a File object in ElectronJS? I attempted the following: return new File([blob], fileName, {lastModified: new Date().getTime(), type: blob.type}); However, it appears that ElectronJs handles the File object differently ...

Loading an animated SVG sprite file in real-time

Recently, I received an SVG sprite file from our designers to use in my app. The specified convention is to load the sprite at the top of the <body> element and then render icons using a specific code snippet: <svg class="u-icon-gear-dims"> ...

Using jQuery or JavaScript to clear multiple selections in a multiselect dropdown when a button is clicked

Is there a way to clear the dropdown selections once my function saves data to local storage? You can refer to this fiddle for more details: http://jsfiddle.net/3u7Xj/139/ I already have code in place to handle other form elements: var $form = $("#formI ...

What is the best way to connect a text box to a nested object in the state of a React component?

Solving a React Debugging Dilemma In my current project, I'm developing an office add-in using a React-based starter kit and TypeScript. Unfortunately, debugging has been a challenge as I am unable to access detailed error messages from React in my s ...