2

I have a basic form in HTML that looks like this:

<form id="myForm">
   <input type="text" id="name" name="name" />
   <br />
   <input type="text" id="email" name="email" />

  <input type="button" id="myButton" onclick="sendIt();">Send It</input>
</form>

<script type="text/javascript">
  function sendIt() {
    var endpoint = '/send-it';

    var xhr = new XMLHttpRequest();
    xhr.open('POST', endpoint, true);
    xhr.send();  
  }
</script>

In reality, my form is MUCH larger and has many more fields. I am trying to figure out how to POST this over AJAX. Previously, I was POSTing by using the method="POST" and an action on the form. However, I'm trying to remove the page refresh. So, I wanted to leverage AJAX via JQuery.

Is there some easy way to serialize the data and send it? I saw the following:

var data = $.param('#myForm');

But, that seems only relevant for appending to a query string. How can I POST myForm to my service via AJAX with jQuery?

Thanks!

user687554
  • 8,165
  • 22
  • 64
  • 119
  • 2
    Possible duplicate of [jQuery AJAX submit form](http://stackoverflow.com/questions/1960240/jquery-ajax-submit-form) – demo May 20 '16 at 18:22

1 Answers1

2

I believe you want something like this

$.ajax({
    type: "POST",
    url: url,
    data: data,
    success: function () {},
    dataType: dataType
});

See jQuery.post

To serialize, you can use:

$('form').serializeArray()

See serializeArray

Then your code:

function sendIt() {
    var endpoint = '/send-it'; 

    $.ajax({ 
        type: "POST",
        url: endpoint,
        data: $('#myForm').serializeArray(),
        success: function () {
            alert('success post');
        }
    });
}
Richard Deeming
  • 23,013
  • 5
  • 65
  • 114