What is the best way to send a form using ajax?

I am having trouble submitting forms without a post back using AJAX. My code is not working as expected.

What could be the issue in my script?

I am new to AJAX and would appreciate some help with AJAX scripts.

Below you can find my code:

Please note: I have two submit buttons within a single view. I want to make an AJAX call for both submit actions.

My View

@model AjaxEF.Models.Customer

@using (Html.BeginForm("Index", "Main", FormMethod.Post,new { id="idForm"}))
{
    @Html.EditorForModel()
    <br />
    <input type="submit" name="save" value="Save" />
    <input type="submit" name="cancel" value="Cancel" />
}
<script>
    $("#idForm").submit(function (e) {
        e.preventDefault(); // prevent the actual submit of the form.
        var url = "~/Main/Result"; // specify the script where form input will be handled.

        $.ajax({
            type: "POST",
            url: url,
            data: $("#idForm").serialize(), // serialize the form's elements.
            success: function (data) {
                alert(data); // display response from the server script.
            }
        });


    });

</script>

My Controller

public ActionResult Index()
{
    return View();
}
[HttpPost]
public ActionResult Index(Customer obj, string save, string cancel)
{
    if (!string.IsNullOrEmpty(save))
    {
        ViewBag.Message = "Customer saved successfully!";
    }
    if (!string.IsNullOrEmpty(cancel))
    {
         ViewBag.Message = "The operation was cancelled!";
    }
    return View("Result", obj);
}
public ActionResult Result()
{
    return View();
}

Answer №1

I'm not sure why the previous response got removed, but it was absolutely accurate. The issue lies in the URL being targeted by your AJAX request - you are currently hitting the Result action, which only returns a view. To resolve this, you should be posting to the Index action instead. Luckily, since your form is already configured to post to the correct action, you can easily extract the URL for your AJAX call from the form itself:

var url = $('#idForm').attr("action");

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

Illustrative demonstration of AngularJS

One way to showcase data using AngularJS is by triggering a function with a button click. Here's an example: <!DOCTYPE html> <html ng-app> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"& ...

Steps for performing position by position sorting within an array of arrays of numbers using the Lodash library

My task involves sorting an array of strings: ['1.2.3', '1.5.2', '1.23', '1.20.31'] I am looking for a way to sort the array by splitting each string separated by dots, such as 1.2.3 into ['1','2&apo ...

Tips for inheriting and overriding controller methods in AngularJS with Java as the base language:

I have a simple controller and I want to create a new controller that is very similar to it, but without copying too much code. angular.module('test').controller('parentController', parentController); parentController.$inject = [' ...

When utilizing AJAX, certain web pages may contain a querystring

Encountering an issue with ajax when using query strings. Data can be successfully sent when the page does not have any query string and Info.aspx/Save works perfectly fine. However, when I include query strings and post the same data, it results in a HTTP ...

How to Revalidate a Next.js Dynamic Route Manually Using an API Route?

In my application built with Next.js, I have a dynamic page that displays resources at the route /resource/[id]. When a user edits a resource, such as #5, I want to refresh the cached page at /resource/5. I've created an API route in my /pages direct ...

Javascript function to monitor and validate the latest entries in the database

Seeking assistance regarding Laravel usage. I am looking for a way to verify if there are newly inserted records in the database using Ajax code. Since I lack knowledge in Ajax, I need guidance on how to achieve this. Here is a snippet of my controller: ...

Despite using .on and .delegate, jQuery seems to be failing to apply to elements loaded via Ajax

I am currently working with Django and utilizing Django Endless Pagination along with Twitter style loading. However, I am facing issues with getting my jQuery code to bind to the newly injected elements. Despite trying to use .on and .delegate as recommen ...

What is the best way to extract key/value pairs from an object in javascript that have a specific suffix?

I'm dealing with an object: { a_suff:"Something", b_suff: "Value", c: "Value", d: "Value, e_suff: "Value" } I'm looking for a way to extract all the keys that end in "_suff". What would be the most efficient solution? Currently, I have this im ...

Pop-up - maintain the initial value

I'm working on a modal using Bootstrap and React. Inside the modal, there's a dropdown with an initial empty option: <select class="form-control" onChange={this.handleSelectCat}> <option disabled selected></option> < ...

Incorporate jQuery into your MVC view by including Html.BeginForm

Using Ajax, I have info boxes that are loaded by calling a function in my controller and generating the HTML dynamically. Now, I want to implement an edit functionality for these info boxes where the static text will be replaced with a form. I am familiar ...

Angular does not always interpret the value returned from a Promise.all call

One of the challenges I'm facing is related to the structure of my controller: controller.things = ['a', 'b', 'c']; controller.loading = true; controller.responses = []; controller.handlePromises = function(){ var pr ...

Creating an HTTPS server that can be accessed via my specific IP address

My attempt to create ad hoc and OpenSSL based certificates in Python Flask was inspired by a tutorial I found on this website. I also explored the method of creating root CA, trusting it, and generating certificates as outlined on this GitHub thread using ...

Tips on Avoiding Initial Click Activation

I've been working on a JavaScript function that dynamically generates an iframe with a button that, when clicked, deletes the iframe itself. Here are the functions I've written: function createIframe (iframeName, width, height) { var ifram ...

Issue with Tooltipster plugin causing jQuery function not to trigger upon clicking the link within the tooltip

Recently, I've been experimenting with a jquery plugin called Tooltipster by inserting some HTML into the tip with an href link. The problem arises when I try to add a class to the href and fire a jquery function upon clicking it. No matter how much I ...

Display an AJAX div when the image is hovered over and have it track the movement of

I am seeking assistance with my website project, which involves providing users with download links to movies. However, I am struggling to make the preview_block div(id) appear when the mouse hovers over the movie_block div(id). Additionally, I am having ...

In JavaScript, the checkboxes in all columns of a table with over 200 rows can be set, but only the checkboxes in the rows

Seeking help to implement toggle buttons for checkboxes on a page with a large table fetched from an external system. The table can have over 200 rows or more. Currently, I am facing an issue where I can only access and manipulate the visible checkboxes o ...

I encounter a black screen issue while attempting to rotate a three.js cube

How can I rotate a cube around all three axes (x, y, z) using the code snippet provided below? ` <html> <head> <title>CM20219 – Coursework 2 – WebGL</title> <meta charset="utf-8"> < ...

Display WooCommerce notifications when using the AJAX add to cart feature

Looking to enhance my WooCommerce shop by incorporating AJAX functionality for the add to cart feature, I stumbled upon this incredibly useful tutorial which worked seamlessly. However, after implementing the solution, I noticed that the WooCommerce notic ...

Attempting to move elements into an array for storage in the local storage

Is there a way to properly add elements to an array and store it in localstorage? Here's the code snippet I've been working with: const handleSelectLayouts = (layout) => { const layoutsArray = []; layoutsArray.includes(layout) ...

Creating artwork using a "graphite drawing tool" on a blank canvas

I created a script that draws a series of lines on a canvas, giving it a sketch-like appearance. However, I have encountered two issues with the script. Firstly, why is the y value appearing to be twice as much as it should be? Secondly, why is the line w ...