0

I have a form in which I retrieved the fields with ajax and send those as post to a PHP file. But one of the fields is a input type="file".

My question is as follow: how to properly send this file (an image) via ajax to the PHP file and read the file so I can upload it to a server.

Here's my code: The form and fields

<form class="uploadForm" id="uploadForm" method="post" enctype="multipart/form-data">
                                    <div class="response" id="response"></div>
                                    <div class="custom-file">
                                        <input type="hidden"
                                               name="<?php echo ini_get("session.upload_progress.name"); ?>"
                                               value="video_upload">
                                        <input type="file" name="lien_video" class="custom-file-input" id="customFile">
                                        <label class="custom-file-label" for="customFile">Choisir le logo</label>
                                    </div>
                                    <div class='progress' id="progress_div">
                                        <div class='bar' id='bar1'></div>
                                        <div class='percent' id='percent1'>0%</div>
                                    </div>
...and some other stuffs

The script so far it's inside the same PHP file as the form

<script type="text/javascript">
            $(document).ready(function () {
                //upload data
                $(document).on('click', '#enreg_ecole', function () {
                    let nom_ecole = $('#input-1').val();
                    let adresse = $('#input-2').val();
                    let nom_rep = $('#input-3').val();
                    let email_rep = $('#input-4').val();
                    let tel_rep = $('#input-5').val();
                    let poste = $('#input-6').val();
                    // let logo = $('#customFile').val();
                    let logo = document.getElementById("customFile").files[0];

                    var form = new FormData();
                    form.append('enreg_ecole', 1);
                    form.append('nom_ecole', nom_ecole);
                    form.append('adresse', adresse);
                    form.append('nom_rep', nom_rep);
                    form.append('email_rep', email_rep);
                    form.append('tel_rep', tel_rep);
                    form.append('poste', poste);
                    if(logo != null){
                        form.append('logo', logo);
                    }


                    $('#scroller').animate({scrollTop: 0}, 'fast');

                    var bar = $('#bar');
                    var percent = $('#percent');

                    $.ajax({
                        url: 'methods/enregistrer_ecole.php',
                        type: 'post',
                        cache: false,
                        contentType: false,
                        processData: false,
                        data:form,
                        enctype: 'multipart/form-data',
                        dataType: 'json',
                        beforeSubmit: function () {
                            document.getElementById("progress_div").style.display = "block";
                            var percentVal = '0%';
                            bar.width(percentVal)
                            percent.html(percentVal);
                        },
                        uploadProgress: function (event, position, total, percentComplete) {
                            var percentVal = percentComplete + '%';
                            bar.width(percentVal)
                            percent.html(percentVal);
                        },
                        success: function (response) {
                            let status = response['status'];
                            let message = response['message'];

                            if (status === 'error') {
                                // window.alert(message);
                                document.getElementById("progress_div").style.display = "none";
                                document.getElementById("alert_div").style.display = "inline";
                                $('#alert_div').addClass('alert-danger');
                                $('#alert_title').html(status);
                                $('#alert_message').html(message +' ' +logo);
                            } else {
                                // window.alert(message);
                                document.getElementById("alert_div").style.display = "inline";
                                // $('#bar1').animate({width: "100%"}, 100);
                                var percentVal = '100%';
                                bar.width(percentVal)
                                percent.html(percentVal);
                                $('#alert_div').addClass('alert-success');
                                $('#alert_title').html(status);
                                $('#alert_message').html(message);
                            }
                        },
                        // complete: function (xhr) {
                        //
                        // },
                        error: function (error, ajaxOptions, thrownError) {
                            // let error = JSON.parse(response);
                            // window.alert('Error happenned: ' + error);
                            // window.alert('Error happenned: ' + response.msg);
                            // var msg = $.parseJSON(error).msg;
                            window.alert(error);
                            window.alert(ajaxOptions);
                            window.alert(thrownError);
                        }
                    });

                    //window.alert('clicked');
                });
            });
        </script>

I want to be able to do something like:

$target_file = $target_dir . basename($_FILES["lien_video"]["name"]);

----EDIT---- Okay, I tried some more codes and it looks like on my PHP file (enregistrer_ecole.php called from ajax), if I try to retrieve only the texts from the form, it's okay. If I try to retrieve only the file, it's okay. But trying to retrieve both the texts and the picture file (like $_POST['someText'] and $_POST['someFile']['tmp_name'] it throws an error.

Does anyone know a way to do this properly? Like get the texts first and then get the file. I don't know.

  • It'll need to be [`multipart`](https://stackoverflow.com/questions/4526273/what-does-enctype-multipart-form-data-mean) for one. – tadman Aug 13 '20 at 19:18

2 Answers2

0

HTML

<div class="container">
    <form method="post" action="" enctype="multipart/form-data" id="myform">
        <div class='preview'>
            <img src="" id="img" width="100" height="100">
        </div>
        <div >
            <input type="file" id="file" name="file" />
            <input type="button" class="button" value="Upload" id="but_upload">
        </div>
    </form>
</div>

PHP

<?php

/* Getting file name */
$filename = $_FILES['file']['name'];

/* Location */
$location = "upload/".$filename;
$uploadOk = 1;
$imageFileType = pathinfo($location,PATHINFO_EXTENSION);

/* Valid Extensions */
$valid_extensions = array("jpg","jpeg","png");
/* Check file extension */
if( !in_array(strtolower($imageFileType),$valid_extensions) ) {
   $uploadOk = 0;
}

if($uploadOk == 0){
   echo 0;
}else{
   /* Upload file */
   if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
      echo $location;
   }else{
      echo 0;
   }
}
0

One of the form attribute is missing in your HTML and that is enctype

<form class="uploadForm" id="uploadForm" method="post" enctype="multipart/form-data">
</form>

and there can be one improvement: instead of writing each input field appended to form data object, you can write single line.

you can replace all these lines

var form = new FormData();
form.append('enreg_ecole', 1);
form.append('nom_ecole', nom_ecole);
form.append('adresse', adresse);

into a single line as below:

var form = new FormData($("form")[0]);

Ishpreet
  • 659
  • 5
  • 19