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>
Piotr M
  • 499
  • 3
  • 9
  • 27
  • 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... – arkascha Dec 17 '15 at 20:24
  • Right, I will use console. Thanks, – Piotr M Dec 17 '15 at 20:26

1 Answers1

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/

Community
  • 1
  • 1
Alexis Matelin
  • 194
  • 1
  • 9
  • 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. – Piotr M Dec 17 '15 at 23:28