A step-by-step guide on sending a JSON string from a Controller to the success event in

Passing the string "recentlyupgraded" from the controller to the ajax success event and checking it at the ajax success event is my current objective. Here's the code in My Controller:

[HttpPost]
[AuthorizeEnum(UserRole.Normal, UserRole.Power)]
public ActionResult BusinessUpdate(BusinessSetting business) {
    ActionResult _returns;
    if (viewModel.BusinessSettingUpdate(business)) viewModel.InitalizeBusiness();
    if (Session["recentlyUpgraded"] != null && (bool) Session["recentlyUpgraded"]) {
        _returns = Json("recentlyUpgraded",JsonRequestBehavior.AllowGet); 
    });
} else {
    _returns = PartialView("_Business", viewModel.Business);
}

return _returns;

Now I need to verify it at the ajax success event with this code:

function OnSuccess(formName) {
        $(formName).removeData("validator");
        $(formName).removeData("unobtrusiveValidation");
        $.validator.unobtrusive.parse(formName);
        alert(formName.innerHTML);//this code gives undefined
 }




 function OnComplete(request, status) {
        $("#DetailandSetting").fadeTo('slow', 1);
     //  alert(JSON.stringify(request));
//        if (request.innerhtml = "recentlyUpgraded") {
//            window.location.href = '/NMPAccount/LogOff';
//        }
    } 

Note: This is an ajax form.

Answer №1

Here is an example of how you can check if a user exists using AJAX in your form:

$.ajax({
    url: '@Url.Action("TestAction", "TestController")',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    type: 'POST',
    data: JSON.stringify(model)
})
    .done(function (data) {
        if (data == "USEREXISTS") {
            alert("User already exists");
        } else {
            alert("User does not exist");
        }
    })
    .fail(function (xhr, status) {
        alert("A JavaScript error occurred");
    });

In your controller, you can handle the AJAX request like this:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult TestAction(TestViewModel testViewModel)
{
    // This is just for demonstration purposes
    return Json("USEREXISTS", 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

I am interested in retrieving a particular item from the data() function in Firestore

snapshot.forEach(doc => { console.log("ID: "+doc.id, '=>', "Doc DATA: "+JSON.stringify(doc.data())); }); I am looking to extract just one item from doc.data(), which is an array of strings named "supportedCurrencies". Can someone guide m ...

How can I change the ActionLink in a MVC3 Grid column to an <a> tag?

Is there a way to swap out the MVC3 Grid column ActionLink with an <a> tag instead? grid.Column(format: (item) => Html.ActionLink("Delete", "Delete", new { id = item.ID }, new { @class = "delete-button" } ), style: "column-action") ...

Executing the npm run test command with the unsafe-perm flag within the lifecycle phase

My React/Redux app is working fine, but whenever I run the command below: npm run test An error occurs as shown below: 6 info lifecycle [email protected]~test: [email protected] 7 verbose lifecycle [email protected]~test: unsafe-perm in li ...

PHP failing to capture input values generated by jQuery in textboxes

Current Situation: I currently have a form consisting of two regular text boxes and two disabled text boxes. The disabled text box values are set using jQuery based on the values in the enabled text boxes. All four element values are then sent via PHP wh ...

Having trouble retrieving information from the controller using an ajax request

Attempting to fetch products from productController using category_id As shown below, these are simple ajax request codes with no complexity. However, my result always comes back as null. ROUTE Route::post('product-list', 'ProductControll ...

What is the best way to create new variables from items in a list?

I have a list of 3 lines that I need to separate into individual items efficiently. myList = [MultiLine.attributes.renderers[0], MultiLine.attributes.renderers[1], MultiLine.attributes.renderers[2]] The desired output is: line1 = MultiLine.attribute ...

Trouble fetching the concealed field data within the MVC framework

Upon executing the code provided below on an ASP.NET web form, I noticed that the value of the hidden field customerDeviceIdReferenceCode appears in the page source. <div id="customerDeviceIdReferenceCode" style="display:none;"> <inpu ...

jQuery's $.ajax method no longer supports XHR

My current code looks like this: $.ajax(options) .then(function (response) { // success }, function (response, a, b) { // fail }) .always(function (output, status, xhr) { // xhr is always null here }); In the p ...

Save the results from the 'Set Variable' task to a JSON file in Azure Data Factory

Is it possible to log the output from the 'Set Variable' activity as a JSON file in Data Factory? ...

What are some alternatives to using Switch Statements in VueJS filter component?

Recently, I developed a Vue Component that incorporates a simple filter feature using BootstrapVue. My query pertains to JavaScript Switch Statements - it is common knowledge that they may not always be the most optimal choice due to potential debugging c ...

Save the array to a data.json file

I am faced with the task of modifying a data.json file using a TS file. This particular data.json file has the following structure: [ { "id": "81a885d6-8f68-5bc0-bbbc-1c7b32e4b4e4", "title": "Need a L ...

Is there a more productive approach to creating numerous React components?

I am currently working on a page where I need to render 8 components. The only thing that differs between each component is the values that are being iterated... <Item classModifier="step" image={Step1} heading={Copy.one.heading} /> <Item ...

Unraveling the mystery of this JSON string

Here is the json string retrieved from the frontend of my application: {"ticker":"glencore","dated":"25/5/2121","resource_name""testing","latlong":"","type":"&qu ...

Interactive AJAX div click functionality

For this code to work, the user needs to first click the like button and then continue to proceed. However, I am having trouble getting the div event to function properly. The like button is located within a div called postos. When something is clicked wit ...

Top method for generating intricate HTML elements sent by the server in real-time

When a Mouse click event occurs, I want to populate a <div> with a form. I have set up the jQuery to send a request to the server and receive the form as plain text. My question is: if I use the innerHTML method to add the form to the <div>, w ...

What is the precise mechanism behind the functioning of rails respond_to feature?

Currently, I'm in the process of developing an application that requires a remote form feature. As I work on this, I've realized that I have never fully grasped how Rails' respond_to function operates. Let's consider the code snippet b ...

Utilize Vus.js 2.0 in conjunction with Laravel 5.4 to pass an object to the application and allow for its global usage

How can I efficiently load the authenticated user and access it across all my Vue components without making unnecessary AJAX requests, as I can directly fetch it from the back-end? In my Laravel home.blade.php file, I have a reference to a Vue app and att ...

Exploring Object to Retrieve Links in React

Upon receiving an API request, I am presented with the following external links: externalLinks : { website: { _links: { self: { rel: 'self', method: 'get', href: 'http://w ...

What could be improved in this AngularJS code snippet?

Currently, I am immersed in an AngularJS book and have extracted the following code snippet directly from its pages: <!DOCTYPE html> <html ng-app='myApp'> <head> <title>Your Shopping Cart</title> </head> & ...

How come the click event is being activated on the child element despite using e.target?

I am encountering an issue with a function that switches between two colors when an element is clicked. The function works correctly on the parent element, but not on the child element. Can you help me understand why? <div class="parent red"> ...