Click here to Skip to main content
15,867,488 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello,

I created file upload with ajax, but then i uploading file ajax refresh page and everything goes to database, but I need to upload file without refreshing the page, somewhere is a problem, and i don't see, please help!


My HTML code:
HTML
<pre>  <div class="panel panel-default">
          <div class="panel-body">
            <form id="uploadImage" enctype="multipart/form-data">
              <div class="form-group">
                  <label for="darb_fileUpload">Įkelkite savo pabaigtus darbus</label>
                  <input type="file" name="darb_fileUpload" id="uploadFile">
              </div>
              <div class="form-group">
                <input type="submit" name="submit" value="Įkelti" class="btn btn-info"/>
              </div>
            </form>
              <div class="progress">
                  <div class="progress-bar"></div>
              </div>
              <!-- Display upload status -->
              <div id="uploadStatus"></div>
          </div>
        </div>


AJAX code :
JavaScript
<pre>$(document).ready(function(){
    // File upload via Ajax
    $("#uploadImage").on('#submit', function(e){
        e.preventDefault();
        $.ajax({
            xhr: function() {
                var xhr = new window.XMLHttpRequest();
                xhr.upload.addEventListener("progress", function(evt) {
                    if (evt.lengthComputable) {
                        var percentComplete = ((evt.loaded / evt.total) * 100);
                        $(".progress-bar").width(percentComplete + '%');
                        $(".progress-bar").html(percentComplete+'%');
                    }
                }, false);
                return xhr;
            },
            type: 'POST',
            url: 'add_darb.php',
            data: 'darb_fileUpload'(this),
            contentType: false,
            cache: false,
            processData:false,
            beforeSend: function(){
                $(".progress-bar").width('0%');
                $('#uploadStatus').html('<img src="images/loading.gif"/>');
            },
            error:function(){
                $('#uploadStatus').html('<p style="color:#EA4335;">File upload failed, please try again.</p>');
            },
            success: function(resp){
                if(resp == 'ok'){
                    $('#uploadImage')[0].reset();
                    $('#uploadStatus').html('<p style="color:#28A74B;">File has uploaded successfully!</p>');
                }else if(resp == 'err'){
                    $('#uploadStatus').html('<p style="color:#EA4335;">Please select a valid file to upload.</p>');
                }
            }
        });
    });

    // File type validation
    $("#uploadFile").change(function(){
        var allowedTypes = ['application/pdf', 'application/msword', 'application/vnd.ms-office', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'image/jpeg', 'image/png', 'image/jpg', 'image/gif'];
        var file = this.files[0];
        var fileType = file.type;
        if(!allowedTypes.includes(fileType)){
            alert('Please select a valid file (PDF/DOC/DOCX/JPEG/JPG/PNG/GIF).');
            $("#uploadFile").val('');
            return false;
        }
    });
});


PHP code:
PHP
if (!empty($_FILES)) {

    // File upload configuration
    $targetDir = "../uploads/";
    $allowTypes = array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg', 'gif');

    $fileName = basename($_FILES['darb_fileUpload']['name']);
    $targetFilePath = $targetDir.$fileName;

    // Check whether file type is valid
    $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
    if (in_array($fileType, $allowTypes)) {
        // Upload file to the server
        if (move_uploaded_file($_FILES['darb_fileUpload']['tmp_name'], $targetFilePath)) {
            $darb_fileUpload = 'ok';
        }
    }
}


What I have tried:

I have tried a lot of advice online but couldn't resolve this problem.
Posted
Updated 12-May-20 2:16am

I think it is
$("#uploadImage").on('#submit', function(e)

The first parameter of the on function is the name of the event and "#submit" isn't the name of an event.
 
Share this answer
 
As well as the incorrect event name that Matthew pointed out in solution 1, there's this:
Quote:
JavaScript
data: 'darb_fileUpload'(this),
I suspect that's going to be a syntax error - you're trying to call a string as if it's a function.

You should check your browser's developer console for errors. (You might need to enable the "persist logs" option so that you can still see the errors even after the page has reloaded.)

If you want to send a file upload via AJAX, you're going to need to use the FormData object:
Using FormData Objects - Web APIs | MDN[^]

Also take note of the jQuery documentation:
jQuery offers several ways to attach a function that will run when the DOM is ready. All of the following syntaxes are equivalent:
  • $( handler )
  • $( document ).ready( handler )
  • $( "document" ).ready( handler )
  • $( "img" ).ready( handler )
  • $().ready( handler )

As of jQuery 3.0, only the first syntax is recommended; the other syntaxes still work but are deprecated.
JavaScript
$(function(){
    // File upload via Ajax
    $("#uploadImage").on('submit', function(e){
        e.preventDefault();
        
        $.ajax({
            xhr: function() { ... },
            type: 'POST',
            url: 'add_darb.php',
            data: new FormData(this),
            contentType: false,
            cache: false,
            processData:false,
            beforeSend: function(){ ... },
            error:function(){ ... },
            success: function(resp){ ... }
        });
    });

    // File type validation
    $("#uploadFile").change(function(){ ... });
});
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900