What could be the reason for receiving a JSON response page following an AJAX post request?

I am currently working on an ASP.NET MVC5 web application and have a controller action post method that resembles the following code snippet:

   [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Set(int id)
        {
            DbHelper dbHelper = new DbHelper();
            dbHelper.Update<News>("update news set ispublished = 1, publishdate = @PublishDate where newsid = @NewsId", new { NewsId = id, PublishDate = DateTime.Now });
            return Json(new { success = true, message = "added successfully!", redirectToUrl = Url.Action("NewsList", "Home") }, JsonRequestBehavior.AllowGet);
        }

When trying to call this method from my View using Ajax:

 $(document).on("click", ".set", function () {

    var mId = $(this).attr("data-model-id");
    $.ajax({
        url: "@Url.Action("Set","Home")",
        data: { "id": mId },
        contentType: 'application/json',
        type: 'POST',
        dataType:'json',
        success: function (response) {
            if (response.success) {
                window.location.href = response.redirectToUrl;
                dt.ajax.reload();

                $.notify(data.message, {
                    globalPosition: "top center",
                    className: "success"
                });
            }
        },
        error: function (response) {
            $.notify(response.message, {
                globalPosition: "top center",
                className: "success"
            });
        }
    });
});

However, I keep encountering the issue shown in this image.

My expected outcome is to be redirected to the home/newslist URL. Despite multiple attempts at modifying the parameters of the Ajax call, the result remains unchanged.

Answer №1

Ensure to test your ajax functionality after removing the "error" function. You may also consider trying out the following approach:

$(document).on("click", ".set", function () {

    var modelId = $(this).attr("data-model-id");
    $.ajax({
        url: "@Url.Action("Set","Home")",
        data: { "id": modelId },
        contentType: 'application/json',
        type: 'POST',
        dataType:'json',
        success: function (response) {
            if (response.success) {
                window.location.href = response.redirectToUrl;
                dt.ajax.reload();

                $.notify(data.message, {
                    globalPosition: "top center",
                    className: "success"
                });
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            $.notify(errorThrown, {
                globalPosition: "top center",
                className: "success"
            });
        }
    });
});

Verify whether the success function is being executed properly.

Answer №2

If you want to retrieve the entire HTML page as part of an ajax response, you will need to make adjustments to the Controller method.

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Set(int id)
{
       DbHelper dbHelper = new DbHelper();
       dbHelper.Update<News>("update news set ispublished = 1, publishdate = @PublishDate  where newsid = @NewsId", new { NewsId = id, PublishDate = DateTime.Now });
       //return Json(new { success = true, message = "added successfully!", redirectToUrl = Url.Action("NewsList", "Home") }, JsonRequestBehavior.AllowGet);
       return view("ViewName");
}

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

Activate inactive html button using javascript

One of the challenges I am facing is testing forms where the client specifically requested that the submit button be disabled by default. I have been exploring ways to dynamically replace the disabled="" attribute with enabled using JavaScript within a s ...

Guide on how to automatically log out a user at a designated time

I am working on a basic application with login functionality using webforms, and I want to automatically log out the user at a specific time for updates. For example, at 13:30, I need to logout the user from the website and redirect them to the login page. ...

Experiencing a 403 error when using Django with jQuery and Ajax

I am currently working on implementing ajax functionality, but I keep encountering a 403 error. My experience with jquery is still limited. Below is the code snippet that I have been using: $('#prod_search_button').click(function(){ if ...

Warning: Rendering issue detected after importing THREE.js OBJ model with [.CommandBufferContext]. The render count or primcount is currently at 0

My Google Chrome browser is flooded with countless errors: [.CommandBufferContext]RENDER WARNING: Render count or primcount is 0. These errors occur when using OBJ and MTL files exported from Blender, specifically with the OBJMTLLoader.js as the loader a ...

Is there a way to prevent the page from refreshing during the beforeunload event?

Is it possible to prevent page refresh in a webpage using the 'beforeunload' event without displaying an alert message? window.addEventListener("beforeunload", this.onUnload); onUnload = e => { e.preventDefault(); // How can ...

The Axios request for the concatenated URL is failing to execute

Encountering an issue with Axios in node js. Here's the code snippet: let callResult = await axios.get(urlData, config) The configuration object used is as follows: let config = { headers: { 'X-Token': token } ...

Every other attempt at an Ajax request seems to be successful

I'm new to using ajax and I'm having an issue with submitting a form through a post request. Strangely, the code I wrote only works every other time. The first time I submit the form, it goes through ajax successfully. However, on the second subm ...

Incorrectly modifying the _locals property while rendering a MySQL result in Express/Node.js leads to the error: "Cannot assign to read only property '_

I am currently using Handlebars to display data retrieved from a MySQL query. The route is set up as shown below: var query = "SELECT col1, col2, col3 FROM table WHERE section >= " + start + " AND section <= " + end + " ORDER BY col1 ASC"; connecti ...

Remove the watchers in ng-bind when the item is no longer visible

I am currently utilizing AngularJS with the ng-repeat directive. Each item within the repeat structure is quite large, containing numerous instances of ng-bind, and the entire list is enclosed within a scrollbar. I am looking to develop a script that can d ...

Display selected columns from a DataTable on a GridView in ASP.NET

I need to display a subset of columns from a datatable in a gridview. How can I achieve this programmatically? Here is the current code I am using: Dim dt As DataTable = New DataTable() dt = GetValues() gvContactList.DataSource = dt I specifically need ...

Could the delete button in a Chip component from Material-UI be customized with a unique style?

I'm having no issues styling the label or background color of the chip itself. However, it appears that the delete button inside the chip is an SVG icon. Is there a method to change the color of this icon? ...

Displaying a div based on the response after it is received using an if/else statement

In my form, each question is on a separate page (div), with the ability to show and hide pages. If a user receives a response from the API with a status of "accepted", they are redirected to a URL. I'm currently trying to display a div if their status ...

GraphQL .Net Conventions do not allow variables to be of a non-input type

Recently, I have been working on implementing graphql.net using conventions. The model that I am working with is defined as follows: public partial class Project { public Project() { ProjectGroup = new HashSet<ProjectGr ...

` ` Despite entering correct values, the HTML form is still displaying validation errors due to JavaScript. ``

My contact form with validations is functioning well, but I am facing an issue where old errors persist even after correcting them and submitting the form again. Below is a snippet of the document containing the JavaScript code: <form id="contactForm" ...

What is the best way to update the src of an input using an onclick event?

When I click the input, my background changes color as expected. However, the src of the input only changes on the second click. How can I make it change the source on the first click? Also, how can I change the src back to the original with a second cli ...

Session identifier recycling

A) I believe that in Asp.Net, reusing session identifiers is only allowed when operating in cookieless mode, and not when using cookies to store the session ID, am I correct? B) According to my book: ASP.NET allows the reuse of session identifiers by d ...

Issue with Bootstrap 4 nested collapse: "data-parent" attribute malfunctioning

I'm looking to implement the collapse data-parent options in a way that mimics traditional accordion behavior: all collapsible elements under a specified parent should close when a new one is opened. However, I am encountering issues with this setup. ...

"Troubleshooting the issue of jQuery failing to set data

Although it seems straightforward, I am puzzled as to why this code is not functioning properly. The selector is accurate, but for some reason the .faqContent div is not being updated with the data-height attribute. $('.faqItem .faqContent').eac ...

Comparing v-show(true/false) and replaceWith: Exploring the best practice between Vue and jQuery

Currently, I am in the process of learning vue.js and have a question regarding the best approach to implement the following scenario: https://i.sstatic.net/2YBEF.png https://i.sstatic.net/YCEHG.png The main query is whether it is acceptable in HTML to w ...

Is it possible to send a POST request to PHP without reloading the page

URGENT UPDATE - REQUESTING ASSISTANCE! ISSUE WITH POSTING DATA TO SQL SERVER WITHOUT PAGE REFRESH I have extensively searched online forums for a solution to my problem, but I keep encountering the same issue. My goal is to submit data without reloading t ...