0

I'm working with Ajax, PHP.

I want to upload an image without clicking the submit button and I'm using the approach described in this answer: How to upload file using jquery ajax and php (without clicking any submit button)

But it's not working. Do I need to change the data type or something else?

Here's my code:

jQuery/Ajax

$(document).ready(function(){
var b = new FormData($(this).closest("form")[0]);
b.append('image', $('input[type=file]')[0].files[0]);
  $("#imgInput").change(function(){
    $.ajax({
      url: "test.php",
      type: "post",
      datatype: 'json',
      processData: false,
      contentType: false,
      data: b,
      success: function(text){
        if(text== "success"){
          alert("Image uploaded");
        }
      },
      error: function(){
        alert("Not uploaded");
      }
    });
  });
});

test.php

<?php
  $filename=$_FILES["image"]["name"];
  $filetmp=$_FILES["image"]["tmp_name"];
  $filetype=$_FILES["image"]["type"];
  $filepath="images/".$filename;
  move_uploaded_file($filetmp, $filepath);
?>

HTML

<form name="form1" method="post" enctype="multipart/form-data">
  <table>
    <tr>
      <td><input type="text" name="name" placeholder="Enter your name" /></td>
      <td rowspan="3"><div class="propic"><img id="" /></div>
        <input id="imgInput" type="file" name="image" /></td>
    </tr>
    <tr>
      <td><input type="text" name="username" placeholder="Enter username"/></td>
    </tr>
    <tr>
      <td><input id="digits" type="text" name="phone" maxlength="10" placeholder="Enter your phone no."/></td>
    </tr>
    <tr>
      <td><input type="password" name="password" maxlength="12" placeholder="Enter password"/></td>
      <td><input id="button" type="submit" name="submit" value="Sign Up" /></td>
    </tr>
  </table>
</form>
Community
  • 1
  • 1
Vikas Kumar
  • 571
  • 3
  • 6
  • 16

2 Answers2

1

You need to use FormData() to send files to server through AJAX. Change your script to:

$.ajax({ 
    url: "test.php",
    type: "POST",
    data: new FormData($(this).closest("form")[0]),  // This is the main place you need.
    contentType : false,
    async: false,
    processData: false,
    cache: false,
    success: function(text) {
        if(text== "success"){
          alert("Image uploaded");
        }
    }
});
Praveen Kumar Purushothaman
  • 154,660
  • 22
  • 177
  • 226
1

If you are just looking to get it working, I recommend Ravishanker Kusuma's Hayageek jQuery File Upload plugin. I don't usually recommend plugins, but this one is excellent. It does almost all the work for you.

http://hayageek.com/docs/jquery-upload-file.php

He breaks down the process into four simple steps, that basically look like this:

Look for //1 //2 //3:

<head>
  // (1) Load the js files (note that it requires jQuery, which we also load)
    <link href="http://hayageek.github.io/jQuery-Upload-File/uploadfile.min.css" rel="stylesheet">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="http://hayageek.github.io/jQuery-Upload-File/jquery.uploadfile.min.js"></script>   // (1)
</head>
<body>
    <div id="fileuploader">Upload</div>  // (2) Create DIV
    <script>
        $(document).ready(function(){
            $("#fileuploader").uploadFile({  // (3) initialize plugin
                url:"my_php_processor.php",
                fileName:"myfile"
            });
        });
    </script>
</body>

The final (fourth) step is to create a PHP file with same name as specified above in the jQuery code (in this case my_php_processor.php) to receive and process the file:

my_php_processor.php:

<?php
    $output_dir = "uploads/";
    $theFile = $_FILES["myfile"]["name"];
    move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$fileName);

Note the relationship between myfile in the PHP ($_FILES["myfile"]), and the filename myfile specified in the jQuery code block.

On the Hayageek web page, study the upload.php example on the Server tab.

Note that you can also pass additional variables to the my_php_processor.php processor file by using dynamicFormData. See this other example:

$("#fileuploader").uploadFile({
    url:"my_php_processor.php",
    fileName:"myfile",
    dynamicFormData: function(){
        return {
            //my_php_processor.php will receive POST vars below
            newSubj: $("#newSubj").val(),
            newBody: $("#newBody").val(),
        };
    },
    onSuccess:function(files,data,xhr,pd){
        //files: list of files
        //data: response from server
        //xhr : jquery xhr object
        alert(xhr.responseText); //displays data ECHOd by `my_php_processor.php`
    }
});

my_php_processor.php:

<?php
    $n = $_POST['newSubj'];
    $b = $_POST['newBody'];
    $uploadedFile = $_FILES["myfile"]["name"];
    //etc.
    echo 'This will display in the alert box';

jsFiddle Sample Code - Click on Image Example

marc_s
  • 675,133
  • 158
  • 1,253
  • 1,388
cssyphus
  • 31,599
  • 16
  • 79
  • 97
  • This looks nice. Will this work when the image is selected? :) – Praveen Kumar Purushothaman Mar 24 '16 at 14:19
  • What do you mean, `when the image is selected`? If you mean, can you trigger a pop-up displaying the jQuery File Upload field/button by clicking on a displayed image, then yes -- extremely similar to jsFiddle Sample Code in my answer. ***See additional jsFiddle in answer*** If you mean, will this plugin work with images, then yes -- and you can specify what file/image types to accept or not to accept. Amazing plugin. Read Kusuma's web site carefully - he covers everything using very few words. – cssyphus Mar 24 '16 at 16:25
  • To restrict allowed file types accepted by plugin, see http://stackoverflow.com/questions/11832930/html-input-file-accept-attribute-file-type-csv – cssyphus Mar 24 '16 at 16:32
  • Nice. Thanks for the explanation. – Praveen Kumar Purushothaman Mar 24 '16 at 18:08