Hammad Nasir
Hammad Nasir

Reputation: 145

Validating Existing Code from Database in Ajax Call

I am not getting why my code is not working. I am trying to validate a code by calling a function in controller. if this code already exists i simply sent 'failed' text and then i want the form to stop its submission. but this does not work. even i get failed error my forms does not stopping itself by getting submitted.

here is the code for view

Script

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

        var code = $('#txtcode').val();
        alert(code);
        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('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;
    }
}

Upvotes: 0

Views: 1040

Answers (2)

Viktor Bahtev
Viktor Bahtev

Reputation: 4908

The request for validation the email is asynchronous (read about common problems here) so it doesn't stop execution of the code below and the form is submitted. Also return false code is in other function and won't stop form submitting.

Here is what can be done:

First option: Make the ajax call synchronous. Define isValid variable. When the request is completed assign value to isValid. Then check if isValid is false and stop 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;
    }
});

Second option: Add 'btnSubmit' id to submit btn for easier DOM manipulation. Remove submit event from the form. Attach click event for submit button. Prevent it's default behavior. Check send asynchronous request to check validity. In success callback check if data is valid and if it's valid submit the form.

$('#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;
    }
});

I assume that validation should be done only if code.length > 0 but if the validation should be done always move the return false part after this if condition.

Note: If the validation is only for 'valid email' it can be done on client side via javascript without server requests. Server request for validity should be done for uniqueness of email for example.

Upvotes: 1

user4571421
user4571421

Reputation:

Prevent default to stop the form from doing a postback. Check below for updated code:

 $(document).ready(function () {
        $('#signupform').submit(function (e) {
             e.preventDefault();
            var code = $('#txtcode').val();
            alert(code);
            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('failed')) {
                            alert(returndata);
                            return false;
                        }
                    }
                });
            }                    
        });
    });
</script> 

Upvotes: 0

Related Questions