laksh's avatar
Level 1

How to pass form data through ajax

i am working on a project in which i got a form which contain input fields and input file field i want to save form data and file using ajax my input fields data is getting saved through ajax but not file so how can i save it

0 likes
4 replies
Tray2's avatar

I use the fetch api to do all my ajax calls.

async function postRequest(url, parameters = {}) {
    try {
        let responsePromise = await fetch(url, { 
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: new URLSearchParams(parameters)
        });
        if(! responsePromise.ok) {
            throw new Error(responsePromise.status );
        }
        return await responsePromise.json();
    } catch (error) {
        return error;
    }
}

You call it like

async function myAjaxCall() {
let params = {
	somevalue: 1,
    someothervalue: 2
};

let response = await postRequest('https://api.yoursite.com/someendpoint', params);

}
```
2 likes

Please or to participate in this conversation.