Skip to content
Advertisement

jquery – upload image file using ajax is not working

I want to submit my image via jquery and ajax , this is my code:

    <form name="photo" id="imageUploadForm" enctype="multipart/form-data" action="<?php echo $base_url ?>admin/resid.php" method="post">
    <input type="file" accept="image/*" id="imguploadresid" /> 
</form>

<Script>

$("#imguploadresid").on("change", function() {
        $("#imageUploadForm").submit();
});
    
$('#imageUploadForm').on('submit',(function(e) {
        e.preventDefault();

        var form = $('#imageUploadForm')[0];
        var formData = new FormData(form);
  
        $.ajax({
            type:'POST',
            url: "<?php echo $base_url ?>admin/resid.php",
            data:formData,
            cache:false,
            enctype: 'multipart/form-data',
            contentType: false,
            processData: false,
            success:function(data){
                console.log("succes")
            },
            error: function(data){
                console.log("error");
            }
        });
    }));

just to add some explanation , when the use choose an image , the form submits immediately .

it works fine and post the data to my php page , but it’s empty and has no data

I put print_R($_POST) in my page and the result is

Array

( )

I logged the ajax post and there was no data posting .

what is the problem ?

Advertisement

Answer

Your image is probably in PHP array $_FILES. You must download your file from it to get your image.

$yourImage = file_get_contents($_FILES['image']['tmp_name']);

You have also to add “name” attribute to your input:

<form name="photo" id="imageUploadForm" enctype="multipart/form-data" action="<?php echo $base_url ?>admin/resid.php" method="post">
  <input name="image" type="file" accept="image/*" id="imguploadresid" /> 
</form>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement