Using jQuery AJAX for JavaScript redirection

I have been working on a JQuery AJAX response, and need help redirecting to another view. Here is the code snippet:

      $.ajax({
            url: "/Home/PersistSelections",
            type: 'post',
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            data: JSON.stringify(selectedItems),


            done: function (response) {
                window.location.href = "Home/GoToBooking";
            }
        })

However, the redirection in the 'done' section doesn't seem to be functioning as expected. I have tried using 'success' with no luck. I am not sure about the parameter that should be passed along with the response.

Additionally, I came across this code snippet:

return JavaScript("window.location = 'http://www.google.co.uk'");'

In my controllers, I have JavascriptResult resolving, but when attempting to use return Javascript, I encounter issues resolving the references. My project is based on ASP.NET Core 2.2.

Answer №1

Consider swapping out -

    done: function (result) {
        window.location.href = "Home/GoToBooking";
    }

For -

        success: function (result) {
            window.location.href = "/Home/GoToBooking";
        }

Answer №2

When working in the controller, opt for IActionResult over JavascriptResult

For JavaScript operations, follow this syntax:

$.ajax({
url: '//',
type: 'POST',
async: false,
data: { Your information },
success: function (data) {
    window.location.href = "/Home/Index";
 }
});

Answer №3

First, make sure that the return data type is json by setting dataType:"json" in your ajax call.

Next, utilize the done method as shown below:

$.ajax({
        url: "/Home/PersistSelections",
        /....
     })
         .done(function (response) {
            window.location.href = "/Home/GoToBooking";
     })

For more information, refer to: jQuery.ajax handling continue responses: "success:" vs ".done"?

Ensure that the href points to /Home/GoToBooking.

Here is a sample code snippet for reference:

1.View:

<button onclick="test()">click</button>

@section Scripts
{
<script>
    function test() {
        var selectedItems = { Id: 1, Namea: "aaa" };
         $.ajax({
            url: "/Home/PersistSelections",
            type: 'post',
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            data: JSON.stringify(selectedItems)
         })
             .done(function (response) {
                window.location.href = "/Home/GoToBooking";
         })
    }
</script>
}

2.Controller:

[HttpPost]
public JsonResult PersistSelections([FromBody]Test test)
{
    return new JsonResult(test);
}

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

Is there a way to manipulate row colors in jQuery based on specific conditions?

<tr class="acti">//class <script type="text/javascript"> var status = $(this).parent().parent().children(".activity-status").attr("data-value");//Modifying colour of the upper class based on jQuery value retrieved I am implementing a for e ...

PHP Ajax Code Error

<!DOCTYPE html> // index.php file <html> <head> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <!-- ...

The ng-model remains empty even after the $parent has been defined

I've encountered an issue where assigning ng-model to a text area and an input does not update the models. It is mentioned that this could be due to using ng-if causing a different scope, and I should use $parent, but even that solution is not working ...

Inquiry about CSS Media Queries

I am facing an issue with CSS media queries... For my HTML page, I have separate files for desktop and iPad styles - desktop.css and ipad.css. In desktop.css, I have used @import url("ipad.css"); and added a @media not only screen and (device-width:768px) ...

Upon hitting submit, the form remains unresponsive

I have been developing a permissions system for my NodeJS project (Using the SailsJS MVC) and encountered an issue. After resolving my initial error as detailed here, I am now facing a problem where the form is unresponsive. It neither shows an error in th ...

Gaining entry to a JavaScript prototype method

I'm currently working on a prototype function called event. Prototype Func("input_element_id").event("keyup",function(){ alert("Works on keyup in an Input!"); } Func.prototype= { keyup: function(func){ //adding event listener and c ...

What is the reason behind Vue.js duplicating its v-model data when the v-model is used within a computed property?

Consider the code snippet below: JavaScript const App = { template: '#app-template', data: () => ({ selected: [], items: Array.from({length: 50}, (x, i) => i+1).map(i => ({ id: i , name: `Item ${i}`, subtitl ...

Passing form data to a different route using express

I need to send the data from this form, located on the index.ejs page, to another page "/rentingForm" for rendering at the "rentingForm" page. Here is the snippet of code from my app.js file: app.use(bodyParser.urlencoded({ extended: true })); app.use( bo ...

The React Bit Dev module is showing a 404 error

Attempting to incorporate the semantic-ui-react table reusable component from the Bit.dev community into my application. The link I am using is: To add this component to your application, use: npm i @bit/semantic-org.semantic-ui-react.table However, when ...

Ways to include a notification if the information cannot be retrieved from the backend within 50 seconds (AngularJS)

Hello everyone, I have a question regarding setting a message if the server does not respond within 50 seconds. I am using an AngularJS factory to send requests to the server. $http.post("https://example.com/_ah/api/tweeting/v1/xxx?average_cycle=1&d ...

The AngularJS factory does not hold on to its value

I have developed a basic factory to store a value from my authService: app.factory("subfactory", function() { var subValue = {}; return { set: set, get: get }; functi ...

Undefined data is frequently encountered when working with Node.js, Express, and Mongoose

Having a beginner's issue: I'm attempting to use the "cover" property to delete a file associated with that collection, but the problem is that it keeps showing up as "undefined". Has anyone else encountered this problem before? Thank you in adv ...

Using Node.js and the Jade templating engine, display the value of a passed variable

Asking such a basic question makes me feel guilty. app.get('/skumanagement/:id', function (req, res){ var options = req.params.id; // req.params.id = itemidx database.skuGetDetail(options, function (error, data){ winston.log('inf ...

Implementing Multiple Identification using JavaScript and PHP

I need to complete a simple task. Here is the code snippet: echo' <div class="col-sm-12" id="recensioni_titolo"> <form role="form" id="review-form" method="post" action="php\insert_comment.php"> ...

Changing the route variable in React Native's bottom bar tab functionality

https://i.sstatic.net/ESGur.png I am looking to create a consistent bottom tab bar that remains the same on every screen, but I want the routes of the tabs at the bottom to change dynamically. For example, in Screen1, the tab at the bottom should route to ...

Ways to adjust the border color when error helper text is displayed on a TextField

I am currently working with React Material UI's TextField element. What I aim to achieve is when the submit button is pressed, the helpertext displayed should be "Please enter the password." It should look like this: https://i.sstatic.net/Nu0ua.png ...

What is the proper way to mention JavaScript packages when including them as parameters in Angular elements within HTML?

I was looking to enhance the command to be more authoritative. <div (click)="lastCall(999)">click me</div> My attempt to utilize Number.MAX_SAFE_INTEGER resulted in an error from my computer stating that it wasn't recognized. As a result ...

What is the method for displaying data on a browser instead of downloading it when creating a link?

Clicking on this link will trigger the download of the f.txt file. Rather than downloading it, I would like the data to be displayed directly in the browser. For example, when you click this link, the data is shown directly in the browser. While I have ...

Issues with d3.js transition removal functionality not functioning as expected

Having an issue with a d3.js visualization that involves multiple small visualizations and a timeline. When the timeline changes, data points are supposed to be added or removed accordingly. Here is the code snippet responsible for updating: var channels ...

Setting a consistent theme or style for all HTML/React tags using a selector inside a specific component

Here's a simplified example of what I'm trying to do: I'm using Material UI Styles for styling my components. I want to style all the <Link> tags in my component. For instance: const useStyles = makeStyles(theme => ({ menuLink: ...