User987
User987

Reputation: 3825

jquery: Uncaught TypeError: Illegal invocation

I have a problem when I try to submit my form to an action on my server side code which looks like this:

   [ValidateAntiForgeryToken]
   public async Task<ActionResult> DoRegister(UserRegistrationViewModel model)
   {
     // Some code here
   }

The form contains Html.AntiForgeryToken() as well so this isn't an issue. The jQuery code looks like following:

 $('form').submit(function (event) {
        event.preventDefault();

        if ($(this).valid()) {

            StartLoading();
            var formdata = new FormData($(this).get(0));
            $.post("/User/DoRegister",formdata, function (data) {
                $(".registerLoader").fadeOut("fast");
                if (data.statusCode == 200) {
                    window.location.href = "/Plans";
                }
                else if (data.statusCode == 100) {
                    $("body").html(data.View);
                }
            });
        }
        return false;
    });

When I try to submit the form I get the following error:

jquery: Uncaught TypeError: Illegal invocation 

What am I doing wrong here? Can someone help me out?

Upvotes: 0

Views: 261

Answers (1)

Muhammad Saqlain
Muhammad Saqlain

Reputation: 2212

The problem is that you are passing an HTML element instead of its value. You can use serializeArray

var formdata = $("form").serializeArray();

The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. It operates on a jQuery collection of forms and/or form controls.

Upvotes: 1

Related Questions