0

In jQuery, we have $('form').serialize() to post all the form data in a single line. Is there any method available in JavaScript to post form data like this or is there an alternative in JavaScript for the code below code?

var url = "path.php"; 
$.ajax({
       type: "POST",
       url: url,
       data: $("#idForm").serialize(), //like this i need in js
       success: function(data)
       {
       }
});
Suman r
  • 75
  • 1
  • 9
  • jQuery is built with JavaScript, you could look at the source code for `.serialize()` and `$.ajax()` to see what it's doing. – Cᴏʀʏ Aug 02 '17 at 11:57
  • 3
    Possible duplicate of [form serialize javascript (no framework)](https://stackoverflow.com/questions/11661187/form-serialize-javascript-no-framework) – Code Lღver Aug 02 '17 at 11:59

2 Answers2

2

You can use FormData, like this:

let data = new FormData(document.querySelector('form'));

And then:

let request = new XMLHttpRequest();
request.open("POST", "url");
request.send(data);

More info: FormData API

I hope it helps you

nidstang
  • 175
  • 4
0

Serialize is creating a parameter string like field1=value1&field2=value2

When using the jquery ajax, the data can provided as object or array

var x = document.getElementById("myForm");
var formData = [];
var i;
for (i = 0; i < x.length; i++) {
    formData[x.elements[i].name] = x.elements[i].value;
}

$.ajax({
       type: "POST",
       url: url,
       data: formData
       success: function(data)
       {
       }
});
Auskennfuchs
  • 1,577
  • 9
  • 18