3

I'm currently working on a script to allow users to upload an image. The script will then return a string containing the file name that will be used in a simplistic text editor.

As of right now, the AJAX call to my PHP file (update.php) does not seem to be working correctly. When I check to see if anything is in $_FILES, I find that it is empty.

I'm still relatively new to PHP and AJAX so I've been looking quite extensively to figure out my problem but have yet to find anything that has fixed the issue.

This is my HTML Code:

<form action="javascript:;" method="post" id="customFRM" enctype="multipart/form-data">
    <input type="hidden" name="rec" id="rec" value="0" />
    <div style="background-color:#3C6893;padding:.5em 15px;width:276px;float:right;color:#fff;">Manage IS Tips</div>
    <textarea name="customPost" id="customPost" cols="60" rows="5"></textarea>
    <br />
    <div style="clear:both;">
        <div style="display:inline;">
            <input name="Link" id="add-link" type="button" value="Insert Link" class="blue-btn">
            <input name="Bold" id="add-bold" type="button" value="Bold" class="blue-btn">
            <input name="Image" id="addImg" type="file" value="Insert Image" class="blue-btn" accept="image/gif, image/jpeg">
        </div>
        <div style="padding-top: 15px">
            <input name="Submit" id="save-custom" type="button" value="Save" class="blue-btn">
        </div>
    </div>
</form>

This is my script that pertains to the Image Upload:

$("#addImg").change(function(event){
        //event.preventDefault(); // need to pick file
        //uploadImg();
        var storedFileName = uploadImg();
        $("#customPost").val($("#customPost").val() + '[img=(' + storedFileName + ')/][/img]'); //on render - /images/directory/storedFileName.ext

    });

function uploadImg() {

    //Needs to make an .ajax request to upload/php script. Script should return the file name of the processed file.

    //should check for file type

    var fileName = false;
    var formData = new FormData();

    fileName = $("#addImg")[0].files[0].name;//don't use this one
    console.log($("#addImg")[0].files[0]);

    formData.append("image", $("#addImg")[0].files[0]);
    console.log(formData);
    alert(formData);
    //*
    //upload file   
    $.ajax({
        url: "upload.php",        // Url to which the request is send
        dataType: "json",
        type: "POST",             // Type of request to be send, called as method
        data: formData,           // Data sent to server, a set of key/value pairs (i.e. form fields and values)
        contentType: false,       // The content type used when sending data to the server.
        cache: false,             // To unable request pages to be cached
        processData:false,        // To send DOMDocument or non processed data file it is set to false
        success: function(data){
            //alert(data);
            //console.log(data);
            fileName = data.image.name;
            alert(fileName);
            //parsed=JSON.parse(data);

            //fileName=parsed.fileName;
            },
        error: function(data){

            console.log(data);
        }
    });
        //*/

    return fileName;
};
</script>

Currently, on upload.php I just have:

<?php
    //echo "test test echo";
    echo json_encode($_FILES);
?>


Forums I've looked at for help:

jQuery AJAX file upload PHP
Access files posted through AJAX using $_FILES variable
jQuery AJAX file upload PHP
jQuery Ajax File Upload

Community
  • 1
  • 1
ebbBliss
  • 173
  • 1
  • 13
  • Have you tested with `echo json_encode($_POST['image']);` in **upload.php** page? Because, you are sending `image` to **upload.php** through `formData.append("image", $("#addImg")[0].files[0]);`. – Nana Partykar Dec 14 '16 at 17:32
  • Try this to upload file with ajax: https://gist.github.com/optikalefx/4504947 – Sazzadur Rahman Dec 14 '16 at 17:43
  • @NanaPartykar I tested it with `echo json_encode($_POST['image']);` it's returning a null and a undefined index error – ebbBliss Dec 14 '16 at 17:50
  • Make sure the server allows for file uploads. >_ – Tank Dec 15 '16 at 18:41
  • @Tank While it wasn't the only issue, it was an issue. I have no access to the server config so I had to wait until someone who did could check on it. – ebbBliss Dec 16 '16 at 13:36

1 Answers1

1

You need to make few changes in your uploadImg() function, such as:

  • Since you're encoding $_FILES using json_encode() function on the server side, change the dataType setting to json. dataType is the type of data you're expecting back from the server. This way you don't have to parse the response in the success() callback function, AJAX will take care of that.
  • Since you're sending images using FormData object, set the contentType to false.
  • You're getting the file name in the success() callback function in the wrong way, it should be like this:

    success: function(data){
        fileName=data.image.name;
        alert(fileName);
    }
    

So your uploadImg() function should be like this:

function uploadImg() {
    var fileName = false;
    var formData = new FormData();

    fileName = $("#addImg")[0].files[0].name;
    formData.append("image", $("#addImg")[0].files[0]);

    $.ajax({
        url: "upload.php",          // Url to which the request is send
        dataType: "json",         // Type of data you're expecting back from server
        type: "POST",             // Type of request to be send, called as method
        data: formData,           // Data sent to server, a set of key/value pairs (i.e. form fields and values)
        contentType: false,       // The content type used when sending data to the server.
        cache: false,             // To unable request pages to be cached
        processData:false,        // To send DOMDocument or non processed data file it is set to false
        success: function(data){
            fileName=data.image.name;
            alert(fileName);
        },
        error: function(data){
            console.log(data);
        }
    });
    return fileName;
}
Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37
  • It's giving me an error at `fileName=data.image.name;` says: "Cannot read property 'name' of undefined" – ebbBliss Dec 14 '16 at 18:08
  • @ebbBliss Did you change anything apart from the ones I suggested above? Have you copied the `uploadImg()` function code correctly? – Rajdeep Paul Dec 14 '16 at 18:11
  • No, I made no other changes. I updated my original post with the updated uploadImg() function, everything looks like it matches up with yours – ebbBliss Dec 14 '16 at 18:18
  • @ebbBliss Strange, everything is working fine on my end. Please paste your HTML, jQuery and PHP code on [pastebin.com](http://pastebin.com/index.php) and give me it's link here. – Rajdeep Paul Dec 14 '16 at 18:23
  • http://pastebin.com/gUMuLy8q upload.php is just `` Looking more closely at debugging it, data is coming back empty for the success function. – ebbBliss Dec 14 '16 at 18:32
  • @ebbBliss Everything is working fine with the given pastebin code snippet. Also, instead of `.change()`, you should bind the events with `.on()`. Just for debugging, change `$("#addImg").change(function(event){...}` to [http://pastebin.com/VEYjgZ6H](http://pastebin.com/VEYjgZ6H) – Rajdeep Paul Dec 14 '16 at 18:45
  • Thanks, your changes helped, found out the reason why it wasn't working was because of a Server Config issue that I had no control over. – ebbBliss Dec 16 '16 at 13:35
  • @ebbBliss Glad I could help. Cheers! :-) – Rajdeep Paul Dec 16 '16 at 15:34