78

Q.1 I would like to convert this form to ajax but it seems like my ajax code lacks something. On submit doesn't do anything at all.

Q2. I also want the function to fire on change when the file has been selected not to wait for a submit.

Here is JS.

$('#imageUploadForm').on('submit',(function(e) {
    e.preventDefault()
    $.ajax({
        type:'POST',
        url: $(this).attr('action'),
        data:$(this).serialize(),
        cache:false
    });
}));

and the HTMl with php.

<form name="photo" id="imageUploadForm" enctype="multipart/form-data" action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">
    <input type="file" style="widows:0; height:0" id="ImageBrowse" hidden="hidden" name="image" size="30"/>
    <input type="submit" name="upload" value="Upload" />
    <img width="100" style="border:#000; z-index:1;position: relative; border-width:2px; float:left" height="100px" src="<?php echo $upload_path.$large_image_name.$_SESSION['user_file_ext'];?>" id="thumbnail"/>
</form>
aug born
  • 248
  • 1
  • 3
  • 20
Relm
  • 7,923
  • 18
  • 66
  • 113
  • 1
    You may need to use `FormData()` to send images with `ajax`. http://stackoverflow.com/a/8244082/2220391 – Spokey Oct 18 '13 at 10:33
  • i'll uoload the php file this form is using if needed. – Relm Oct 18 '13 at 10:35
  • It's not the `PHP` code. You need to append the files to `FormData()` in order to send them with `ajax` – Spokey Oct 18 '13 at 10:39
  • This link might help u mate which is done using ajaxform.. http://stackoverflow.com/questions/19221647/how-to-copy-the-source-src-to-folder-using-ajax/19222320#19222320 – Nibin Oct 18 '13 at 10:40
  • You can't upload files using ajax alone. – Ben Fortune Oct 18 '13 at 10:50
  • there's php. as you can see ajax is calling some action. – Relm Oct 18 '13 at 10:59
  • What people trying to say is, apart from posting form to some action url with default form submit, you cannot send files to anywhere without using FormData. Note that FormData does not exist on many versions -including late ones- of ie. – Quad Oct 18 '13 at 11:35
  • @BenFortune: Yes he can. At least if he's using a somewhat modern browser (i.e. not oldIE). – ThiefMaster Oct 19 '13 at 11:33
  • I highly recommend this plugin for jQuery for uploading items over AJAX. jQuery Form Plugin: http://malsup.com/jquery/form/ – Luke Oct 18 '13 at 12:08

6 Answers6

116

first in your ajax call include success & error function and then check if it gives you error or what?

your code should be like this

$(document).ready(function (e) {
    $('#imageUploadForm').on('submit',(function(e) {
        e.preventDefault();
        var formData = new FormData(this);

        $.ajax({
            type:'POST',
            url: $(this).attr('action'),
            data:formData,
            cache:false,
            contentType: false,
            processData: false,
            success:function(data){
                console.log("success");
                console.log(data);
            },
            error: function(data){
                console.log("error");
                console.log(data);
            }
        });
    }));

    $("#ImageBrowse").on("change", function() {
        $("#imageUploadForm").submit();
    });
});
Sohil Desai
  • 2,940
  • 5
  • 23
  • 35
  • 1
    This is not sending the input file to the PHP file. I'm trying to print the name or type of the file using console.log and I'm not getting any data. – napstercake Feb 18 '14 at 14:34
  • 2
    It seems sends 'formData' variable in that way is wrong without use 'processData: false' because the jQuery processes 'data' converting it into a string. If you run that code you'll get an error. Still this not solve the problem to get the file into the php file. I've found 'jquery.form.min.js' library to handle this kind of input into the submit process of a form. In this context you should use $(imageUploadForm').ajaxSubmit(); – napstercake Feb 19 '14 at 15:24
  • yes that's true sorry I forgot to mention that. check my answer now. – Sohil Desai Feb 20 '14 at 04:24
  • @Jek-fdrv: According to me it should work on IE9 but I have not tested it on IE9 because I use linux so don't have IE. What error you got in IE9? – Sohil Desai Aug 18 '14 at 11:20
  • but page is still refreshing – Kashyap Patel Apr 21 '15 at 07:27
  • To make this work properly the onsubmit function should return false to prevent the form from being submitted on some browsers (with undesirable results such as the page refresh Developer is experiencing). – pizzamonster Oct 09 '15 at 18:23
  • I thinks this will help you guys. FormData support starts from following desktop browsers versions. IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+ For more detail, see MDN link https://developer.mozilla.org/en-US/docs/Web/API/FormData – Sohil Desai May 19 '17 at 07:25
  • Working fine with Symfony3 on Mozilla and Chrome. Nice! – Isaac Bosca Jun 28 '17 at 12:31
  • Hi, I need to get respond from server via data and I need to set dataType to json while uploading image, but when I just add dataType it occures error. Can you help me? – SenTisso Sep 06 '18 at 17:09
  • @SohilDesai, this is valuable answer, btw when I implement this FormData not containing any data in it, what am I missed? form contains one input file only. – brucelin Oct 04 '18 at 20:15
  • @SenTisso : please make sure you are sending data into json only from server to this ajax. Still gets an error you might need to debug on error, what its meaning. – Sohil Desai Dec 22 '18 at 08:51
  • @brucelin : if your form doesn't contain any data, what you will be posting on server? – Sohil Desai Dec 22 '18 at 08:51
24

HTML Code

<div class="rCol"> 
     <div id ="prv" style="height:auto; width:auto; float:left; margin-bottom: 28px; margin-left: 200px;"></div>
       </div>
    <div class="rCol" style="clear:both;">

    <label > Upload Photo : </label> 
    <input type="file" id="file" name='file' onChange=" return submitForm();">
    <input type="hidden" id="filecount" value='0'>

Here is Ajax Code:

function submitForm() {

    var fcnt = $('#filecount').val();
    var fname = $('#filename').val();
    var imgclean = $('#file');
    if(fcnt<=5)
    {
    data = new FormData();
    data.append('file', $('#file')[0].files[0]);

    var imgname  =  $('input[type=file]').val();
     var size  =  $('#file')[0].files[0].size;

    var ext =  imgname.substr( (imgname.lastIndexOf('.') +1) );
    if(ext=='jpg' || ext=='jpeg' || ext=='png' || ext=='gif' || ext=='PNG' || ext=='JPG' || ext=='JPEG')
    {
     if(size<=1000000)
     {
    $.ajax({
      url: "<?php echo base_url() ?>/upload.php",
      type: "POST",
      data: data,
      enctype: 'multipart/form-data',
      processData: false,  // tell jQuery not to process the data
      contentType: false   // tell jQuery not to set contentType
    }).done(function(data) {
       if(data!='FILE_SIZE_ERROR' || data!='FILE_TYPE_ERROR' )
       {
        fcnt = parseInt(fcnt)+1;
        $('#filecount').val(fcnt);
        var img = '<div class="dialog" id ="img_'+fcnt+'" ><img src="<?php echo base_url() ?>/local_cdn/'+data+'"><a href="#" id="rmv_'+fcnt+'" onclick="return removeit('+fcnt+')" class="close-classic"></a></div><input type="hidden" id="name_'+fcnt+'" value="'+data+'">';
        $('#prv').append(img);
        if(fname!=='')
        {
          fname = fname+','+data;
        }else
        {
          fname = data;
        }
         $('#filename').val(fname);
          imgclean.replaceWith( imgclean = imgclean.clone( true ) );
       }
       else
       {
         imgclean.replaceWith( imgclean = imgclean.clone( true ) );
         alert('SORRY SIZE AND TYPE ISSUE');
       }

    });
    return false;
  }//end size
  else
  {
      imgclean.replaceWith( imgclean = imgclean.clone( true ) );//Its for reset the value of file type
    alert('Sorry File size exceeding from 1 Mb');
  }
  }//end FILETYPE
  else
  {
     imgclean.replaceWith( imgclean = imgclean.clone( true ) );
    alert('Sorry Only you can uplaod JPEG|JPG|PNG|GIF file type ');
  }
  }//end filecount
  else
  {    imgclean.replaceWith( imgclean = imgclean.clone( true ) );
     alert('You Can not Upload more than 6 Photos');
  }
}

Here is PHP code :

$filetype = array('jpeg','jpg','png','gif','PNG','JPEG','JPG');
   foreach ($_FILES as $key )
    {

          $name =time().$key['name'];

          $path='local_cdn/'.$name;
          $file_ext =  pathinfo($name, PATHINFO_EXTENSION);
          if(in_array(strtolower($file_ext), $filetype))
          {
            if($key['name']<1000000)
            {

             @move_uploaded_file($key['tmp_name'],$path);
             echo $name;

            }
           else
           {
               echo "FILE_SIZE_ERROR";
           }
        }
        else
        {
            echo "FILE_TYPE_ERROR";
        }// Its simple code.Its not with proper validation.

Here upload and preview part done.Now if you want to delete and remove image from page and folder both then code is here for deletion. Ajax Part:

function removeit (arg) {
       var id  = arg;
       // GET FILE VALUE
       var fname = $('#filename').val();
       var fcnt = $('#filecount').val();
        // GET FILE VALUE

       $('#img_'+id).remove();
       $('#rmv_'+id).remove();
       $('#img_'+id).css('display','none');

        var dname  =  $('#name_'+id).val();
        fcnt = parseInt(fcnt)-1;
        $('#filecount').val(fcnt);
        var fname = fname.replace(dname, "");
        var fname = fname.replace(",,", "");
        $('#filename').val(fname);
        $.ajax({
          url: 'delete.php',
          type: 'POST',
          data:{'name':dname},
          success:function(a){
            console.log(a);
            }
        });
    } 

Here is PHP part(delete.php):

$path='local_cdn/'.$_POST['name'];

   if(@unlink($path))
   {
     echo "Success";
   }
   else
   {
     echo "Failed";
   }
RITU
  • 279
  • 3
  • 6
2

You can use jquery.form.js plugin to upload image via ajax to the server.

http://malsup.com/jquery/form/

Here is the sample jQuery ajax image upload script

(function() {
$('form').ajaxForm({
    beforeSubmit: function() {  
        //do validation here


    },

    beforeSend:function(){
       $('#loader').show();
       $('#image_upload').hide();
    },
    success: function(msg) {

        ///on success do some here
    }
}); })();  

If you have any doubt, please refer following ajax image upload tutorial here

http://www.smarttutorials.net/ajax-image-upload-using-jquery-php-mysql/

Musa
  • 96,336
  • 17
  • 118
  • 137
muni
  • 1,362
  • 2
  • 19
  • 21
0
Image upload using ajax and check image format and upload max size   

<form class='form-horizontal' method="POST"  id='document_form' enctype="multipart/form-data">
                                    <div class='optionBox1'>
                                        <div class='row inviteInputWrap1 block1'>
                                            <div class='col-3'>
                                                <label class='col-form-label'>Name</label>
                                                <input type='text' class='form-control form-control-sm' name='name[]' id='name' Value=''>
                                            </div>
                                            <div class='col-3'>
                                                <label class='col-form-label'>File</label>
                                                <input type='file' class='form-control form-control-sm' name='file[]' id='file' Value=''>
                                            </div>
                                            <div class='col-3'>
                                                <span class='deleteInviteWrap1 remove1 d-none'>
                                                    <i class='fas fa-trash'></i>
                                                </span>
                                            </div>
                                        </div>
                                        <div class='row'>
                                             <div class='col-8 pl-3 pb-4 mt-4'>
                                                <span class='btn btn-info add1 pr-3'>+ Add More</span>
                                                 <button class='btn btn-primary'>Submit</button> 
                                            </div>
                                        </div>
                                    </div>
                                    </form>     
                                    
                                    </div>  
                      
    
      $.validator.setDefaults({
       submitHandler: function (form) 
         {
               $.ajax({
                    url : "action1.php",
                    type : "POST",
                    data : new FormData(form),
                    mimeType: "multipart/form-data",
                    contentType: false,
                    cache: false,
                    dataType:'json',
                    processData: false,
                    success: function(data)
                    {
                        if(data.status =='success')
                            {
                                 swal("Document has been successfully uploaded!", {
                                    icon: "success",
                                 });
                                 setTimeout(function(){
                                    window.location.reload(); 
                                },1200);
                            }
                            else
                            {
                                swal('Oh noes!', "Error in document upload. Please contact to administrator", "error");
                            }   
                    },
                    error:function(data)
                    {
                        swal ( "Ops!" ,  "error in document upload." ,  "error" );
                    }
                });
            }
      });
    
      $('#document_form').validate({
        rules: {
            "name[]": {
              required: true
          },
          "file[]": {
              required: true,
              extension: "jpg,jpeg,png,pdf,doc",
              filesize :2000000 
          }
        },
        messages: {
            "name[]": {
            required: "Please enter name"
          },
          "file[]": {
            required: "Please enter file",
            extension :'Please upload only jpg,jpeg,png,pdf,doc'
          }
        },
        errorElement: 'span',
        errorPlacement: function (error, element) {
          error.addClass('invalid-feedback');
          element.closest('.col-3').append(error);
        },
        highlight: function (element, errorClass, validClass) {
          $(element).addClass('is-invalid');
        },
        unhighlight: function (element, errorClass, validClass) {
          $(element).removeClass('is-invalid');
        }
      });
    
      $.validator.addMethod('filesize', function(value, element, param) {
         return this.optional(element) || (element.files[0].size <= param)
        }, 'File size must be less than 2 MB');
Vikas kumar
  • 87
  • 1
  • 4
0

   $(document).on('change', '#photo', function() {
      var property = document.getElementById('photo').files[0];
      var image_name = property.name;
      var image_extension = image_name.split('.').pop().toLowerCase();
      var url = './services/userProfile.php';
      if (jQuery.inArray(image_extension, ['jpg', 'jpeg', 'png']) == -1) {
        $('#msg').html('Invalid image file');
        return false;
      }
      var form_data = new FormData();
      form_data.append("file", property);
      $.ajax({
        url: url,
        method: 'POST',
        data: form_data,
        contentType: false,
        cache: false,
        processData: false,
        beforeSend: function() {
          $('#msg').html('Loading......');
        },
        success: function(data) {
          const obj = JSON.parse(data);
          $('.image').attr('src', 'upload/' + obj['data']);
          $('#msg').html(obj['msg']);
        }
      });
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form" action="" method="post" enctype="multipart/form-data">
          <img src="upload/imag.jpg" class="mx-auto img-fluid img-circle d-block image" alt="avatar">
          <h6 class="mt-2">Upload a different photo</h6>
          <label class="custom-file">
            <input type="file" id="photo" name="profilePicture" class="custom-file-input">
            <span class="custom-file-control">Choose file</span>
          </label>
          <span id="msg" style="color:red"></span>
        </form>
-1

Here is simple way using HTML5 and jQuery:

1) include two JS file

<script src="jslibs/jquery.js" type="text/javascript"></script>
<script src="jslibs/ajaxupload-min.js" type="text/javascript"></script>

2) include CSS to have cool buttons

<link rel="stylesheet" href="css/baseTheme/style.css" type="text/css" media="all" />

3) create DIV or SPAN

<div class="demo" > </div>

4) write this code in your HTML page

$('.demo').ajaxupload({
    url:'upload.php'
});

5) create you upload.php file to have PHP code to upload data.

You can download required JS file from here Here is Example

Its too cool and too fast And easy too! :)

Paras Pitroda
  • 208
  • 1
  • 10