Uploading image using JQuery AJAX

Hi,
I want to upload an image file using JQuery AJAX and send it to php code for further processing including image cropping. I tried this code for Js:

<script type="text/javascript">
   $(document).ready(function() {
       $('#uploadstatus1').hide();
       $('#uploadstatus2').hide();

       $('#btnupload').click(function() {
           var file = $('#formFile')[0].files[0];
           var filename = file.name;
           var filedata = $('#formFile').prop('files')[0];
           var formdata = new FormData();
           formdata.append("file", filedata);
           formdata.append("filename", filename);
           $.ajax({
               url: "../app/model/saveimage.php",
               type: "POST",
               dataType: 'script',
               cache: false,
               processData: false,
               data: formdata,

               success: function(data2) {
                   if (data2 == 1) {
                       location.reload();
                   } else {
                       alert(data2);
                       $('#uploadstatus1').show();
                   }
               }
           });
       });
   });
   </script>

Uploading modal:

<div class="modal fade" id="uploadModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
           <div class="modal-dialog">
               <div class="modal-content">
                   <div class="modal-header">
                       <h5 class="modal-title" id="exampleModalLabel">Upload image</h5>
                       <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                   </div>
                   <div class="modal-body">
                       <form action="" method="POST" enctype="multipart/form-data">
                           <p>Upload file:</p>
                           <div class="mb-3">
                               <label for="formFile" class="form-label">Only Jpeg files are supported.</label>
                               <input class="form-control" type="file" id="formFile" name="formFile" required>
                           </div>
                       </form>
                       <div class="alert alert-danger" id="uploadstatus1" role="alert">
                           Upload failed!
                       </div>
                       <div class="alert alert-success" id="uploadstatus2" role="alert">
                           File uploaded successfully!
                       </div>
                   </div>
                   <div class="modal-footer">
                       <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                       <button type="button" class="btn btn-primary" name="btnupload" id="btnupload">Upload</button>
                   </div>
               </div>
           </div>
       </div>

saveimage.php:

if (isset($_POST['file'])) {
           try {

               //For uploading original image
               $crop = new Crop();

               $crop->img_name = $_FILES['file']['name'];
               $crop->tmp_img_name = $_FILES['file']['tmp_name'];
               $crop->folder = "../public/assets/uploadIMG/";
               //For finding file extension
               $crop->ext = pathinfo($crop->img_name, PATHINFO_EXTENSION);
               //Renaming the uploaded file
               $crop->new_name = $this->RandomStringGenerator() . "." . $crop->ext;
               $this->new_name = $crop->new_name;
               //Moving to the desired path
               move_uploaded_file($crop->tmp_img_name, $crop->folder . $crop->new_name);
               $this->RegisterIntoDatabase();

               //For cropping image and creating thumbnail
               $crop->RunCrop();

               unset($_POST);
               echo '1';
           } catch (\Throwable $th) {

               echo '2';
           }
       }else{
           echo '2';
       }

The problem is that if (isset($_POST[‘file’])) returns false.
How can I solve this problem?

The default contentType for a jquery ajax call won’t upload files. You need to specifically set it to a false value in order to upload files. Add the following to the .ajax parameters -

contentType: false,

Next, the var file = ... line is already getting all the file information. You don’t have to do anything else to this. Just append it to the formdata object -

formdata.append('file', file);

When this works, you will get a traditional $_FILES array in the php code, which contains the filename, so, no extra client-side code is needed to specifically get the filename and send it with the form data.

1 Like

I changed JS to this:

<script type="text/javascript">

    $(document).ready(function() {

        $('#uploadstatus1').hide();

        $('#uploadstatus2').hide();

        $('#btnupload').click(function() {

            const file = document.getElementById("formFile").files[0];

            const formdata = new FormData();

            formdata.append("file", file);

            $.ajax({

                url: "../app/model/saveimage.php",

                type: "POST",

                processData: false,

                contentType: false,

                data: formdata,

                success: function(data2) {

                    if (data2 == 1) {

                        location.reload();

                    } else {

                        alert(data2);

                        $('#uploadstatus1').show();

                    }

                }

            });

        });

    });

    </script>

it still returns false for if (isset($_POST[‘file’]))

See this -

There is no $_POST data being sent, because there are no text, select, radio, or checkbox form fields in your form and the click event on the submit button that causes the javascript code to execute occurs before the button is a successful form control, so the button won’t ever exist in the $_POST data. This is why all form processing code should always detect if the request method == ‘POST’ in order to detect if a post method form was submitted.

1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service