
Every time I do projects with AJAX in them, I always have to research the codes again and again. Yeah I have a weak memory, sue me!
Anyways, posting this for myself and for people who might need it in the future.
Sending FormData Using AJAX, jQuery, and Pure Javascript. Kinda awesome right! LOL
FormData Constructor or .serialize()?
var formD = new FormData( document.getElementById(“form-id”) )
If you are using JQuery, you can always use the serialize() function. It works well and returns the same data. Check the docs here.
Using JQuery, we can do this:
// using formData
var formD = new FormData( $(“#form-id”) )
// using serialize
var formD = $(“#form-id”).serialize()
You can use whichever you want… malaki ka na! char
Using JQuery and FormData
$.ajax({
type:”POST”,
url:”your-url-here”,
dataType:”json”, processData:false, contentType:false, cache:false,
data:new FormData( $(“#form-id”) ),
beforeSend: function( pikachu ) {
// display waiting message
}, error: function ( squirtle ) {
// display error message
}
}).done( function( evolve ) {
// do what you want
})
Using JQuery and serialize()
$.ajax({
type:”POST”,
url:”your-url-here”, dataType:”json”, data:$(“#form-id”).serialize(),
beforeSend: function( pikachu ) {
// display waiting message
}, error: function ( squirtle ) {
// display error message
}
}).done( function( evolve ) {
// do what you want
})
As you can see that’s pretty much it LOL
Codes using Pure Javascript and FormData
var request = new XMLHttpRequest()
request.open(“POST”, “your-url-here”, true)
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
var rs = JSON.parse(request.response)
// do what you want
} else {
// display error message
}
}
request.onerror = function() {
// display connection error message
}
request.send( new FormData( document.getElementById(“form-id”) ) )
There you go, we can’t really use the serialize() function in pure JS since that is a library of jQuery.
For some explanations, maybe drop a comment below.
HAPPY CODING!!!!
1 Comment
Working at Walmart · November 7, 2022 at 8:19 pm
Good to know!