Will the error function of Ajax have any impact, or just the success part?

I am new to JavaScript and currently working on a view where the submit button should save data. If the textboxes are empty, there should be an error message displayed using Bootstrap alert. However, in all cases, only the success alert pops up, even when the fields are empty. Any help would be greatly appreciated.

<script src="~/Scripts/jquery-1.10.2.min.js"></script>

<script>
    $(document).ready(function ()
    {

        $("#btnSubmit").click(function () {



        var data = $("#myForm").serialize();
        var newUrl = '@Url.Action("Index","AspNetUsers")';

        $.ajax({
            type: "POST",
            url: "/AspNetUsers/Index1",
            data: data,
            success: function (response) {
                $('#your-modal').fadeTo(2000, 500).slideUp(500, function () {
                    $('#your-modal').slideUp(500);
                    window.location.href = newUrl;

                });
            },
            error: function (response) {
                $('#your-modal2').fadeTo(2000, 500).slideUp(500, function () {
                    $('#your-modal2').slideUp(500);
                });
            }
        })
        })


    })
</script>;

<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
 <style>
     
       #your-modal
    {
        text-align:center;
    }



    #your-modal2
    {
        text-align:center;
    }


        #x:hover {
            padding: 15px;
            border: 1px solid #6699ff;
            border-bottom-width: 2px;
            background-color: transparent;
        }

        .col-md-6.active:hover {
            box-shadow: 2px 2px 2px 2px rgba(4,4,4,.4) !important;
        }
    </style>
@model CMSFC.Models.AspNetUser

@{
    ViewBag.Title = " ";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

...


e  // GET: AspNetUsers/Create
    public ActionResult Index1()
    {
        return View();
    }

    // POST: AspNetUsers/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Index1([Bind(Include = "Id,Email,EmailConfirmed,PasswordHash,SecurityStamp,PhoneNumber,PhoneNumberConfirmed,TwoFactorEnabled,LockoutEndDateUtc,LockoutEnabled,AccessFailedCount,UserName")] AspNetUser aspNetUser)
    {
        if (ModelState.IsValid)
        {
            db.AspNetUsers.Add(aspNetUser);
            db.SaveChanges();
           // return Json("User Details are updated");
               return RedirectToAction("Index");
        }

        return View(aspNetUser);
    }

Answer №1

Don't count on the JS error callback being triggered unless your Asp script returns an HTTP error.

Many modern web frameworks offer tools for client-side validation, but it's always best to have your own backup plan:

$('input').each(function(k, v) {
  var v_val = $(v).val()
  if (v_val == null || v_val == "") {
    alert("Please fill in the required field: " + $(v).attr("name"))
  }
});

Consider implementing something similar...

Answer №2


   if (ModelState.IsValid)
        {
            var errorMessage = string.Join(" | ", ModelState.Values
                .SelectMany(value => value.Errors)
                .Select(error => error.ErrorMessage));
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest, errorMessage);
        }

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

Exporting Data from Angular's ui-grid to Excel

I am currently facing a scenario where I receive significant response data from a REST service to the Angular UI-Grid. Rather than rendering all the data simultaneously, I would like to display it in batches, while still having the option to export all t ...

Is it possible to retrieve a physical address using PHP or Javascript?

Is it possible to retrieve the physical address (Mac Address) using php or javascript? I need to be able to distinguish each system on my website as either being on the same network or different. Thank you ...

Error in Spring when updating with PATCH API in React JS due to missing request body

Spring exhibition - Error Resolved: Required request body is missing for updating delivery status Console error - Error: Request failed with status code 400 class UpdateOrder extends Component { state = { deliveryStatus:"" } handleCha ...

The AJAX call in MVC 6 is receiving a 502 HTTP Error code

Recently, I've been experimenting with MVC6 controllers and action methods. One thing that caught my attention is the change in behavior when returning JSON results - there seems to be no JsonRequestBehaviour anymore. While Ajax Posts are functioning ...

displaying a post-end issue on the express server

Currently, I am working on a school project that requires the development of a client-server application. The specific task is to create a webshop that can load products using AJAX. To achieve this, I am utilizing jquery and the $.load() method. Within my ...

if considering an integer value of 0 as equivalent to null

I am struggling with using axios to send data to an API in react. Despite the server successfully receiving the values, my code is not entering the if block as expected. Interestingly, when I make the same request from a rest client, it works perfectly. He ...

Error in Webpack: JSX elements that are adjacent must be enclosed within a wrapper tag

After adding a new component and integrating it into my Main component, I encountered an error when running webpack. The error message displayed was: "Adjacent JSX elements must be wrapped in an enclosing tag" Below is the snippet of code where the iss ...

What is the process for NPM to execute a command that is not located in the path directory?

When I try to run the ava command from my project directory that contains AVA tests, I encounter an issue because it is not in my path. In my project, the npm test command is configured as ava tests/*.js --verbose, and mysteriously manages to execute the ...

Is there a way to set the canvas size to match the exact window size in pixels without being affected by the browser's zoom factor?

I'm currently developing a website called sphere.mars2540.com. Is there a way in JavaScript or CSS to maintain a fixed canvas size regardless of the zoom level of the page, ensuring it always aligns with the actual pixels on the screen (even with 4k ...

The setInterval() function appears to be malfunctioning

My code dictates that the counter should stop once it reaches 60%, but instead, it continues counting beyond that point indefinitely. How can I rectify this issue and make sure it halts at 60%? var i = 0; function counter(tag_name, precent, varname) { ...

Compel the browser to initiate a reflow by adjusting the CSS

I am currently in the process of building a responsive image slider without relying on jQuery, using CSS3 transitions. The setup is quite simple: there's a viewport with a UL inside, containing relatively positioned LIs that are left floated. Howeve ...

When using React, draggable components with input fields may lose their ability to receive focus when clicking on the input field

<Draggable axis="y" grid={[135,135]} onStop={this.handleStop} defaultPosition={{x: this.props.task.positionX, y: this.props.task.positionY,}}> <div id="edit-task-component"> <form onSubmit={this.handleSubmit} id=" ...

I am curious to know how I can utilize Node.js to sum up values from a specific column within a CSV file

I recently started working with node.js and I'm currently working on a side project that I'm having some trouble with. My goal is to extract values from a specific column in an unzipped csv file and then add them up using node.js. Below is my co ...

Refreshing specific iframes without having to reload the entire webpage using jQuery

As the page loads initially, a hidden iframe and other visible ones are present. When a button is clicked, one of the visible iframes needs to be hidden while another becomes visible (with its src attribute set accordingly). The goal is to achieve this wit ...

To restore the position of the chosen object in Three.js after clicking reset

I am facing an issue with resetting the position of my latest Object in three.js. Initially, my code consists of the following: function onDocumentMouseDown( event ) { event.preventDefault(); var vector = new THREE.Vector3( mouse ...

Updating the Animation for Datepicker Closure

While using the date picker, I want it to match the width of the input text box. When closing the date picker, I prefer a smooth and single motion. However, after selecting a from and to date, the datepicker no longer closes smoothly. I have attempted sol ...

What is the best way to identify a specific AdWords account while utilizing campaignSelector within AdWords scripts?

I have been working on a script that aims to achieve the following tasks: Go through all the accounts in an MCC and pick out the ones with 'SEM' in their name. Go through the campaigns in a selected account and choose those that meet specific c ...

Booking.com's embedded content is experiencing display issues

My current project involves adding a booking.com embedded widget. Initially, when accessing the main page, everything works perfectly - the map and booking widget are visible for ordering. However, if you switch views without leaving the page or closing th ...

Tips for parsing a JSON file within my node.js application?

I am working on a node.js service that involves validating JSON data against a schema defined in jsonSchema. Below is the code snippet for my service: app.post('/*', function (req, res) { var isvalid = require('isvalid'); ...

What is the best way to eliminate an object from an array of objects depending on a certain condition?

I have an array of objects structured like so: data = [ { "name":"abc", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fa9b9899ba9d979b9396d4999597">[email protected]&l ...