1

I am trying to use jquery( v. 1.11.3 )ajax, in conjunction with jquery.validate 1.15 to upload a form that includes input type file. You can see from the js comment lines some of everything I have tried. With each of the variations the php script returns "no image file". Of course, if I remove the jquery script, the form submits fine with accompanying page refresh. I really wanted to eliminate the page refresh for a better UX but I am having no luck getting this to work. If someone could help me fix my code, I'd really appreciate it. Please Note: I have researched numerous examples of jquery ajax .post but these examples are not helping me as those code structures don't work with Jquery.Validate plugin. I also found this answer here: File Upload PHP AJAX but as you can see from my code comments, I have tired this with no luck. I must be missing something.

Heading ##The html and js:

<!DOCTYPE html>
<html>
<body>

<form action="imguploadTest.php" method="post" enctype="multipart/form-data" id="addItemsForm" name="addItemsForm">
<label>Select image to upload:</label>
    <input type="file" name="itemImg" id="itemImg" />

<label>Name</label>
    <input type="text" name="itemName" class="form-control" placeholder="Item Name..." maxlength="25" value="Really Cool Hoodie" />

<input type="submit" value="Upload Form" name="submit">

<div>
    <div id="results"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">    </script>
<script src="js/bootstrap.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/additional-methods.min.js"></script>
<script>
$(document).ready(function(){

    $.validator.setDefaults({
        highlight: function(element) {
            $(element).closest('.form-group').addClass('has-error');
        },
        unhighlight: function(element) {
            $(element).closest('.form-group').removeClass('has-error');
        },
        errorElement: 'span',
        errorClass: 'help-block',
        errorPlacement: function(error, element) {
            if(element.parent('.input-group').length) {
                error.insertAfter(element.parent());
            } else if (element.parent('.radio-inline').length || element.parent('.checkbox-inline') ) {
                error.insertAfter(element.parent().parent());
            } else {
                error.insertAfter(element);
            }
        }
    });

    $('#addItemsForm').validate({ // initialize the plugin

        debug: true,

        submitHandler: function(){

            //var formData = $('#addItemsForm').serialize();
            //var data = new FormData($('#addItemsForm'));
            //var form = $('form')[0];
            //var formData = new FormData(form);
            //console.log(addform);
            var frmData = new FormData($(this)[0]);

            $.ajax({
                url: "imgUploadTest.php",
                data: frmData,
                cache: false,
                contentType: false,
                processData: false,
                dataType: 'json'
            })
            .done( function(res, jqXHR, textStatus) {
                console.log(res);
                //$('#results').html('<h4>Thumb link: ' + res["thumb"] + '<h4>');
                //$('#results').append('<h4>Small link: ' + res["small"] + '<h4>');
                //$('#results').append('<h4>Name: ' + res["name"] + '<h4>');
            })
            .fail( function (res, jqXHR, textStatus, errorThrown){
                alert("failed!  " + jqXHR, textStatus);
            });

        return false;

        }  // submitHandler

    });  // validate

});  // doc ready

</script>
</body>
</html>

Heading ##The PHP:

        <?php

        include 'imguploader.class.php';

        // FUNCTIONS

            function imagehandler($item_attr_ID) {

                $imgId = $item_attr_ID;
                $img = new imgUploader($_FILES['itemImg']);
                $time = time();
                $thumb = $img->upload('mobileApp/uploads/', $imgId.'_thumb', 100,100);  // change these numbers for display
                $small = $img->upload('mobileApp/uploads/', $imgId.'_small', 400,400);  // change these numbers for display
                //$full = $img->upload_unscaled('mobileApp/uploads/', $time);

                if($thumb && $small){ // && $full
                    return array($thumb, $small);
                      /* TO SHOW IMAGE
                      echo '<img src="'.$thumb.'" alt="aPicture" /> <img src="'.$small.'" alt="aPicture" /> <img src="'.$full.'"alt="aPicture" />';
                      */
                } else {
                    echo ( 'ERROR! '.$img->getError() );  // --> error code 011.1
                }
            } // end imagehandler()

        // Processes

        if (!empty( $_FILES["itemImg"]) ){
            $item_attr_ID = "jPlayerandtheGirls_8_1456";
            list($item_img_thumb, $item_img_small) = imagehandler($item_attr_ID);
                if ($item_img_thumb && $item_img_small){
                    $r["thumb"] = $item_img_thumb; 
                    $r["small"] = $item_img_small;
                } else {
                    $r["thumb"] = "No Thumb"; 
                    $r["small"] = "No Small";
                    $r["name"] = "Didn't get to name";
                    echo json_encode($r);
                }
        } else {
            $r = "No image file";
            echo json_encode($r);
        }

        if (!empty( $_POST["itemName"] )){
            $r["name"] = $_POST["itemName"];
            json_encode($r);
        }
        ?>
Community
  • 1
  • 1
detourOfReason
  • 325
  • 1
  • 3
  • 11

1 Answers1

0

Ok I am able to answer my own question, though I am not exactly sure about the theory that goes with it as I am relatively new to JS/Jquery. .serialize() does not work. I think this is because by definition, files are binaries and thus can not be serialized - but don't quote me. So you have to use FormData to send the file. I was aware of this but could not come up with the proper syntax for use with jquery validation 1.15. See the answer below. Hope it helps someone to save some time.

first correct the rookie mistake with my code: add type: 'post'

second: the variable to hold your form's data, including the input type="file" is this var formData = new FormData($('#useYourFormElementIdHere')[0]);

So the final is this:

$.ajax({
     type: "POST",
     url: "imgUploadTest.php",
     data: formData,
     cache: false,
     contentType: false,
     processData: false,
     dataType: 'json'
 }).done({}).fail({}).always({})
detourOfReason
  • 325
  • 1
  • 3
  • 11