0

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 ?

2
  • 1
    Uploaded files are not stored in $_POST, take a look at $_FILES instead. And you also need to add name attribute to the file input, otherwise it's not send to the server. After adding the name, you can access the file using $_FILES["input_name"]["tmp_name"]. Commented Jan 21, 2021 at 7:42
  • 1
    Not exactly related, but for future readers: If the native submit method is used in change handler, it will just ignore the attached submit handler of the form, and the form is submitted instead of the AJAX call being executed. With jQuery submit method this works fine. Commented Jan 21, 2021 at 7:51

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.