0

I want to get from post value in my class method via ajax call here is my html page

<form method="post">
    <input type="text" name="text"  />
    <input type="email" name="email" />
    <input type="file" name="file" />
    <input type="date" name="date" />
    <input type="submit" name="send" />
</form>

And this is my jquery code

$(document).ready(function () {
        $('form').submit(function (e) {
            var data = $(this).serializeArray();
            var jsObj = {};
            $.each(data, function (feild, value) {
                jsObj[value.name] = value.value;
            });

            $.ajax({
                url: "index.cs/addRow",
                method: "post",
                dataType: "json",
                data: jsObj,
                success : function(response){
                    console.log(response);
                }
            });
            e.preventDefault();
 });

And this is my c# code these is the method where i want post form

[WebMethod] 
public static void addRow(object form)
{
  var stuff = form;
}

1 Answer 1

1

Your url parameter seems to be wrong (it should reference to ASPX page instead of code-behind file), also if the response is not JSON better to opt out dataType: 'json' definition. Try handling submit button's click event instead waiting for form submission like example below:

Markup (ASPX)

<form method="post">
    <input type="text" name="text"  />
    <input type="email" name="email" />
    <input type="file" name="file" />
    <input type="date" name="date" />
    <input id="submit" type="submit" name="send" />
</form>

jQuery

$('#submit').click(function () {
    var formData = $('form').serializeArray();

    $.ajax({
        url: 'index.aspx/addRow',
        method: 'POST',
        data: formData,
        success: function (response) {
            // do something
        },
        // error handling
    });
});

Note 1: $.each(data, function (feild, value) { ... }) is unnecessary because serializeArray() already contains form objects.

Note 2: If the form data is unchanged before POST, I suggest you using serialize() instead of serializeArray().

Related: Use AJAX to submit data from HTML form to WebMethod

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.