How to send form data in ajax

Let’s start we have a simple form.

<form id="contactForm">
    <div class="form-control">
        <label for="name">Name</label>
        <input id="name" name="name" type="text" />
    </div>
    <div class="form-control">
        <label for="email">Email</label>
        <input id="email" name="email" type="email" />
    </div>
    <div class="form-control">
        <label for="message">Remark</label>
        <textarea id="remark" name="remark" rows="6" cols="65"></textarea>
    </div>
    <button class="btn" type="button" id="submit">Submit</button>
</form>

Below function Converting FormData to JSON

<script>
$.fn.serializeFormJSON = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
</script>
</html>

Now use serializeFormJSON() function to Converting FormData to JSON and send form.

<script>
$(document).ready(function(){
  $("#submit").click(function(){
   var  data= $("#contactForm").serializeFormJSON(); // convert to json    
    console.log(data)
    $.ajax({
        url: 'http://localhost:51964/savedata',
        dataType: 'json',
        type: 'post',
        contentType: 'application/json',
        data: JSON.stringify(data),
        processData: false,
        success: function (data, textStatus, jQxhr) {
      
        },
        error: function (jqXhr, textStatus, errorThrown) {
      
        }
    });

  });
  return false;
});
</script>
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments