skip to Main Content

I need to send an image via ajax to a php file. I can not use form tags for my purposes. Based on what I’ve read, the best way to go about this is set processData and contentType to false and dataType to json. If I click submit, ajax doesn’t appear to fire. If I delete “dataType: ‘json'”, ajax fires and I get an alert “getimagesize([object FormData]): failed to open stream: No such file or directory in …”. I’ve read that I may need to reset Content-type on the server end, but I’m not sure how to go about this.

index.php

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).on('click', '#sendFile', function() {   
            var file = $("#file").prop('files')[0];
            var data = new FormData();
            data.append('image', data);
            $.ajax({
                type: "POST",
                processData: false,
                contentType: false,
                dataType: 'json',           
                url: 'uploadFile.php',
                data: data,
                success: function(data){
                    alert(data);
                }
            });
        });
    </script>
</head>
<body>
    <input type="file" name="file" id="file"><br>
    <button id="sendFile">Submit</button>
<body>
</html>

uploadFile.php

<?php

if(isset($_POST['image'])){
    $data = $_POST['image'];
    echo getImageSize($data); //Just to test if $data is an image file
} else {
    echo "Not working";
}

?>

2

Answers


  1. On the PHP page you must get the data by data not image because that’s the name you have set for the data in ajax

    <?php
    if(isset($_POST['data'])){
        $data = $_POST['data'];
        echo getImageSize($data); //Just to test if $data is an image file
    } else {
        echo "Not working";
    }
    ?>
    

    And yes, you are posting data to sendFile.php which is wrong you should post it to uploadFile.php

    Login or Signup to reply.
  2. Add your code as following:

    JAVASCRIPT

    var file = $("#file")[0].files[0];
            var data = new FormData();
            data.append('image', file);
    $.ajax({
                type: "POST",
                processData: false,
                contentType: false,
                cache: false,
                dataType: 'json',           
                url: 'uploadFile.php',
                mimeType: 'multipart/form-data',
                data: data,
                success: function(data){
                    alert(data);
                }
            });
    

    PHP

    var_dump($_FILES['image'});
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search