form having image submission using ajax in php code example

Example 1: upload image ajax demo

$(document).ready(function(){

    $("#but_upload").click(function(){

        var fd = new FormData();
        var files = $('#file')[0].files[0];
        fd.append('file',files);

        $.ajax({
            url: 'upload.php',
            type: 'post',
            data: fd,
            contentType: false,
            processData: false,
            success: function(response){
                if(response != 0){
                    $("#img").attr("src",response); 
                    $(".preview img").show(); // Display image element
                }else{
                    alert('file not uploaded');
                }
            },
        });
    });
});

Example 2: file upload in php through ajax

async function saveFile() 
{
    let formData = new FormData();           
    formData.append("file", sortpicture.files[0]);
    await fetch('/uploads', {method: "POST", body: formData});    
    alert('works');
}

Tags:

Php Example