How to use $_FILES in a Jquery/Ajax script to stay on the previous HTML page and upload a file into a folder

I have a php script that uploads a file into a folder :

$photo = $_FILES["photo"]['name'];
$background = $_FILES["background"]['name'];
    
move_uploaded_file($_FILES["photo"]['tmp_name'],"C:/MAMP/htdocs/Projet-Your-Market/uploads/".$photo);
move_uploaded_file($_FILES["background"]['tmp_name'],"C:/MAMP/htdocs/Projet-Your-Market/uploads/".$background);

This works fine, don’t mind the fact that i don’t test if the files exist or other test, it is just to see how uploading a file works.

I also did a script using Ajax to avoid the php file to be loaded and then redirect to my homepage.

$(function(){
    $('#form').submit(function(e){
        e.preventDefault();
        var myData = $(this).serialize()

        $.ajax({
            url: '/Projet-Your-Market/PHP/createSellerAccount.php',
            type: 'POST', // GET or POST
            data: myData,
            success: function() { // data is the response from your php script
                // This function is called if your AJAX query was successful
                window.location.href = '/Projet-Your-Market/HTML/homePage.html';
            },
            error: function() {
                // This callback is called if your AJAX query has failed
                alert("Error!");
            }
        });
    });
});

These two codes seems to work fine independently but when i combine them the file that i need to upload is not uploaded.

Here is my html code

<div class="title">Create a seller account</div>
<form  method="POST" id="form" enctype="multipart/form-data">
    <div>Username : <input type="text" name="username"></div>
    <div>Password : <input type="password" name="password"></div>
    <div>First name : <input type="text" name="fName"></div>
    <div>Last name : <input type="text" name="lName"></div>
    <div>Email : <input type="text" name="email"></div>
    <div>Photo : <input type="file" name="photo"></div>
    <div>Background : <input type="file" name="background"></div>
    <button id="submitButton" type="submit">Create</button>
</form>

Answer

Instead of serialize() use FormData()

 var formData = new FormData(this);

See for more details – Uploading both data and files in one form using Ajax?

Leave a Reply

Your email address will not be published. Required fields are marked *