简体   繁体   中英

How to upload a file together with other text inputs without refreshing the page

I use the code below to upload a file successfully without refreshing the page. What I want now is to add one text input field for the title of the file and one textarea to describe the file, but I am having difficulty doing that. It is giving me 'undefined index' error. What should I add to my code below to upload the file, text input and the textarea?

HTML

<form action="trash_one.php" method="post" id="uploadForm">
    <div id="targetLayer">No Image</div>
    <div id="uploadFormLayer">
    <label >Upload Image</label><br>
    <input type="file" class="inputFile" name="userImage" id="userImage">
    <input type="submit" name="submit" class="btnSubmit">
</form>
<div>

EXPECTED HTML FORM

Text input and textarea added

<form action="trash_one.php" method="post" id="uploadForm">
    <div id="targetLayer">No Image</div>
    <div id="uploadFormLayer">
    <input type="text" name="img_name">
    <label >Upload Image</label><br>
    <input type="file" class="inputFile" name="userImage" id="userImage">
    <textarea name="description" ></textarea>
    <input type="submit" name="submit" class="btnSubmit">
</form>
<div>

JAVASCRIPT

$(document).ready(function(e) {
  $("#uploadForm").on('submit',(function(e) {
    e.preventDefault();
    $.ajax({
        url: "trash_one.php",
        type: "POST",
        data: new FormData(this),
        contentType: false,
        cache: false,
        processData: false,
        success: function(data){
            $("#targetLayer").html(data);
        },
        error: function(){
        }
    });
}));
});

PHP

This script uploads only the file

if(is_array($_FILES)){
    if(is_uploaded_file($_FILES['userImage']['tmp_name'])){
        $sourcePath = $_FILES['userImage']['tmp_name'];
        $targetPath = "imagess/".$_FILES['userImage']['name'];
        if(move_uploaded_file($sourcePath,$targetPath)){
        ?>
        <img src="<?php echo $targetPath; ?>" width="100px" height="100px" />
        <?php
        }
    }
}

You're code is already working like you want to. Just take a look at the $_POST array instead of the $_FILES array. The post array contains all the text field contents. the files array contains uploaded files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM