0

I have a simple upload image form...

 <form id="form" action="upload-image-ajax.php" method="post" enctype="multipart/form-data">
  <input id="uploadImage" type="file" accept="image/*" name="image" />
  <input id="button" type="submit" value="Upload">
 </form>

And some JS...

$(document).ready(function (e) {
 $("#form").on('submit',(function(e) {
  e.preventDefault();
  $.ajax({
         url: "upload-image-ajax.php",
   type: "POST",
   data:  new FormData(this),
   contentType: false,
         cache: false,
   processData:false,
   beforeSend : function()
   {
    //$("#preview").fadeOut();
    $("#err").fadeOut();
   },
   success: function(data) {
    if(data=='invalid file') {
     // invalid file format.
     $("#err").html("Invalid File !").fadeIn();
    } else {
     // view uploaded file.
     $("#preview").html(data).fadeIn();
     $("#form")[0].reset(); 
    }
      },
     error: function(e) 
      {
    $("#err").html(e).fadeIn();
      }          
    });
 }));
});

And the PHP (upload-image-ajax.php) ...

<?php
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'bmp'); // valid extensions
$path = 'uploads/'; // upload directory

if(isset($_FILES['image']))
{
 $img = $_FILES['image']['name'];
 $tmp = $_FILES['image']['tmp_name'];

 // get uploaded file's extension
 $ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));

 // can upload same image using rand function
 $final_image = $_SESSION['poolid']. "." .$ext;

 // check's valid format
 if(in_array($ext, $valid_extensions))  {     
  $path = $path.strtolower($final_image); 
    //checking if file exsists, so we can overwrite it
    if(file_exists("uploads/$final_image")) unlink("uploads/$final_image");
      if(move_uploaded_file($tmp,$path)) {
       echo "<img src='$path' />";
      }
 } else {
      echo 'invalid file';
 }
}

?>

The problem is that I'd like this image upload "form" to be included in a larger form. But when you click "upload" it tries to submit the larger, overall form. Is there a way to edit this to maybe just have a button HTML element (not a true submit button) and when that gets clicked, it performs the same AJAX call?

Or does AJAX need to occur as a result of a true form submission?

FYI, when you upload the image, it sends to server and shows a preview. So I'd like it to be part of a larger form with other questions. This is just one "question" where they can upload an image and see the preview BEFORE clicking to submit the overall, larger form.

user3304303
  • 997
  • 7
  • 25
  • 1
    You can run on click. $('#id of button or link').on('click', function(){ do ajax call here}); – Chris Oct 26 '16 at 20:25
  • Nested `
    `s are not allowed in html.
    – tcooc Oct 26 '16 at 20:28
  • @mark.hch answer is very correct. I would suggest you add `$("#ImageForm").submit();` after `e.preventDefault()`. – Endi Zhupani Oct 26 '16 at 20:28
  • mark and endi are both wrong. your event is fine. https://jsfiddle.net/mx7rqvad/ – I wrestled a bear once. Oct 26 '16 at 20:31
  • Why do you have your action in the form that is the same file as your ajax url? – Jeff Oct 26 '16 at 20:36
  • If this form is nested inside another form as you say, then [`e.stopPropagation();`](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation) should stop the event from propagating up to the parent form. – War10ck Oct 26 '16 at 20:37
  • @jeff, I was wondering that too haha. FYI, I got this script from this site: http://www.codingcage.com/2015/12/easy-ajax-image-upload-with-jquery-php.html Maybe it's a questionable overall script? because that does seem strange to have the ajax URL in two places. – user3304303 Oct 26 '16 at 20:46

3 Answers3

0

Make your button: <button id="button">Upload</button>

Then add a jquery event listener:

$("#button").click(function(){
    //Make ajax call here:
    $.ajax({
           url: upload-image-ajax.php,
           type: 'POST',
           contentType: '[Type of the content being returned]',
           data: [json object with data you're sending. i.e the photo file],
           success: function(){ callback function for when call completes}
     });
});

There are more options to do whatever you'd like. Look at http://api.jquery.com/jquery.ajax/ for more info.

PLan
  • 133
  • 7
0

To upload just image, change button type to button from submit and try like this:

$('#button').on('click', function() {
    var imageData = new FormData();
    imageData.append('name_of_picture_file', $('#uploadImage').prop('files')[0]);

    $.ajax({
      url: 'upload-image-ajax.php',
      type: 'POST',
      processData: false, // important
      contentType: false, // important
      dataType : 'json',
      data: imageData
    });
});

And your html should look like

<form id="largerForm" action="upload-larger-form.php" method="post">
  <input id="uploadImage" type="file" accept="image/*" name="image" />
  <input id="button" type="button" value="Upload">
</form>
Soham
  • 1,271
  • 7
  • 15
0

As I understand your question as I can reach, you have two main requirements.

  1. You want to upload the files from your page with ajax.
  2. You want to show preview to them

For the first requirement, you can use following script.

 <html>
 <head>
     <script src="jquery-1.9.1.min.js"></script>

 </head>
 <body>
    <div id="main">
    <input type="file" id="file-select" multiple webkitdirectory/>

        <button id="btn-upload" ><span class="glyphicon glyphicon-upload">   </span> Upload</button>
    </div>

  <script>

    var fileSelect = document.getElementById('file-select');


    $(document).ready(function () {

        //Listen the upload button onclick
        $('#btn-upload').on("click",function(){

            event.preventDefault();

            //Check if contains files to upload

            if(fileSelect.files.length != 0){

                //Declare a FormData Object to pass the files
                var formData = new FormData();
                var fileCount = fileSelect.files.length;

                //Add the files from file-select into FormData                  
                for (var i = 0; i < fileCount; i++)
                {
                    var file = fileSelect.files[i];
                    formData.append("FileUpload", file);
                }

          //Make the ajax post request with FormData to your destination(eg:webservice or php page)

                $.ajax({
                    type: 'POST',
                    url: 'http://yourhost:port/something.php', 
                    data: formData,
                    contentType:false,
                    processData: false,
                    success: function (data) {
                        //Do the next process u want
                    },
                    error: function(err){
                        //Process the error
                    }

                });
            }

      });
    });
   </script>
 </body>
 </html>

The above file upload function will work when you click upload button, not of form submit.

For the second requirement, refer to this question Preview an image before it is uploaded

Goodluck.

Community
  • 1
  • 1
Sithu Kyaw
  • 343
  • 1
  • 3
  • 14