problem of Multipart/form-data with PHP and AJAX by POST method

Viewed 113

I made a form in PHP to insert in my Database an image from the form. The form works and my Ajax request works too. The problem is that when I want to insert my image in the '../uploads' repository I have to use the $_FILES method and this when my ajax request doesn't work anymore... I don't understand, I created another form just to test if my php code to insert the image in the repositroy was right and it was. I made research and I think it could be link to the multipart/form-data in ajax (I don't know a lot in AJAX, really). Can someone help me please ? Here is my code :

the form :

<form action="traitement.php" method="post" enctype="multipart/form-data" id="form_img">
   Choose a file<input type="file" name="fileToUpload" id="fileToUpload">
   <button type="submit" name="submit_btn" id="submit_btn">OKK</button>
</form>

the traitement in php :

$target_dir = "../uploads/";
$target_file = $target_dir.basename($_POST['fileToUpload']);
//$exec is my sql request to insert the image (and it works).
if ($exec){ 
                echo "Success";
                move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
            }

my ajax request :

$("#form_img").submit(function(e){
            e.preventDefault();
    
            $.post(
                'traitement.php', 
                {
                    fileToUpload : $("#fileToUpload").val()                    },
    
                function(data){
                    if(data == 'Success'){
                     $("#text_ajt").removeClass('text-warning').addClass('text-success').html("cool");
                    }
                    if(data == 'Failed'){
                        $("#text_ajt").addClass('text-danger').html("respect the format");
                    }
                    if(data == 'Miss'){
                        $("#text_ajt").addClass('text-warning').html("miss something");
                    }
                },
                'text'
            );
        });
1 Answers

Ajax is not needed here. Just send your form (using target) to a hidden iframe and write an on-load event for your iframe.

somthing like this:

HTML:

<form action="traitement.php" method="post" enctype="multipart/form-data" target="file_upload_frame" id="form_img">
   Choose a file<input type="file" name="fileToUpload" id="fileToUpload">
   <button type="submit" name="submit_btn" id="submit_btn">OKK</button>
</form>

<iframe id="file_upload_frame" name="file_upload_frame" frameborder="0" style="display: none"></iframe>

jQuery:

$('#file_upload_frame').on("load", function () {
    var response = $(this).contents().find('body').html()
           
    alert(response );
});
Related