Home Why I get error when I submit login form using jQuery Post?
Reply: 3

Why I get error when I submit login form using jQuery Post?

Michael
1#
Michael Published in 2017-11-14 10:10:38Z

I have this partial view:

@model GeomindEnterprise.Models.LoginViewModel

<div class="row">
    <div class="col-md-6 col-sm-6 col-xs-6">
        <!-- /SOCIAL LOGIN -->
        @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "sky-form", role = "form" }))
        {

            <fieldset class="nomargin">
                <div class="row">
                    <div class="col-md-10 col-md-offset-1">
                        @Html.AntiForgeryToken()

                        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                        <label class="input margin-bottom-10">
                            <i class="ico-append fa fa-envelope"></i>
                            @Html.TextBoxFor(m => m.UserName, new { @placeholder = "Email" })
                            @Html.ValidationMessageFor(m => m.UserName, "", new { @class = "text-danger" })
                        </label>

                        <label class="input margin-bottom-10">
                            <i class="ico-append fa fa-lock"></i>
                            @Html.PasswordFor(m => m.Password, new { placeholder = "Password" })
                            @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })
                        </label>

                        <label class="form-group">
                            @Html.CheckBoxFor(m => m.RememberMe, new { @class = "col-md-1" })
                            @Html.LabelFor(m => m.RememberMe)
                        </label>

                        <footer>
                            <button type="submit" onclick="myFunction()" class="btn btn-default noradius pull-right"><i class="fa fa-check"></i> OK, LOG IN</button>
                        </footer>
                    </div>
                </div>

            </fieldset>

        }
    </div>
</div>

When I click button submit, this javascript method is called:

 function myFunction() {      
        debugger;
        jQuery.ajax({
            type: "POST",
            url: '@Url.Action("Login", "Account")',
            contentType: "application/json; charset=utf-8",
            data: jQuery('form').serialize(),
            datatype: "json",
            success: function (data) {
                debugger;
                jQuery('#myModalContent').html(data);
            },
            error: function () {
                alert("Dynamic content load failed.");
            }
        });
    }

The javascript method above calls this action:

//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    //some logic
}

When the acction Login is called I get this error:

    The required anti-forgery form field "__RequestVerificationToken" is not present.

Any idea why I get this error?And how to fix it?

Stephen Muecke
2#
Stephen Muecke Reply to 2017-11-14 10:37:32Z

Remove the contentType: "application/json; charset=utf-8", ajax option, so that you use the default "application/x-www-form-urlencoded; charset=UTF-8" which you need when using .serialize() (note that the token is included in the request when using .serialize())

As a side note, you should be handling the forms .submit() event so you can validate the form before submitting. Remove the onclick="myFunction()" from your submit button and change the script to

$('form').submit(function(e) {
    e.preventDefault();
    if (!$(this).valid) {
        return; // cancel the ajax call and display error messages
    }
    ... make ajax call
});

You also have datatype: "json",, but the fact you also have $('#myModalContent').html(data); suggests that your controller method returns html (a PartialViewResult), not json, so it should be datatype: "html", (or just omit that option and the $.ajax() method will work it out)

Qaiser Imam
3#
Qaiser Imam Reply to 2017-11-14 10:27:09Z

Remove the @Html.AntiForgeryToken() from your form. it will work for now.How ever it will open you for attacks. Here is the article on anti forgery token to secure yourself.

https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/preventing-cross-site-request-forgery-csrf-attacks

Saneesh kunjunni
4#
Saneesh kunjunni Reply to 2017-11-14 11:28:54Z

What you want to do is.

contentType: "application/json; charset=utf-8"

And by doing that (which changes the kind of post request being made), to get the Json content of the actual data property to bind correctly to your T model type DO NOT JSON.stringify() or jQuery('form').serialize() the data.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.295551 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO