Oops! Looks like there was a glitch in the server for the application. The page you are looking for cannot be found. Error code: HTTP 404. Requested URL: /

Description: Oops! The page you are trying to access cannot be found. It may have been removed, renamed, or is currently unavailable. Please double-check the URL for any errors.

Requested URL: /UsersPage/undefined

I've got this AJAX script that is supposed to redirect the user to a specific URL:

$.ajax({
    url: '@Url.Action("UsersHome", "UsersPage")',
    type: 'POST',
    data: {
            chosenMood: chosenMood    
          },
    success: function(response) {
            // Deal with the successful response
            console.log('Success:', response);
            // Now let's move the user to the designated URL
            window.location.href = response.redirectUrl;
    },
    error: function(xhr, status, error) {
            // Handling any errors that occur
            console.error('Error:', error);
            // Optionally, display an error message to the user
            alert('An error occurred. Please try again later.');
    }
    });

And here is the controller or destination page:

public ActionResult UsersHome()    
{
    if (User.Identity.IsAuthenticated)
    {
        //Session["ChosenMood"] = chosenMood;
        var redirectUrl = Url.Action("UsersHome", "UsersPage");
        //return Json(new { redirectUrl }, JsonRequestBehavior.AllowGet);
        return View();
    } else
    {
        return RedirectToAction("../Home/Index");
    }
}

Answer №1

There seems to be a few issues with the code provided.

  1. If you are sending an ajax request to the action method in the controller and it returns a view, you will receive HTML code in the ajax response. In this case, you should send Json data with the redirect URL instead.

  2. Furthermore, after sending the redirectUrl in your json, there may be a 404 error because the success function calls window.location.href with a GET action method Url.Action("UsersHome", "UsersPage"), which could actually be a POST in your controller (assuming).

To make your code work properly, consider modifying it like this:

Controller Code

[HttpGet]
    public ActionResult UsersHome()
    {
        bool auth = true;
        var isAjax = Request.IsAjaxRequest();
        if (auth)
        {
            //Session["ChosenMood"] = chosenMood;
            var redirectUrl = Url.Action("UsersHome", "UsersPage");
            if(isAjax)
                return Json(new { redirectUrl=redirectUrl }, JsonRequestBehavior.AllowGet);

            return View();
        }
        else
        {
                return Json(new { redirectUrl= "../Home/Index" });
        }
    }

Ajax Code

 $.ajax({
url: '@Url.Action("UsersHome", "UsersPage")',
type: 'GET',
        data: {
            chosenMood: "chosenMood"
        },
success: function(response) {
        // Handle the success response
        console.log('Success:', response);
        // Redirect to the received URL
        window.location.href = response.redirectUrl;
},
error: function(xhr, status, error) {
        // Handle errors, if any
        console.error('Error:', error);
        // Optionally, you can display an error message to the user
        alert('An error occurred. Please try again later.');
}
});

NOTE Request.IsAjaxRequest() checks for ajax requests and initially returns Json. Upon window.location.href, it renders the View.

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

error: cannot parse data with Jquery, AJAx, and JSON

Can you assist me with this issue: I am currently building a search page using PHP and attempting to fetch a specific record from a MySQL table through JQuery-AJAX-JSON. However, the problem I'm facing is that I do not receive any data from process.p ...

Angular 2: The window.crypto.subtle.importKey function functions properly on 'localhost' but encounters issues on an 'ip' address

As a newcomer to Angular 2, I am working on creating a login form that encrypts and sends the user's emailid and password to the server. I have successfully implemented AES-ECB using AES-CTR from the following link: https://github.com/diafygi/webcry ...

Having trouble retrieving information from the local API in React-Native

Currently, I have a web application built using React and an API developed in Laravel. Now, I am planning to create a mobile app that will also utilize the same API. However, I'm encountering an issue where I cannot fetch data due to receiving the err ...

How does Code Sandbox, an online in-browser code editor, manage file storage within the browser?

What are the ways in which Code Sandbox and StackBlitz, as online in-browser code editors, store files within the browser? ...

Passing a value from a prop to a click event that is dynamically created within an SVG Vue.js

Currently, I am in the process of developing a map component using a JSON array and implementing a click event handler for each item. The objective is to toggle the CSS style to color the item when clicked, which is functioning as expected. However, my goa ...

React.js Form Validation issue: When using input type "number", the text field remains a single value even after attempting to delete characters with the backspace key

Experiencing difficulty in clearing the input field value, even after pressing backspace the value remains constant. One particular value persists in the input field. import * as React from "react"; import { Button, Form } from "react-boots ...

Transitioning from Jquery to vanilla JavaScript or transforming Jquery code into pseudo code

Struggling with a snippet of jQuery code here. While I have a good grasp on JavaScript, my knowledge of jQuery is somewhat limited. I am seeking assistance to analyze the following code in order to translate it into plain JavaScript or pseudo code that ca ...

What is the best way to manage errors and responses before passing them on to the subscriber when using rxjs lastValueFrom with the pipe operator and take(1

I'm seeking advice on the following code snippet: async getItemById(idParam: string): Promise<any> { return await lastValueFrom<any>(this.http.get('http://localhost:3000/api/item?id=' + idParam).pipe(take(1))) } What is the ...

Troubleshooting problem with infinite scrolling in AngularJS with Ionic framework

I recently created a webpage with an infinite scroll page load more script using Ionic AngularJS. However, I encountered an issue where the page restarts from the beginning once it reaches the bottom. Below is the HTML code snippet: <ion-content class ...

Obtaining the NodeValue from an input of type <td>

I have a HTML code snippet that I am trying to parse in order to extract the nodeValue of all elements within the table columns. <table id="custinfo"> <tr> <td><label>First Name</label></td> <td& ...

Retrieving JavaScript array data following a page reload

I am facing an issue with updating an array dynamically in my C# server-side code and then utilizing the updated data in a JQuery function on my webpage. When the page first loads, the array is filled with some default values by C#. However, when a user ma ...

What is the method for achieving the equivalent effect of "background-size: cover" on an <img>?

I am looking to ensure that an <img> has the smallest possible size without any empty spaces inside a div, while also being perfectly centered both horizontally and vertically. The image size may vary. To better illustrate, here is an example: http: ...

Import data from JSON using JavaScript

I have a collection of txt files that contain custom content. The file names are stored in a JSON array. { txtFiles: ['./file1.txt', './file2.txt', './file3.txt'] } I am looking to use the require function in JavaScript t ...

Ways to execute a function only once within setInterval

Hey there, I'm facing an issue with this... getSocketPerSecond = function () { Interval_PerSecond = setInterval(function () { $.ajax({ url: "/asset/ashx/GetSocket.ashx", type: "post", ...

What is the best way to prevent a form from being submitted and conduct validation using JavaScript?

Encountered a form that is unchangeable in appearance: <form id="mx_locator" name="mx_locator" method="post" action="search-results"> <!-- form elements --> <span><input type="image" src="/images/search.png" onclick="loader()"> ...

What strategies are typically employed to prevent falling into the callback hell trap when working with error-back asynchronous functions in Node.JS?

As a new Node user, I've been practicing pure Node scripting without relying on third-party npm packages. However, I quickly ran into the issue of my code becoming nested with callbacks inside callbacks, making it difficult to follow. This can lead to ...

Extra Pathway

Having trouble adding a second route to the /privacy page. The error "Cannot GET /privacy.html" keeps popping up. Any suggestions? This code seems to be failing to display the privacy.html content app.get('/privacy', function(req, res) { res.s ...

Unlock the secrets of accessing the router prop in VUE

I have set up a route where I am passing a prop to display different headers in my index component, but I'm struggling to access the prop properly... { path: '/store/:id', name: 'store', component: SystemStart, pr ...

Ways to receive a response using Jquery Ajax

How can I receive the response result from an ajax request when clicking a button labeled "Accept" to send to the server? Your assistance is greatly appreciated. An error message appears showing 419 POST http://localhost:8000/posts/list_post_ajax 419 (unk ...

Creating the dynamic Google Ad AJAX impact with JavaScript

My task is to develop a convenient script that can be shared with others for embedding on their websites. This script needs to dynamically display content sourced from my MySQL database. I am aware of the cross-site issues associated with AJAX, however, i ...