-1

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";
}

?>
James
  • 37
  • 1
  • 5

2 Answers2

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

Kunal Raut
  • 2,495
  • 2
  • 9
  • 25
  • After making that change, ajax still would't fire. If I deleted "dataType: 'json'", I got the alert "Not working". – James Jun 13 '20 at 02:45
  • Can you tell me what's ajax status in dev tools ? – Kunal Raut Jun 13 '20 at 02:47
  • you are posting data to `sendFile.php` which is wrong you should post it to `uploadFile.php` – Kunal Raut Jun 13 '20 at 02:51
  • uploadFile.php. just changed that. I haven't used dev tools so I'm figuring that out. – James Jun 13 '20 at 03:00
  • Ok don't worry i'll tell you the process basically for debugging ajax requests Press `Ctrl+Shift+i` and then in networks tab go into `XHR` and just initiate the request and from there you can debug your ajax calls – Kunal Raut Jun 13 '20 at 03:04
  • Thanks. The output in the preview tab is "Notice: Undefined index: image in C:\xampp\htdocs\long_polling\uploadFile.php on line 3 NULL Warning: getimagesize([object FormData]): failed to open stream: No such file or directory in C:\xampp\htdocs\long_polling\uploadFile.php on line 7" – James Jun 13 '20 at 03:11
  • Ok here are two things to be taken care of first check if your upload.php is in the same directory if not give the correct path and secondly image should not be and index it should be as my answer says `data` in the php file. – Kunal Raut Jun 13 '20 at 03:15
  • uploadFile.php is in the same directory and I changed the index to data. I'm currently getting it to work using the answer below, but only if I DON'T set the dateType to 'json'. – James Jun 13 '20 at 03:37
  • You can do two things here as 1: Do not set any dataType or set it to `text` because setting it to `json` will return a javascript object – Kunal Raut Jun 13 '20 at 03:42
  • For more details search for dataType in https://api.jquery.com/jquery.ajax/ – Kunal Raut Jun 13 '20 at 03:43
  • Thanks for all your input. You helped me a ton. – James Jun 13 '20 at 03:54
  • My pleasure @James :) – Kunal Raut Jun 13 '20 at 03:55
1

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'});
Star_Man
  • 1,091
  • 1
  • 13
  • 30
  • ajax didn't fire. If I deleted "dataType: 'json'", I got an alert saying "undefined index: image" – James Jun 13 '20 at 02:58
  • I'm getting the same result as before – James Jun 13 '20 at 03:06
  • @James, I updated the formdata set. try my answer again now. – Star_Man Jun 13 '20 at 03:07
  • ajax didn't fire. I then deleted "dataType: 'json'" and received the alert "array(5) { ["name"]=> string(8) "home.png" ["type"]=> string(9) "image/png" ["tmp_name"]=> string(24) "C:\xampp\tmp\phpF432.tmp" ["error"]=> int(0) ["size"]=> int(6259) } Not working" – James Jun 13 '20 at 03:18
  • @James, now you uploaded file to server successfully. You have to study file upload process in php. – Star_Man Jun 13 '20 at 03:30
  • Thanks. Most of what I read said to set dataType: 'json'. Should I have any concerns since it is only working without this? – James Jun 13 '20 at 03:33