0

I tried to combine the browse button and submit button together .When the button is clicked , Iam able to select the file.

But the file doesn't get uploaded

This is the form

HTML:

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"])?>" method="post" id="myform" enctype="multipart/form-data">
    <input type="file" name="upload" id="upload" style="display:none">
    <button id="browse">Upload</button>
</form>

JQuery

$(document).ready(function(){
        $("#upload").change(function(){
                $("#myform").submit();
        });
        $("#browse").click(function(){
        $("#upload").click();
        });

    });

Then I submitted the data

PHP :

if($_SERVER["REQUEST_METHOD"]=="POST")
{

    $file=$_FILES["upload"]["name"];
    $folder='uploads/';
    $err=$_FILES["upload"]["error"];
    $target=$folder.$file;
    $temp=$_FILES["upload"]["tmp_name"];
    echo $err;
    move_uploaded_file($temp, $target);
}

I got the output as 4 . This means that no file was uploaded .How can i resolve this issue?

Anoop saju
  • 450
  • 3
  • 16
  • http://php.net/manual/en/function.error-reporting.php and check folder permissions and the console. `` btw, isn't a valid closing tag, so you can safely get rid of it. – Funk Forty Niner Mar 29 '16 at 15:18
  • add `type="button"` to the browse button, else it will also fire the submit event: `` the default button type in forms is submit. Also, try `print_r($_FILES)` and `print_r($_POST)` for debugging information – Tanuel Mategi Mar 29 '16 at 15:22

1 Answers1

0

There is a easy an elegant way to achieve that.

  • Add the type="submit" to the button because not all web browser are using "submit" as default button type
  • Add a form event listener that triggers when "submit" event is raised

Example code:

$(document).ready(function(){
  
  $('#myform').submit(function(e) {
    
    // Remove following two lines in order to perform the submission
    // I added the two lines in order to avoid the real submission (Test purposes)
    e.preventDefault(); 
    alert('Submitted!')
    
  })
  
  $("#upload").change(function(){
    $("#myform").submit();
  }); 

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form action="example.html" method="post" id="myform" enctype="multipart/form-data">
    <input type="file" name="upload" id="upload">
    <button id="browse">Upload</button>
</form>

Remember to remove the "preventDefault" and the "alert" lines that I included in order to execute the code snippet without redirect you to another page.

Juan Lago
  • 686
  • 8
  • 17
  • You can submit also the form using an AJAX request: http://stackoverflow.com/questions/1960240/jquery-ajax-submit-form – Juan Lago Mar 29 '16 at 16:27