简体   繁体   中英

How to solve this jQuery ajax post method undefine index problem while uploading images?

I want to Upload photos by using Ajax Post method, Here is my html and javascript code

 <script> $(document).ready(function(){ $('#multiple_upload_form').submit(function(e){ e.preventDefault(); var upload = $('#images').val(); $.ajax({ type:'POST', url:'album.php', data: { upload : images }, cache:false, contentType:false, processData:false, success:function(data) { $('#image_preview').html(data); }, error:function() { $('#image_preview').html('error'); } }); return false; }); }); </script> 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form method="post" action="album.php" name="upload_form" id="multiple_upload_form" role="form" enctype="multipart/form-data"> <div class="form-group"> <label for="email">Album Name</label> <input type="text" name="aname" class="form-control" id="aname"> </div> <div class="form-group"> <label for="file">Upload Photos:</label> <input type="file" id="images" name="images" /> </div> <div id="images_preview"></div> </div> <center class="feedback" style="display:none">Loading...</center> <button id="submit" name="submitt" class="btn btn-default">Submit</button> </form> 

and this is my PHP CODING

if(isset($_FILES['images']['name']) )
{
    $img = $_FILES['images']['name'];

    if(!empty($img))
    {
        echo 'MaxSteel';
    }
}
else
{
    echo 'Same Problem';
}

I am having undefine index : images it works fine with input type="text" but when it comes to "file" type is shows error help me solving this problem

Its posible that the file is not upload becouse of some error. You should review the parameters related to file upload as UPLOAD_MAX_SIZE, etc.

You can use var_dump($file) to see the $_FILE content.

You need to be sending your data through FormData(). Try something like this:

var images = $("#images").get(0).files;
var formData = new FormData();

$.each(images, function(i, image) {
  data.append("images[]", image);
});

Then send formData as your $.ajax data.

Go through this code, it may help

                   var data = new FormData();  
                    data.append("Avatar", file.files[0]);
                    $.ajax({
                     url: "http://192.168.1.1:2002/,
                     type: "POST",             
                     data:data,
                     contentType: false,      
                     cache: false, 
                     processData:false,  
                     success: function(data)
                      {
                     console.log(data);
                      }

                     });

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