Using the Form.Submit method



Submitting form data through AJAX request

The form element contains an action attribute that tells the form where to submit its data.

Users can submit form's data through an AJAX request without leaving the current page while the request is being processed.

You can capture the data from all form elements by constructing a query string to submit to the server from the AJAX call.

The following code demonstrates this:

<body>
<form id="signupForm">
    First Name: <input type="text" id="firstName" name="firstName" /><br />
    Last Name: <input type="text" id="lastName" name="lastName" /><br />
    <input type="radio" name="gender" value="m" />Male
    <input type="radio" name="gender" value="f" /> Female
    <input type="checkbox" name="brownCheck" /> Brown
    <input type="checkbox" name="blueCheck" /> Blue
    <button type="submit">Submit</button>
</form>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.2.0.min.js"></script>
<script>
    $("document").ready(function () {
        $("form").submit(function () {
            var fName = $("#firstName").val();
            var lName = $("#lastName").val();
            //construct a query string
            var qString = "Last Name=" + lName + "&First Name=" + fName;
            $.ajax({
                url: 'processSignUp.aspx',
                type: "POST",
                data: qString,
                success: function (r) {
                }
            });
            return false;
        });
    });
</script>
</body>

Using the jQuery.serialize method

jQuery provides a way to encode data from an HTML form by traversing the form that’s passed into it and looking for input boxes to construct and return a query string.

The jQuery.serialize method handles the extraction of the data from all the input elements and creates the query string. Only successful controls are serialized.

<body>
<form id="signupForm">
    First Name: <input type="text" id="firstName" name="firstName" /><br />
    Last Name: <input type="text" id="lastName" name="lastName" /><br />
    <input type="radio" name="gender" value="m" />Male
    <input type="radio" name="gender" value="f" /> Female
    <input type="checkbox" name="brownCheck" /> Brown
    <input type="checkbox" name="blueCheck" /> Blue
    <button type="submit">Submit</button>
</form>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.2.0.min.js"></script>
<script>
    $("document").ready(function () {
        $("form").submit(function () {
            //SERIALIZE ALL INPUTS IN VAR qString = $(this).serialize()
            var qString = $(this).serialize();
            alert(qString);
            $.ajax({
                url: 'processSignUp.aspx',
                type: "POST",
                data: qString,
                success: function (r) {
                }
            });
            return false;
        });
    });
</script>
</body>

PROMOTIONS