Send Object data and variable data with FormData objects using Ajax-requests in jQuery

Send additional parameter as object and variable with form data with ajax using jQuery.

JavaScript / Ajax Code

function generateImageQr() {
        var imageId = jQuery('#imageUploadQr').prop('files')[0];
        var formData = new FormData();

        var visibility = jQuery('input[name="visibility"]:checked').val();
        var tags = jQuery('#tags').val();
        var img_title = jQuery('#img-title').val();
        var description = jQuery('#description').val();
        var source_url = jQuery('#source_url').val();
        var cat_name = jQuery('#cat_name').val();
        var cat_custom = jQuery('#cat_name').data("categarys");
        var sub_cat = jQuery('#sub_cat').val();
        var series_cat = jQuery('#series_cat').val();
        var actor_cat = jQuery('#actor_cat').val();
        var seo_title = jQuery('#seo_title').val();
        var seo_alt = jQuery('#seo_alt').val();

        console.log(visibility);

        var otherData = {
            "visible": visibility,
            "tags": tags,
            "img_title": img_title,
            "description": description,
            "source_url": source_url,
            "cat_name": cat_name,
            "cat_custom": cat_custom,
            "sub_cat": sub_cat,
            "actor_cat": actor_cat,
            "series_cat": series_cat,
            "seo_title": seo_title,
            "seo_alt": seo_alt
        };

        formData.append('file', imageId);

        for (const [key, value] of Object.entries(otherData)) {

            formData.append(key, value);

        }

        console.log(formData);
        $.ajax({
            url: 'upload.php',
            type: 'POST',
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            success: function(data) {
                console.log(data);
               // location.reload();
            }
        });
    }

FormData object is an iterable structure that resembles an array and contains numerous name-value pairs as well as maybe an HTML form.

jQuery append() method is used to insert key value pair to the object as the last child the selected elements.

PHP Code for form data handling

if(isset($_FILES['file'])){

     $rand = rand(1, 20);
    
    date_default_timezone_set("Asia/Calcutta"); 
        
    $visible = filter_var($_POST['visible'], FILTER_SANITIZE_STRING);
    $cat_id = filter_var($_POST['cat_name'], FILTER_SANITIZE_STRING);
    $img_id = uniqid("img");    
    $tag = filter_var($_POST['tags'], FILTER_SANITIZE_STRING);
    $title = filter_var($_POST['img_title'], FILTER_SANITIZE_STRING); 
    $description = filter_var($_POST['description'], FILTER_SANITIZE_STRING);   
    

//    echo 'Get Uploaded File';   
    
    if(0 < $_FILES['file']['error']){
        echo $_FILES['file']['error'].'<br>'; 
    }else{
       
        $fileUploadPathName = $pathFolder.'_'.$_FILES['file']['name']; 
        
        move_uploaded_file($_FILES['file']['tmp_name'], $fileUploadPathName); 
        $upload_size = $_FILES['file']['size'];
        
        $upload_size = number_format($upload_size / 1048576, 2) . ' MB';
        
       // echo $fileUploadPathName; 
       
        
        // Create connection
        $conn = new mysqli($servername, $username, $password, $dbname);
        // Check connection
        if ($conn->connect_error) {
          die("Connection failed: " . $conn->connect_error);
        }
        
         $array_sql = array();
        
        $array_sql['img_id'] = $img_id;    
        $array_sql['visible'] = $visible;    
        $array_sql['tag'] = $tag;    
        $array_sql['title'] = $title;    
        $array_sql['description'] = $description;    
           
        
            foreach( array_keys($array_sql) as $key ) {
                $fields[] = "`$key`";
                $values[] = "'" . $array_sql[$key] . "'";
            }  

            $fields = implode(",", $fields);
            $values = implode(",", $values);
 
            $sql =  "INSERT INTO `store` ($fields) VALUES ($values) ";
       
        if ($conn->query($sql) === TRUE) {
          echo "New record created successfully";
        } else {
          echo "Error: " . $sql . "<br>" . $conn->error;
        }

    $conn->close();
        
     
    
    }
}   
?>