I am building a website that can send custom data after submission with the below code.
$('form').submit((e)=>{
e.preventDefault();
let data = $('form').serializeArray();
console.log(data);
$.ajax({
url: 'path/to/submit',
type: 'POST',
data: data,
success: (res) => {
console.log(res);
}
})
});
form {
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
Name
<input type="text" name="name" value="Andi" /><br />
Password
<input type="password" name="password" value="pass" /><br />
Role <br/ >
<input type="radio" name="role" value="teacher" checked /> Teacher <br />
<input type="radio" name="role" value="student" /> Student <br />
Hobby <br/ >
<input type="checkbox" name="hobby[]" value="Sport" checked /> Teacher <br />
<input type="checkbox" name="hobby[]" value="Music" /> Student <br />
Description
<textarea name="description">I like programming</textarea><br />
City
<select name="city">
<option value="Jakarta">Jakarta</option>
<option value="Bali">Bali</option>
</select><br />
<input type="submit" />
</form>
So, to get the data after submission, I use .serializeArray()
method with returning an array of object data. But the output does not identical to my expectation:
{
"name": "Andi",
"password": "pass",
"role": "teacher",
"hobby": ["Sport"],
"description": "I like programming",
"city": "Jakarta"
}
Is there a simple way to get data as JSON Object after submission like the example above?
2
Answers
Not really sure if this is what you really want but you can try this
You can use the native FormData object. You need to loop through all the keys now that you have more values (radio buttons) with the same name. So, if there are more values with the same name/key you get the value as an array (with getAll()) otherwise you get the plain text value.