Ad

How Can Append Data Object When Send Data Via Ajax On Vue Component?

My script to send data via ajax axios like this :

let formData = new FormData()
formData.append('file', user.avatar)
formData.append('selected_data', user)

axios.post(this.baseUrl+'/member/profile/update',
    formData,
    {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    }
).then(function(response) {
    console.log('sukses')
})
.catch(function(error) {
    console.log('fail')
})

If I do this :

console.log(user.avatar)
console.log(user)

The result like this :

enter image description here

My code in the backend (I use laravel framework) like this :

public function update(Request $request)
{
    echo '<pre>';print_r($request->all());echo '</pre>';
    die();
}

The result like this :

enter image description here

Why selected data is not show data object?

If the image is not show, look at this :

image 1 : https://postimg.org/image/hqshs9l23/

image 2 : https://postimg.org/image/i3jvyi8hn/

Ad

Answer

It says [object Object]because its converted to string. FormData sends these as strings. You can use something like JSON.stringify(user) to convert it to string and then append it.

Maybe something like this will solve your problem.

formData.append('selected_data', JSON.stringify(user))

Then you can convert this back to an object in your backend code.

Ad
source: stackoverflow.com
Ad