JavaScript submit form fields to PHP back-end throws Unsupported Media Type

70 Views Asked by At

I have two sites running separately, where the front end is one end, which connects to multiple back-end systems.

The end goal is to be able to submit a form with text and video fields to a PHP(Drupal) back-end.

For this, my HTML and JS look like the following:

<form method="post" enctype="multipart/form-data">
    <input type="text" name="first_name" id="first_name">
    <input type="text" name="surname" id="surname">
    <textarea name="message" id="message" cols="30" rows="10"></textarea>
    <input type="file" name="sample_image" id="sample_image">
    <div id="uploaded_image"></div>
</form>
<script>

    const first_name = document.querySelector("#first_name");
    const surname = document.querySelector("#surname");
    const message = document.querySelector("#message");
    const sample_image = document.getElementsByName("sample_image")[0];

    sample_image.addEventListener('change', e => {
        e.preventDefault()
        upload_image(sample_image.files[0])
    })

    const upload_image = (file) => {            
        const form_data = new FormData();
        form_data.append("sample_image", file);

        let data = {
            "webform_id": "springboks",
            "first_name": first_name.value,
            "surname": surname.value,
            "message": message.value,
            "video": form_data
        };

        fetch("http://localhost:49640/api/v1/form/14436545/CBUFormSubmission", {
            mode: 'no-cors',
            headers: { 
                'Content-Type': 'application/json'
            },
            method: "POST",
            params: { '_format': 'json'},
            body: JSON.stringify(data)
        }).then(function(response){
            return response.json();
        }).then(function(responseData){
            console.log("responseData")
            console.log(responseData)
        })
    }
</script>

For now, am running the script during file upload, and am getting the following in the console:

http://localhost:49640/api/v1/form/14436545/CBUFormSubmission net::ERR_ABORTED 415 (Unsupported Media Type)

However, I get a successful response when doing the submission using Insomnia, obviously without the file and the setup is as follows:

enter image description here

enter image description here

enter image description here

Below is also the payload(without the file for now) when I look at developer tools: enter image description here

In code, with or without the file I get the 415 response. And this is with or without the video.

How do I submit the form data to the backend system?

0

There are 0 best solutions below