-4

How do I post and returned images when the div(not submit button) is clicked without refreshing the page?

  <html>
    <head>
      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    </head>
    <body>

  <input multiple class="fileInput" type="file" id="files" name="files[]"/>
  <br>
  <div id="submit" > click me to pass the photo to upload.php</div>
  <div name="photoreturn"></div>
</body>
</html>



<style>
#submit{
    background-color: #ffcc99;
    display:inline-block;
    padding:5px;
    border-radius: 3px;
    cursor:pointer;
}
</style>

2 Answers2

0

Use AJAX. Everybody does that.

$("body").on("click", "#submit", function(e) {
  e.preventDefault();
  post_image();
});

function post_image() {
  var img = find("input#files").val();

   $.ajax({
     url: './your_dir_here/upload.php',
     type: 'POST',
     data: img,
     dataType: 'json',
     success: function(data) {
        $("#photoreturn").fadeIn("fast");
        alert("img uploaded");
     },
   }); // End of ajax call 
}

Something like that.

NOTE: I haven't tried running the code, you might get an error but that's the idea. Good luck!

Hard Spocker
  • 765
  • 11
  • 32
0

You can call ajax function by adding onclick event on div

 <div id="submit" onclick="uploadImage()" > click me to pass the photo to upload.php</div>

ajax function

fuction uploadImage(){

file_data=$('#files').val();

 $.ajax({
    url: 'uplaod.php', //call your upload fuction/page 
    type: 'post',
    dataType: 'json', //return type from given url called function
    data: 'files=' + file_data, // pass the field data        
    success: function(json) {
        //fetch the success message here...
        alert('successfully uploaded');
    }
    error: function(xhr, ajaxOptions, thrownError) {
        alert('something went wrong');
    }
});

}