A guide on implementing AJAX redirection in MVC

I currently have a button that, when clicked, takes input values and redirects to another page in JavaScript using the following code

window.location = "Action Param1=value1&Param2=Value2"
. However, I am looking to avoid using query strings for this method. I have decided to explore using ajax instead:

   ` $.ajax({
            type: "POST",
            url: "/MyController/MyAction",
            data: '{Param1:"value1",Param2:"value2"}',
            contentType: "application/json,charset=utf-8",
            dataType: "json",
            success: function () {
            }
        });`

Although this successfully calls the controller, it does not return anything. If anyone can provide a working solution or point out any mistakes I may have made, I would greatly appreciate it.

Answer №1

If you only want to redirect to the page, using JavaScript is the best option:

return JavaScript("window.location = 'http:yourlink'");

However, if you also need to pass data, you can do the following:

function redirectToPage() {
        var date = new Date(); 
        var link = '@Url.Action("ActionMethod", "Home")';  
        var args = {
            param1: date.toISOString(),  
            param2: date.toISOString(),
            param3: 'yourdata'
        }; 

        $.ajax({
            type: "GET",
            url: link, 
            data: args, 
            dataType: "json",
            success: function (data) {

                window.location.href = data.redirecturl; 

            },
            error: function (httpRequest, textStatus, errorThrown) {   
                alert("Error: " + textStatus + " " + errorThrown + " " + httpRequest);
            }
        });

}

In your controller:

[HttpGet]
public ActionResult ActionMethod(DateTime param1, DateTime param2, string param3)
{
    return Json(new { redirecturl = "http:yourlink" }, JsonRequestBehavior.AllowGet);

}

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

Looking for assistance with the AJAX flow

I stumbled upon this diagram and I have some questions about it. Can you explain what the Raise - > DOM Event does? Why is a callback function created after creating an XMLHTTPRequest? What is the purpose of registering a callback in the process? How ...

Utilizing data from an external JavaScript file in an Express application

I am currently developing an application using Node.js Express, where I need to pass some data from Express and utilize it in an external JavaScript file. Below is my app.js: const express=require('express'); const path=require('path&apos ...

The migration-mongo module is not being recognized as a standard CommonJS module

I have integrated a nodejs server component into my project, which includes the usage of migrate-mongo. In my package.json file, the type specified is module. However, when attempting to run the migration process, I encounter the following error: > migr ...

Retrieving User Activity Reports for a specified set of users within G Suite

I am currently attempting to utilize the Admin SDK Reports Service to retrieve the latest login time and other data for a specific set of 20 users. Due to the large size of the domain, it is not practical to fetch data for the entire domain and then filter ...

Alter attribute with an impact

I am looking for a solution to switch the image source using attr, while also incorporating a fade effect in the process. I have attempted to implement one of the suggestions from another post, but it is not producing the desired outcome. Current Appearan ...

Exponential calculator in Javascript

I'm working on a basic calculator project using html5, css3 and javascript. However, I've run into an issue with the exponent button not functioning properly. Here's my code snippet: <html> <head> <meta charset = "utf-8" ...

Utilize VUE NPM to add imported packages to all remaining files

I am using a Vue 3 npm app and I have installed the jQuery package to use it. Currently, in order to use jQuery, I need to import it like this: import $ from "jquery"; Although this method works, I find it cumbersome as I have to include this im ...

Using JSON object as an argument in React functional component

Currently, I'm trying to assign a JSON object to a const variable. I've been successful with using vars in the past, like so: {this.props.user.map(function(user){... However, when it comes to stateless consts, I'm encountering some confusi ...

Encountering issues while trying to install Java using NPM

Encountering errors when attempting to run the following command to install java dependencies for NPM. NPM install -g java In need of assistance to fix this error. C:\WINDOWS\system32>npm i -g java [email protected] install C:\D ...

Updating a component from a different source

As a newcomer to React, I'm curious about the ability to update one component's content based on events from another component. I have two React components set up. The first component loads data when the page initializes, while the second compon ...

"Dynamically populate dropdown options based on the selection made in another dropdown menu

On a JSP page, I have two dropdown fields and a type4 connection with Oracle 10g. I want the second dropdown to be automatically filled based on the selection from the first dropdown by fetching data from the database. This should happen without refreshing ...

Prioritize loading the JS function before initiating PHP validation

My current challenge involves calling a JavaScript function from PHP upon form submission. The error message I am encountering indicates that the function is not defined. This issue arises because PHP is loaded before JavaScript, resulting in the function ...

JavaScript's Math.round function does not always produce accurate results

After adding the specified line within the function, the code seems to encounter issues. parseLocalFloatCnt: num = Math.round(num*1.2); Is there a solution available for this problem? Your help is much appreciated. <!DOCTYPE html> <html> < ...

Python web server responding to AJAX HTTP requests

As a newcomer to integrating AJAX HTTP requests with Python webserver responses, I find myself struggling to understand how it all works. For instance, my webpage is located on a different IP address, such as 192.168.1.1, and I need to retrieve data from ...

Is there a way to transfer JavaScript data to PHP?

<div> <p>This is a sample HTML code with JavaScript for tallying radio button values and passing them to PHP via email.</p> </div> If you need help converting JavaScript data to PHP and sending it via email, there are v ...

A collection of functions embedded within a JSON data structure

I am working with a website that provides data in a JSON-like format similar to the following: { "name":"tom jones", "no": 123, "storedproc": function(){ callbuyer(0123); } } Currently, I am using $. ...

identifying which specific button was clicked using JavaScript/jQuery

All of the buttons on my page are identical - same title, same value, everything is the same. Is there a way for me to identify which specific button was clicked? ...

Customize Meta tags in Next.js 13.4

I am facing an issue with overriding the meta tag in my RootLayout.js file. Whenever I try to add a new viewport meta tag, it ends up duplicating the existing one. Can anyone help me find a solution to this problem? RootLayout.js <html lang="en&q ...

What is the best way to show personalized messages to users using modal windows?

Encountering bugs while trying to implement user messages in modals. function displayMessage(title, description) { var myModalErrorMessage; $("#customErrorMessageTitle").text(title) $("#customErrorMessageDescription").html(description) myModalEr ...

Tricks for displaying a dynamic object tooltip in Three.js

Can anyone help me figure out how to create a HUD hint effect for a moving object? I envision something like this: An asteroid is floating through space, and when I click on it, a hint box with information pops up. I've been playing around with thi ...