Validating Code Retrieved from Database Using Ajax Requests

I can't figure out why my code isn't working as expected. I'm attempting to validate a code by calling a function in the controller. If the code already exists, I want to display a 'failed' message and prevent the form from being submitted. However, this functionality is not working as intended. Even when the failed error is displayed, the form continues to submit.

Here is the code for the view:

Script

$(document).ready(function () {
    $('#signupform').submit(function () {

        var code = $('#txtcode').val();
        alert(code);
        if (code.length > 0) {

            // Validate code
            $.ajax({
                type: "POST",
                url: "@(Url.Action("CheckCode", "Home"))",
                data: {
                    "code": code,
                    "type": "Data"
                },
                success: function (returndata) {
                    if (returndata.match('failed')) {
                        alert(returndata);
                        return false;
                    }
                }
            });
        }
    });
});

Form

@using (Html.BeginForm("ManipuleInfo", "Home", FormMethod.Post, new { enctype = "multipart/form-data", id = "signupform", name = "signupform" }))
{
    <div>
        <table>
            <tr>
                <td>
                    Code:
                </td>
                <td>
                    @Html.HiddenFor(m => m.Id)
                    @Html.TextBoxFor(m => m.Code, new { @id = "txtcode", @name = "txtcode", @required = "required" })
                </td>
            </tr>
            <tr>
                <td>
                    Title:
                </td>
                <td>
                    @Html.TextBoxFor(m => m.Name)
                </td>
            </tr>
            <tr>
                <td>
                    Sub-Type:
                </td>
                <td>
                    @Html.DropDownListFor(m => m.SubType, listItemsmode)
                </td>
            </tr>
            <tr>
                <td>
                    Subscriber Type:
                </td>
                <td>
                    @Html.DropDownListFor(m => m.SubscriberType, listItemstypes)
                </td>
            </tr>
            <tr>
                <td>
                    <label> Live:</label>
                </td>
                <td>
                    @Html.CheckBoxFor(m => m.Published)
                </td>
            </tr>
            <tr>
                <td></td>
                <td colspan="2">
                    <label> Press add button to start adding fields!</label>
                    <table id="Controls" style="display: none"></table>
                </td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <div style="text-align:right">
                        <input type="submit" value="Save" class="btnStyle" name="btnSaveData" />
                        <input type="button" value="Cancel" onclick="return Cancel()" class="btnStyle" />
                    </div>
                </td>
            </tr>
        </table>
    </div>
}

Controller

public ActionResult CheckCode(string type, string code)
{
    try
    {
        WCMSDataContext wcmsContext = new WCMSDataContext();

        if (type == "Data")
        {
            var Objp = from p in wcmsContext.Packages.Where(p => p.Code == code && p.Type == "Data") select p;
            if (Objp.Count() > 0)
            {
                return Json("failed");
            }
        }

        return Json("success");
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

Answer ā„–1

The validation process for the email request is handled asynchronously, which means that it does not pause the execution of the code below and allows the form to be submitted. Additionally, the return false code exists in a separate function and does not prevent the form submission.

To address this issue, there are two potential solutions:

Option 1: Change the ajax call to synchronous, define an isValid variable, assign a value to isValid upon completion of the request, and then check if isValid is false before preventing the form from submitting.

$('#signupform').submit(function () {

    var isValid = false;

    var code = $('#txtcode').val();
    alert(code);
    if (code.length > 0) {
        //validate email
        $.ajax({
            async: false,
            type: "POST",
            url: "@(Url.Action("CheckCode", "Home"))",
            data: {
                "code": code,
                "type": "Data"
            },
            success: function (returndata) {
                if (returndata.match('success')) {
                    alert(returndata);
                    isValid = true;
                }
            }
        });

        if (!isValid)
           return false;
    }
});

Option 2: Add an 'btnSubmit' id to the submit button for easier DOM manipulation. Remove the submit event from the form and attach a click event to the submit button. Prevent the default behavior, send an asynchronous request to verify validity, and upon success, submit the form if valid.

$('#btnSubmit').click(function () {
    var code = $('#txtcode').val();

    if (code.length > 0) {
        //validate email
        $.ajax({
            type: "POST",
            url: "@(Url.Action("CheckCode", "Home"))",
            data: {
                "code": code,
                "type": "Data"
            },
            success: function (returndata) {
                if (returndata.match('success')) {
                    $('#signupform').submit();
                }
            }
        });

        return false;
    }
});

This solution assumes that the validation should only occur if code.length > 0, but if validation should always take place, move the return false portion after this condition.

Note: If the validation is solely for ensuring a 'valid email,' it can be performed on the client side using JavaScript without requiring server requests. Server-side validation for validity could be necessary for checking factors like uniqueness of the email address.

Answer ā„–2

Make sure to use prevent default in order to halt the form from performing a postback. See the revised code snippet below:

 $(document).ready(function () {
        $('#signupform').submit(function (e) {
             e.preventDefault();
            var password = $('#txtpassword').val();
            alert(password);
            if (password.length > 0) {

                //validate password
                $.ajax({
                    type: "POST",
                    url: "@(Url.Action("CheckPassword", "Home"))",
                    data: {
                        "password": password,
                        "type": "Data"
                    },
                    success: function (returndata) {
                        if (returndata.match('incorrect')) {
                            alert(returndata);
                            return false;
                        }
                    }
                });
            }                    
        });
    });
</script> 

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

Developing a Multi-Stage Pop-Up with Jquery

I am interested in creating a custom multi-step modal This particular div has dynamically generated classes $('.modal-content').append('<div class="modal-body step step-' + key + '" data-step="'+key+'"></div> ...

React's componentDidMount fails to trigger for jQuery AJAX request

Here is my code snippet: import React from 'react'; import {render} from 'react-dom'; class App extends React.Component { constructor(props) { super(props); this.state = { data: '' }; ...

json success function not being triggered

I am facing an issue with executing the success function in my code while trying to post the value of an input box and retrieve the value of a checked radio button. The objective is to perform a query based on which radio button is checked. Here is the HT ...

Asynchronous jQuery AJAX calls are now obsolete and deprecated

Currently, I am utilizing jquery version 1.11.2 and attempting to perform an asynchronous ajax call for form validation purposes. Below is the code snippet: <form name="form1" id="form1" method="post" action="/payment/payment.php" onsubmit="retur ...

Using AJAX call and jquery each loop to work with JSON syntax

I made an AJAX request that fetches data from PHP. echo json_encode($json_response); The output looks like this: [{"name":"Sprouts.......}] Next, I used JQUERY to iterate through the data using the following code: $.each($.parseJSON(data), function(i, ...

retrieve the value of an HTML element once it has been modified

When I am working in a view, I encounter an issue where I need to retrieve the value of an HTML input box after it has been changed. Initially, the page loads with the following code: <input id="input_one" type="text" value = "apple" /> Upon loadin ...

Unable to invoke a function in TypeScript from a Kendo template within the Kendo TreeList component

In my TypeScript file for class A, I am encountering an issue with the Kendo TreeList code. I am trying to call a function from the Kendo template. export class A{ drillDownDataSource: any; constructor() { this.GetStatutoryIncomeGrid ...

NodeJs took an unexpected turn

Iā€™m encountering an issue with an http request to forecast.io. When I make a normal request using $.ajax, everything works fine. However, when I try using the ajax-request module, I receive the following output: SyntaxError: Unexpected token u in JSON at ...

The jQuery AJAX function executing twice upon click

I've encountered an issue while attempting to make two Ajax calls on a single page using jQuery. The first Ajax call executes successfully and generates the desired results. However, the second Ajax call is meant to be triggered by clicking a button b ...

Issue with Ajax-Enabled WCF Service (JSON) encountered during utilization with jquery .ajax()

Regrettably, the error condition is only triggered when calling .ajax(), and textStatus (the second parameter) merely displays "error". Despite thoroughly examining multiple examples and other inquiries on stackoverflow, I seem to be overlooking something ...

JavaScript For Each loops are really starting to frustrate me

My issue seems to be straightforward. I am attempting to update a list of objects called localData with another list of objects that I received after making an AJAX request (referred to as data). The process involves using two loops, however, when I atte ...

Bring to life the div that has been clicked

There are three divs labeled as "left", "active", and "right" in my setup: Whenever the left div is clicked, it animates to become active and the previously active one moves into its place. I want this same functionality to apply to the right div as well. ...

Effortless file uploading with Uploadify

I've been attempting to use Uploadify to upload PDF or TXT files, but so far it's only uploading image files. Even after trying various methods like renaming file extensions and allowing different formats, I can't seem to make it work for no ...

Updating the options in a dropdown menu does not automatically reflect in the corresponding labels when using Ajax and jQuery

In my Laravel project, I have leveraged jQuery to dynamically add multiple select boxes and labels. The values for the select boxes are fetched from the database. Using Ajax, I aim to change the label's value dynamically based on the selected options ...

Page title missing from browser tab

I don't come from a design background, so the issue I'm experiencing is quite peculiar. Below is a snippet of code from MVC4 - <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-C ...

"Anticipate the presence of expression" mistake

On my page, users can choose a registration type and input content into the tinymce textarea to associate that content with the selected registration type. However, an error "expression expected" is appearing in the code below? The console indicates that ...

Encountering a stagnant element while performing Selenium testing in the C3 framework

Currently, I am utilizing Selenium testing and have identified all div elements with an id containing a specific name (in this case, "center-"). var x = driver.FindElements(By.XPath("//div[contains(@id, 'center-')]")); When attempting to itera ...

Ways to identify the active anchor within an li element

Below is the code snippet I am currently working with: <li> <a href="<?php echo base_url()?>home/promos/call" class="promo-call active-call"></a> </li> <li> <a href="<?php echo base_url()?>home/promos/text ...

Trouble accessing onclick function

My dataSend AJAX function is not being called when I use the onclick event. I have checked in the Inspector of my browser and confirmed that the click handler is attached to it. However, when I set a breakpoint in the function using the Debugger, it never ...

Display the chosen date from the datepicker in the input field

Utilizing a JQuery DatePicker to be constantly displayed, I have assigned it to a div. Despite wanting it to display the selected date in the input box like in this example, it just isn't functioning as desired for me. Is there a way to have the selec ...