0

I have a simple file upload form that works properlly only when when I remove the ajax script from the form html file. With out on submission I am taken to a blank page wiht the proper error or success message (It validates like it should).

If I include it, it bypasses all my arguments and skips right to the last error. Saying there You must upload a file to continue.

Is there something I am missing in my ajax file? I can't figure out why it skips all my validation.

Thanks for any help you can give

Form Html File

<form enctype="multipart/form-data" id="anytimereg-form" class="shake" method="post" action="test-process-form.php'?>">                 
    <div id="frm-filehandler">
        <div id="file-drop" class="well">
            <input type="file" name="upload" id="uplfile" class="inputfile" />
            <label for="uplfile"><i class="fa fa-upload" aria-hidden="true"></i>Choose a file</label>
        </div><!--end #file-drop-->
    </div><!--end #frm-filehandler-->
    <input type="hidden" name="action" value="upload"/>
    <button id="submit" name="submit" type="submit" class="action-button btn-lg">Submit Registration</button>
</form>

test-process.php

<?php
$errors = array();
$data = array();

// A list of permitted file extensions
$allowed = array('png', 'jpg', 'pdf');

if(isset($_FILES['upload']) && $_FILES['upload']['error'] == 0){

    $extension = pathinfo($_FILES['upload']['name'], PATHINFO_EXTENSION);
    //Max Fiels Size
    $maxsize = 2097152;
    //File Size
    $file_size = $_FILES['upload']['size'];
    //The File Path
    $file_path = '../../../../../upl_docs/';
    //The File Name
    $file_name = $_FILES['upload']['name'];

    //Is the file type allowed
    if(!in_array(strtolower($extension), $allowed)){
        $errors['upload'] = 'File type not allowed';

    }
    //Does the file already exist
    if(file_exists($file_path.$file_name)){
        $errors['upload'] = $file_name.' That file already exists. Please select another or rename your file.';

    }
    //is the file size to big
    if($file_size >= $maxsize){
        $errors['upload'] = 'Your File is too large. File must be less than 2 megabytes.';

    }

    if(empty($errors)){
        //We upload the file to outside of the root directory for security reasons
        if(move_uploaded_file($_FILES['upload']['tmp_name'], $file_path.$file_name)){
            $success['upload'] = $file_name.' Message: File has been uploaded';

            $data['success'] = $success;

        }else{
            $errors['upload'] = 'Could not find the directory';
        }

        //$data['success'] = $success;
    }//If empty of errors
    else{
        $data['success'] = false;
        $data['errors']  = $errors;
    }

}else{
    $errors['upload'] = 'You must upload a File to continue';
    $data['errors'] = $errors;
}
echo json_encode($data);
?>

Ajax File

// Set up an event listener for the contact form.
$(form).submit(function(event) {
    $('.error-message').remove();
    // Serialize the form data.
    var formData = $(form).serialize();

    $.ajax({
        type: 'POST',
        url: $(form).attr('action'),
        data: formData,
        dataType :'json',
        encode:true
    })
    .done(function(data){
        //Log the data into the console so that we can be sure what is happening
        console.log(data);

        //If we do have errors create the 
        if(!data.successmessage){
            if(data.errors){
                $(form).removeClass('success');
                $('.submit-success').remove();

                $(form).addClass('form-has-error'); // add the form-has-error-class

                if(data.errors.upload){
                    $('#frm-filehandler').addClass('has-error'); // add the error class to show red input
                    $('#frm-filehandler').append('<div class="error-message"><p>' + data.errors.upload + '</p></div>'); 
                    // add the actual error message under our input
                }
                $('footer').prepend('<div class="error-message"><p>There are errors with your submission. Errors will be marked in red</p></div>');

            }//end data errors
        }//end no data successmessage

        else if(data.successmessage){
            //Remove the errors stuff
            $('.error').remove();
            $('.error-message').remove();
            $(form).removeClass('form-has-error'); // add the form-has-error-class
            $('.submit-success').remove();
            //Add the success stuff
            $(form).addClass('success');


            $('footer').prepend('<div class="success-message"><p>' + data.successmessage + '</p></div>');

        }//End if successmessage
    })//end done function

    .fail(function(data){
        //If there is a failed submission lets log the errors
        console.log(data);
    });

    //Stop the broweser from submitting the form
    event.preventDefault();
    });
});   
bilcker
  • 956
  • 1
  • 8
  • 28
  • [Have you watched the AJAX request / response in the browser's developer tools? Have you included the jQuery library in the project? Are there any errors reported? Are you running this on a web-server?](http://jayblanchard.net/basics_of_jquery_ajax.html) – Jay Blanchard Jun 20 '17 at 19:33
  • Thanks for your Reply, – bilcker Jun 20 '17 at 19:52
  • Thanks for your Reply, There are no errors, I have included the jquery library. Yes I am running on a server and When i view the response in the developer tools, all I get is and object with the response upload: "You must upload a File to continue." Is there a better way to review a response? – bilcker Jun 20 '17 at 19:58

2 Answers2

1

You can't post files the way you do with text data. You need to use xhr requests to post the file.

For more information:

https://stackoverflow.com/a/10811427/3774582

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

Goose
  • 4,243
  • 3
  • 36
  • 75
-1

Honestly that AJAX code you posted is terrible... what an awful and convoluted way to show/hide simple success or error messages. I mean it takes six lines of code to hide an error message if the form is successfully validates...

I would reprogram all of it (PHP included), make it simpler. Shouldn't take all that code to make a simple AJAX form.

Edward B.
  • 418
  • 3
  • 10