1

I have a form like this:

<form method="post" class="form_cnvc">
   <p><input type="text" name="f_nm" value="" placeholder="type your first name"></p>
   <p><input type="text" name="l_nm" value="" placeholder="type your last name"></p>
   <div class="dropfile visible-lg">
   <input type="file" id="image_file_input" name="image_file_input">
   <span>Select Images(.jpg , .png, .bmp files) </span>
   </div>
   <p class="submit"><input type="submit" name="submit" value="post"></p>
 </form>

I want that when the user will selects an image, it would be automatically submitted to my PHP page so that I can save it in the database and return an insert_id with the thumbnail of the picture.

I want to do it using jQuery but not able to do so.

PHP code is:

user3177114
  • 57
  • 1
  • 2
  • 8
  • 1
    You shouldnt do something like that. Its rly annoying when you upload things you dont even want to because you misclicked for example. I would always recommend to upload via button. – Realitätsverlust Jan 16 '14 at 14:45

1 Answers1

5

Easy, use a change trigger on your input Element and do an ajax-request inside:

$("#image_file_input").change(function() { 
    $.ajax({
        url: "my-target-url.php",
        type: "post",
        dataType: 'json',
        processData: false,
        contentType: false,
        data: {file: $("#image_file_input").val()},
        success: function(text) {
            if(text == "success") {
                alert("Your image was uploaded successfully");
            }
        },
        error: function() {
            alert("An error occured, please try again.");         
        }
    });   
});

Create a url or route and enter it at url: tag (domain/file.php) and then code serversided stuff:

function processFileUpload() {
    if(count($_FILES) > 0) {
        foreach($_FILES as $file) {
            //DO whatever you want with your file, save it in the db or stuff...
            //$file["name"];
            //$file["tmp_name"];
            //Insert here bla blubb
            echo "success";
        }
    }
    die();
}
Steini
  • 2,753
  • 15
  • 24
  • 1
    You can't upload files using ajax alone without some sort of BLOB data, which can be created using the HTML5 file API. – Ben Fortune Jan 16 '14 at 15:02
  • @up Just noticed one error in my script, $(#image_file_input).val() should be: $("#image_file_input").val() -> quotes were missing I edited the post. However If its still not working you should post some more output, errors, watch JavaScript console of your browser and try if the script on PHP side is called at all. Locate the error and provide me more information. – Steini Mar 24 '16 at 15:20
  • @Steini dataType: 'json' is generating conflicts with php answer also data: {file: $("#image_file_input").val()}, does not seem to correspond to PHP $_FILES that said, thank you a lot for the tips – bysanchy Jul 21 '16 at 23:00