Send data with ajax | Sololearn: Learn to code for FREE!

0

Send data with ajax

Hello everyone. How can I post my formdata to server by ajax in javascript? I'mworking with asp mvc

7/30/2020 1:31:22 PM

maryam mirzapoor

2 Answers

New Answer

+2

If you use jQuery, use the ajax method. Specify the data key in your ajax configuration. This will hold your form's parameters which correspond with the named inputs/selects/textareas... from your HTML form. Also, set type to 'POST' to indicate your HTTP request method. contentType should likely be 'application/json'. More detailed explanation of calling an ASP.net web API using JavaScript is at: https://www.carlrippon.com/calling-an-asp-net-web-api-from-jquery/ Official jquery ajax documentation is at: https://api.jquery.com/Jquery.ajax/ If you don't already use jQuery and really want to avoid it, fetch can process your HTTP POST request too. More explanation is at: https://javascript.info/fetch

+1

For example: 'use strict'; function init() { let form = document.getElementById('aForm'); form.addEventListener('submit', (e) => { e.preventDefault(); let formData = new FormData(form); let request = new XMLHttpRequest(); request.open('POST', 'aForm', true); request.send(formData); }); } document.addEventListener('DOMContentLoaded', init);