Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submit form with jquery ajax

I'm trying to learn MVC and one the things I want to do is submit a form to an action in my controller and this action will return the submitted data. Sounds simple but I've been trying for hours without any success. my view:

 @using (Html.BeginForm("BlogComment","Blog"))
 {
     @Html.ValidationSummary(true)
    <legend class="AddAComment">Add a comment</legend>

    <div class="commentformwrapper">

        <div class="editor-text">
        <span class="editor-label">User Name:</span>
        </div>

        <div class="editor-text">
        <input type="text" id="username" />
        </div>

        <div class="editor-text">
        <textarea id="comment" rows="6" cols="23"></textarea>
        </div>

        <div class="editor-field">
        <input type="hidden" id="hiddendate" />
        </div>

        <input type="submit" id="submit" value="Create" />

    </div>
}

my controller:

[HttpPost]   
public ActionResult CommentForm(Comment comment)
{
    Comment ajaxComment = new Comment();
    ajaxComment.CommentText = comment.UserName;
    ajaxComment.DateCreated = comment.DateCreated;
    ajaxComment.PostId = comment.PostId;
    ajaxComment.UserName = comment.UserName;

    mRep.Add(ajaxComment);
    uow.Save();
    //Get all the comments for the given post id

    return Json(ajaxComment);
}

and my js:

 $(document).ready(function () {

        $('form').submit(function () {

            $.ajax({
                url: '@Url.Action("CommentForm")',
                type: "POST",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                data: {
                    PostId: $('.postid').val(),
                    UserName: $('#username').val(),
                    DateCreated: new Date(),
                    CommentText: $('#comment').val()
                },
                success: function (result) {

                    alert("success " + result.UserName);
                },
                error: function (result) {
                    alert("Failed");
                }
            });
          return false;
        });
    });
like image 802
user2302622 Avatar asked Apr 20 '13 17:04

user2302622


People also ask

Can we submit form using AJAX?

We can submit a form by ajax using submit button and by mentioning the values of the following parameters. type: It is used to specify the type of request. url: It is used to specify the URL to send the request to. data: It is used to specify data to be sent to the server.

What is AJAX form submission?

AJAX form submitting allows you to send data in the background, eliminating the need to reload websites to see the updates. This makes the user experience much smoother.

How do I automatically submit a form without clicking?

Submit a Form Using JavaScript The most simple way to submit a form without the submit button is to trigger the submit event of a form using JavaScript. In the below example we are going to create a function to submit a form. We will set that function at onclick event of a div tag.


3 Answers

You don't need to write any client side code to do this, FYI.

To use the ajax methods successfully in MVC, you will need to do the following. Add this key to appsettings in web.config:

  <appSettings>
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>

As well as include the unobtrusive ajax script:

<script src="/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>

Then create div container around your form and replace Html.BeginForm with Ajax.BeginForm

<div id="ajaxReplace">
@using (Ajax.BeginForm("BlogComment", "Blog", null, new AjaxOptions { UpdateTargetId = "ajaxReplace", OnSuccess = "doFunctionIfYouNeedTo", OnFailure = "ShowPopUpErrorIfYouWant" }))
 {
 @Html.ValidationSummary(true)
        <legend class="AddAComment">Add a comment</legend>

        <div class="commentformwrapper">

            <div class="editor-text">
            <span class="editor-label">User Name:</span>
            </div>

            <div class="editor-text">
            <input type="text" id="username" />
            </div>

            <div class="editor-text">
            <textarea id="comment" rows="6" cols="23"></textarea>
            </div>

            <div class="editor-field">
            <input type="hidden" id="hiddendate" />
            </div>

            <input type="submit" id="submit" value="Create" />

        </div>

    }
</div>

Then in your controller you'll return something like this:

return PartialView(ajaxComment);

This will save you maintaining a script to do this manually and will funnel you into using the framework as intended. It will also help you out with data annotation validation and all of the juicy stuff that goes with it,

I hope this helps in some way.

like image 169
Moby's Stunt Double Avatar answered Oct 04 '22 15:10

Moby's Stunt Double


Try this:

The Model

public class Comment
{
    public string CommentText { get; set; }
    public DateTime? DateCreated { get; set; }
    public long PostId { get; set; }
    public string UserName { get; set; }
}

The View and js

@model SubmitMvcForWithJQueryAjax.Models.Comment

@using (Html.BeginForm("BlogComment","Blog"))
{
    @Html.ValidationSummary(true)
    <legend class="AddAComment">Add a comment</legend>

    <div class="commentformwrapper">

        <div class="editor-text">
        <span class="editor-label">User Name:</span>
        </div>

        <div class="editor-text">
            @Html.EditorFor(m => m.UserName)
        </div>

        <div class="editor-text">
            @Html.TextAreaFor(m => m.CommentText, new { rows="6", cols="23"} )
        </div>

        <div class="editor-field">
             @Html.HiddenFor(m => m.DateCreated)        
        </div>

         <div class="editor-field">
             @Html.HiddenFor(m => m.PostId)          
        </div>

        <input type="submit" id="submit" value="Create" />

    </div>

}

<script type="text/javascript">
    $(document).ready(function () {

        $('form').submit(function () {
            var serializedForm = $(this).serialize();                       
            $.ajax({
                url: '@Url.Action("CommentForm")',
                type: "POST",                                       
                data: serializedForm,
                success: function (result) {

                    alert("success " + result.UserName);
                },
                error: function (result) {
                    alert("Failed");
                }

            });
            return false;
        });
    });

</script>

The Controller

public class CommentController : Controller
{
    //
    // GET: /Comment/

    public ActionResult Index()
    {
        return View(new Comment());
    }

    [HttpPost]
    public ActionResult CommentForm(Comment comment)
    {
        Comment ajaxComment = new Comment();
        ajaxComment.CommentText = comment.UserName;
        ajaxComment.DateCreated = comment.DateCreated ?? DateTime.Now;
        ajaxComment.PostId = comment.PostId;
        ajaxComment.UserName = comment.UserName;

        //mRep.Add(ajaxComment);
        //uow.Save();
        //Get all the comments for the given post id

        return Json(ajaxComment);


    }

}
like image 27
Bob Nowadly Avatar answered Oct 04 '22 13:10

Bob Nowadly


Basically you are passing javascript object literals directly. So, before you pass data to your controller, it must be in JSON format(because you have specified application/json. see your $.ajax call).
SO, you are missing JSON.stringify()

data: JSON.stringify({
                        PostId: $('.postid').val(),
                        UserName: $('#username').val(),
                        DateCreated: new Date(),
                        CommentText: $('#comment').val()
                    }),

OR

var someObj = {
            PostId: $('.postid').val(),
            UserName: $('#username').val(),
            DateCreated: new Date(),
            CommentText: $('#comment').val()
        };

         $.ajax({
            /// your other code
            data: JSON.stringify(someObj),
            // your rest of the code

        });
like image 28
Idrees Khan Avatar answered Oct 04 '22 13:10

Idrees Khan