1

I want to send post request with data from html form which will be filled by user. I would like to use jquery to achieve this. Here is my attempt (not working):

$(function () {
    $("#create").click(function (event) {
        event.preventDefault();
        $.ajax({
            type: "POST",
            url: "/home/new",
            data: $(this).serialize(),
            success: function (data, textStatus, jqXhr) {
                //call "home/new" with data from html form as json and update current view with returned data
                console.log("success");
            },
            error: function () {
                alert("error");
            }
        });
    });
});

<html lang="en">
<head>
    <script type="text/javascript" src="/Scripts/jquery-1.10.2.js"></script>
    <script src="/Scripts/Helpers.js"></script>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title>Title Goes Here</title>
</head>

<body>
    <form>
        Note:<br>
    </form>
    <textarea rows="4" cols="50" name="note" form="form">

    </textarea>
    <br/>
    <input type="date" name="day" form="form">
    <input type="submit" id="create" value="Submit" form="form">
</body>
</html>
2
  • 2
    $(this) does not refer to the form in this case, why do you expect that? You can solve that yourself, absolutely. Start using your browsers development console and output $(this). Look through the object... Commented Dec 17, 2015 at 20:24
  • Right, I will use console. Thanks, Commented Dec 17, 2015 at 20:26

1 Answer 1

2

I believe this should do the trick:

  1. Loop through your inputs with jQuery in order to extract your values.
  2. Store the values in a new object.
  3. Pass this object to your Ajax call.

You just need to add this piece of code (source: Obtain form input fields using jQuery?)

var values = {};

$.each($('#myForm input').serializeArray(), function(i, field) {
values[field.name] = field.value;
});

And pass values as the data to your Ajax call.

Here is the example in JSFiddle: https://jsfiddle.net/gsdfoyu5/6/

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

1 Comment

This is nice, but not working for textarea (only iterating over inputs). I used this code: date: document.getElementById("day").value, note: document.getElementById("note").value As objects in request data.

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.