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

Innovative computations that change in real-time according to the data at

The tale. My quest involves the intricate task of computing product costs based on a multitude of variables. Although my current system operates flawlessly through PHP functions, I am eager to enhance the user experience by incorporating Ajax functionalit ...

The Strapi plugin seems to be encountering an issue as the API is not reachable, leading to a

In an attempt to create a custom API in Strapi backend, I developed a plugin called "test" for testing purposes. However, when trying to access the test response in Postman, it displays a 404 error stating that it is not accessible. Let me provide you wit ...

Optimal methods for organizing various perspectives on a one-page website

I am developing an application that incorporates AngularJS and Bootstrap. The current setup involves organizing various views using ng-show, allowing for view changes based on button interactions and the enablement/disabling of ng-show values. Within a si ...

How can I apply concatMap in Angular?

Can you please guide me on how to effectively utilize concatMap with getPrices() and getDetails()? export class HistoricalPricesComponent implements OnInit, OnDestroy { private unsubscribe$ = new Subject < void > (); infoTitle ...

Mapping an object in ReactJS: The ultimate guide

When I fetch user information from an API, the data (object) that I receive looks something like this: { "id":"1111", "name":"abcd", "xyz":[ { "a":"a", "b":"b", "c":"c" ...

Use Google Maps to plan your route and find out the distance in kilometers as well as the

Feeling a bit overwhelmed with the project I'm working on, but hoping for some guidance. We're aiming to create a form where users input a starting point and an ending point, similar to the examples on Google Maps (http://code.google.com/apis/ma ...

Tips for generating a node for the activator attribute within Vuetify?

Vuetify offers the 'activator' prop in multiple components like 'v-menu' and 'v-dialog', but there is limited information on how to create a node for it to function correctly. The documentation states: Designate a custom act ...

Sending form data from React to Express involves creating a form in the React component,

Hello, I am new to React and trying to figure out how to send registration data from a form submission to my backend. I have attempted the traditional method of setting up the post method and route in the form, but it doesn't seem to be working for me ...

PHP: display text without requiring the user to scroll back to the beginning of the page

My function sends emails and includes error messages if all required fields are not completed. When everything is correct, it will display "Email sent!" if(isset($_POST['submit'])) { $name = $_POST['name']; $visitor_email = $_ ...

Encountering errors while attempting to share files in a system built with Node.js, Express,

This snippet shows my Node.js code for connecting to a database using Mongoose const mongoose = require('mongoose'); function connectDB() { // Establishing Database connection mongoose.connect(process see your Naughty's you're sure ...

Having trouble making JSON work alongside Ajax and jQuery?

In my JavaScript, I have the following code snippet... $.ajax({ type: 'POST', url: 'http://www.example.com/ajax', data: {email: val}, success: function(response) { alert(response); } }); The PHP fil ...

What could be the reason for receiving an HttpErrorResponse when making a GET request that returns byte data

When using these headers, the API returns byte data as a response. let headers = { headers: new HttpHeaders({ 'Content-Type': 'application/octet-stream', 'responseType':'arraybuffer' as 'js ...

Substitute for SendKeys() in Angular JS web pages using Selenium

Currently, I am utilizing selenium automation to streamline the processes of a third-party website. To input data into form fields, I have been employing the SendKeys() method. While this method is functional, it's time-consuming as there are numerous ...

Navigating a path and executing unique functions based on varying URLs: A guide

I am trying to send a post request to the path /users and then right away send another post request to /users/:id. However, I need the actions to be different for each of these URLs, so I cannot use the array method to apply the same middleware. The goal ...

My server keeps crashing due to an Express.js API call

I'm completely new to express.js and API calls, and I'm stuck trying to figure out why my server keeps crashing. It works fine the first time, rendering the page successfully, but then crashes with the error: TypeError: Cannot read property &apo ...

Issue with swal() not triggering in Internet Explorer 11

Looking for some assistance here, I believe I might be missing a small detail. The _layout.cshtml file includes all the necessary scripts to ensure that sweetheart works on IE: (this used to work in previous versions, but we haven't had to support I ...

Verify the text file for any data, and if it contains any, display it on the web browser using JavaScript

I have a program in C that works with a temperature sensor. It creates a file to store the temperature and indicates whether it falls within specific values. I want to display this data on a web browser and update it every 5 minutes. I'm looking for ...

Properties of the State Object in React Redux

I'm curious as to why my state todos were named todo instead of todos in the redux dev tools. Where did that name come from? There is no initial state, which makes me wonder. I'm currently following a Udemy course by Stephen Grider, but I am wor ...

Transfer data between PHP files seamlessly using Jquery

I need help passing a variable from file1.php to file2.php using jQuery. file1.php <?php $user_rank = $rank; ?> file2.php <?php $user_rank = $_GET['user_rank']; ?> AJAX function getRank() { $.ajax({ type: "GET", ...

Updating state within a loop of properties in a React ComponentDidUpdate function

I have been working on a project where I needed to update the state after the componentDidMount lifecycle method. The props that I am expecting in the child component are only available at mount, so I can only update the state after that point. The only so ...