1

I have a form with a file uploader. I want to display error messages without refreshing the page. I guess I need to display the errors with jQuery and pass the file to the PHP script with Ajax. I'm not sure how to approach this.

This is my current code. After submission, it redirects you to upload.php and displays error/success messages there, but it isn't very user friendly.

<form method="post" action="upload.php" enctype="multipart/form-data">
     <div id="file_upload">
          <input type="file" name="file">
          <input type="submit" value="Upload">
     </div>
</form>


<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$fileType = pathinfo($target_file,PATHINFO_EXTENSION);

// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists. Rename and try again.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["file"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($fileType != "zip" ) {
    echo "Sorry, only zip files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>
Data
  • 689
  • 7
  • 23

3 Answers3

0

You can use Ajax with FormData():

Here us HTML code :

<form method="post" onsubmit="return submitForm()" action="upload.php" enctype="multipart/form-data">
     <div id="file_upload">
          <input type="file" name="file">
          <input type="submit" value="Upload">
     </div>
</form>

Here is Jquery AJAX code :

function submitForm() {
    var formData = new FormData($('form')[0]);
    $.ajax({
        type: 'POST',
        dataType: 'json',
        processData: false,
        contentType:  false,
        data: formData,
        url: 'upload.php',
        success:function(){
            //code after success upload
        }
    });
    return false;
}
Pankaj Makwana
  • 3,030
  • 6
  • 31
  • 47
0

Here you can go with this code. it will helps you.

Html

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="upload.php" enctype="multipart/form-data" class="upload_form">
 <div id="file_upload">
      <input type="file" name="file">
      <input type="submit" value="Upload">
 </div>
</form>

jQuery

$(".upload_form").on("submit",function()
{
    $.ajax(
    {
        url: 'upload.php',
        type: 'post',
        data: $(this).serialize(),
        success:function(response) {
            console.log(response);
        },
        error: function(response) {
            console.log(response);
        }
    });
    return false;
});

PHP

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$fileType = pathinfo($target_file,PATHINFO_EXTENSION);

// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists. Rename and try again.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["file"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($fileType != "zip" ) {
    echo "Sorry, only zip files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>
Nirav Joshi
  • 2,924
  • 1
  • 23
  • 45
0

try this one as per your code

HTML and Script File
add letest .js library:letest js file

<form method="post"  enctype="multipart/form-data">
     <div id="file_upload">
          <input type="file" name="file" id="file">
          <input type="button" value="Upload" id="upload">
     </div>
</form>
<script type="text/javascript" src="letest js file"></script>
<script type="text/javascript">
  $(document).ready(function(){
    $("#upload").click(function(){
        var data = new FormData();
          $.each(jQuery('#file')[0].files, function(i, file) {
              data.append('file-'+i, file);
          });
        $.ajax({
            url: 'error.php',
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            type: 'POST',
            success: function(data){
                  alert(data);
              }
          });
    });
  });
</script>

PHP code

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES['file-0']['name']);
$uploadOk = 1;
$fileType = pathinfo($target_file,PATHINFO_EXTENSION);

//echo $target_file;/*
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists. Rename and try again.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["file-0"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($fileType != "zip" ) {
    echo "Sorry, only zip files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["file-0"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["file-0"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>
Bhargav Chudasama
  • 6,928
  • 5
  • 21
  • 39