Search code examples
javascriptphpfetch

Posting Form Data in Javascript with Fetch - Bug


I'd like to start by mentioning that I'm using vanilla Javascript and PHP, no jquery. The code that I have posted below is just a fragment. I have not included the PHP file or other code in javascript.

Now, the problem I am having is that no other code besides the form data post runs whenever I click my save button and activate the event. I have a console log at the beginning and end of the event to test if other code runs, and it never does. The form data, in this case a picture, gets posted to the PHP rest API file and stored in a folder as it should, but I do not receive a response in JSON from the PHP file that it is posted to, and my biggest problem is that no other code besides the post request runs in the event of the javascript code. Neither of the console.logs (test 1 and test 2) will appear.

When I test the post request with any other type of data, for instance, JSON, everything works perfectly. All of the code in the event runs, and I can receive responses in JSON from the same PHP file that the request was made to. There's something about posting form data that creates this bug. I hope that I have explained this clearly enough. Thank you for any assistance.

save_bg_btn.addEventListener('click', save_background_picture);

async function save_background_picture(){

    console.log("test 1");

    const formData = new FormData();
    const save_files_background_pic = file_bg_pic.files[0];
    const url = 'http://localhost/test/background-cover.php';

    formData.append("file_bg_pic", save_files_background_pic);

    await post_formdata_request(url, formData)
        .then(data =>{ 
            console.log(data);
        })
        .catch(err => console.log(err));
    
     console.log(test 2);

}


function post_formdata_request(url, formData){

    return new Promise((resolve, reject) => {
        
        fetch(url, {
            method: 'POST',
            body: formData
        })
        .then(res => res.json())
        .then(data => resolve(data))
        .catch(err => reject(err));
    });
}

Solution

  • Assuming this button is in a form, I think you need to add preventDefault() for the click event otherwise the form will submit and refresh the page. Also, fix the second console.log because that was breaking my tests until I noticed it as well.

    
    async function save_background_picture(e){
        e.preventDefault();
        
        // ...rest of the code
    
        console.log("test 2");  // <--- needed quotes
    }