Form Template – Upload Photos

HTML:

<form action="http://xxx.xxx.com/index.php/api/products/photo/product_photo" method="post" accept-charset="utf-8" id="product_photo_form" enctype="multipart/form-data">
	<div class="upload">
	  <input type="file" name="product_photo[]" value="" id="product_photo" class="upload_field" multiple="multiple">              
	  <button class="button bt_upload active">Upload</button>
	  <div class="overlay"></div>
	</div>
	<input type="hidden" id="post_id" name="post_id" value="27">
</form>

<div id="thumbs_container">
	<div id="thumbs_wrapper">
	  <ul class="photos">
		
	  </ul>
	</div>
	<div class="clearfix"></div>
	<a href="#" id="post_nav_left" class="carousel_nav left"></a>
	<a href="#" id="post_nav_right" class="carousel_nav right"></a>
</div>

CSS:

.upload .upload_field{
	/* Note: display:none on the input won't trigger the click event in WebKit.
    Setting visibility: hidden and height/width:0 works great. 
    
https://ericbidelman.tumblr.com/post/14636214755/making-file-inputs-a-pleasure-to-look-at
*/ visibility: hidden; width: 0; height: 0; }

Javascript:

var post_fun = {
  init: function(){
    var wrapper = this; 

    $('#win_new_post .bt_submit').on('click', function(e){
      e.preventDefault();
      var post_id = $('#win_new_post #post_id').val();

      if(parseInt(post_id) > 0){
        wrapper.update(post_id);
      }else{
        wrapper.create();
      }
    });

    $('#win_new_post .photos').delegate('li .remove', 'click', function(e){
      e.preventDefault();
      var $this = $(this);
      var $li = $this.parent('li');
      var id = $this.attr('data-id');
      if(confirm('Are you sure to remove this image?')){
        wrapper.remove_image(id, $li);
      }
    });

    wrapper.init_posts();
    wrapper.init_upload_form();
  }, 
  photos: function(){
    var $list = $('#win_new_post .left .photos li a');
    var photos = [];
    $list.each(function(index){
      var $this = $(this);
      photos.push($this.attr('data-id'));
    });

    return photos;
  },
  init_upload_form: function(){
    var wrapper = this;
    var $form = $('#product_photo_form');
    var $upload_field = $('#product_photo');
    var $upload_button = $('#win_new_post .bt_upload');
    var $submit_button = $form.find('.bt_submit');
    var $overlay = $('#win_new_post .upload .overlay');

    $upload_button.on('click', function(e){
      e.preventDefault();
      $upload_field.trigger('click');
    });

    //No submit button for now
    $submit_button.on('click', function(e){
      e.preventDefault();
      $form.submit();
    });

    $upload_field.on('change', function(){
      var value = $(this).val();
      //console.log('file selected: ' + value);return;
      if(value != null && value.length > 0 && $upload_button.hasClass('processing') == false){
        $overlay.addClass('active');
        $form.submit();
        $upload_button.text('Uploading...')
      }
    });

    $form.submit(function() { 
      $(this).ajaxSubmit({
          beforeSubmit: function(arr, $form, options) {
              for(var i = 0; i < arr.length; i++){
                  var obj = arr[i];
   
                  if(obj.required == true && (obj.value == null || obj.value == '')){
                      alert('Please enter all required fields');
                      return false;
                  }
              }
   
              //$('#bt_submit').text('Processing...').attr('disabled', true);
              return true;
          }, 
          data: {
              
          }, 
          success: function(data, statusText, xhr, $form) { 
            //console.log(data);
            //return;
            if(typeof data.status == 'undefined'){
                show_msg('Error', data);
            }else if(data.status == 'success'){
                $overlay.removeClass('active');
                $upload_button.text('Upload').removeClass('processing');
                wrapper.append_thumb(data.response);
            }else{
                show_msg('Error', data.response);
            }
            
            $form[0].reset();
          }, 
          error: function(){
              alert("ERROR");
          }
      }); 
   
      return false; 
    });
  }, 
  show_post_win: function(){
    var wrapper = this;
    var $win = $('#win_new_post');

    $win.find('#product_name').val('');
    $win.find('#product_desc').val('');
    $win.find('#price').val('');
    $win.find('#quantity').val('');
    $win.find('#post_id').val('');

    wrapper.init_carousel();

    var $societies = $('#win_new_post .societies');
    $societies.find('li a').addClass('active');

    $win.wlightbox('show');
  },
  init_carousel:function(){
    var $carousel = $('#win_new_post .left .photos').children().remove().end();
    $carousel.trigger('destroy');
    $carousel.carouFredSel({
      direction: 'left', 
      circular: false,
      infinite: false,
      auto    : false,
      prev    : { 
          button  : "#post_nav_left",
          key     : "left"
      },
      next    : { 
          button  : "#post_nav_right",
          key     : "right"
      }, 
      items:{
          visible: 4
      }
    });
  },
  append_thumb: function(data){
    var $carousel = $('#win_new_post .left .photos');

    for(var i = 0; i < data.length; i++){
      var item = data[i];

      var file_name = item.file_name;
      if(typeof file_name == 'undefined') file_name = item.name;

      var thumb = base_url + item.url + 'thumb/' + file_name;
      var large = base_url + item.url + file_name;

      var new_item = '<li><a href="' + large + '" data-id="' + item.image_id + '" class="fancybox" rel="post_win_gallery"><img src="' + thumb + '" /></a><a href="#" class="remove" data-id="' + item.image_id + '"></a></li>';
      
      $carousel.trigger('insertItem', new_item);
    }

    $carousel.find(".fancybox").fancybox();
  }, 
  create: function(callback){
    var wrapper = this;
    var params = {
      title: $('#product_name').val(), 
      description:$('#product_desc').val(), 
      featured_image_id:$('#thumbs_wrapper .photos li:first a').attr('data-id'), 
      price:$('#price').val(), 
      currency:$('#currency').val(), 
      quantity:$('#quantity').val(), 
      url:$('#url').val(), 
      photos: wrapper.photos(), 
      societies: wrapper.checked_societies()
    }

    loading.show();
    $.ajax(base_url + 'index.php/api/products/create', {
        type: 'post',
        data: params,
        success: function(data, textStatus, jqXHR){
          //console.log(data);return;
          if(data.status == 'fail'){
            alert(data.message);
          }else{
            $('#win_new_post').wlightbox('hide');

            if(typeof callback == 'function'){
              callback.call(wrapper, data.response);
            }else{
              window.location.reload();
            }
          }
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert('Error:' + jqXHR.responseText + '; ' + textStatus);
        }
    });
  }, 
  update: function(post_id, callback){
    var wrapper = this;
    var params = {
      product_id: post_id, 
      title: $('#product_name').val(), 
      description:$('#product_desc').val(), 
      featured_image_id:$('#thumbs_wrapper .photos li:first a').attr('data-id'), 
      price:$('#price').val(), 
      currency:$('#currency').val(), 
      quantity:$('#quantity').val(), 
      url:$('#url').val(), 
      societies: wrapper.checked_societies()
    }

    loading.show();
    $.ajax(base_url + 'index.php/api/products/update', {
        type: 'post',
        data: params,
        success: function(data, textStatus, jqXHR){
          //console.log(data);return;
          if(data.status == 'fail'){
            alert(data.message);
          }else{
            $('#win_new_post').wlightbox('hide');

            if(typeof callback == 'function'){
              callback.call(wrapper, data.response);
            }else{
              window.location.reload();
            }
          }
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert('Error:' + jqXHR.responseText + '; ' + textStatus);
        }
    });
  }, 
  single: function(post_id, callback){
    var wrapper = this;
    var params = {
      
    }

    $.ajax(base_url + 'index.php/api/products/single/' + post_id, {
        type: 'get',
        data: params,
        success: function(data, textStatus, jqXHR){
          //console.log(data);
          if(data.status == 'fail'){
            alert(data.message);
          }else{
            if(typeof callback == 'function'){
              callback.call(wrapper, data.response);
            }
          }
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert('Error:' + jqXHR.responseText + '; ' + textStatus);
        }
    });
  }, 
  fillout_win: function(data){
    var wrapper = this;
    var images = (typeof data == 'undefined') ? [] : data.images;
    var post = data;
    var $win = $('#win_new_post');

    //Append photos
    wrapper.append_thumb(post.images);

    //Fillout form fields
    $win.find('#product_name').val(post.title);
    $win.find('#product_desc').val(post.description);
    $win.find('#price').val(post.price);
    $win.find('#currency').val(post.currency);
    $win.find('#quantity').val(post.quantity);
    $win.find('#url').val(post.purchase_url);

    $win.find('#post_id').val(post.product_id);

    //Societies
    var societies = post.societies;
    var $societies = $('#win_new_post .societies');

    $societies.find('li a').each(function(index){
      var $this = $(this);
      var s_id = parseInt($this.attr('data-id'));
      var matched = false;

      for(var i = 0; i < societies.length; i++){
        var cur_id = parseInt(societies[i].society_id);

        if(s_id == cur_id){
          matched = true;
          break;
        }
      }

      if(matched == true){
        $this.addClass('active');
      }else{
        $this.removeClass('active');
      }
    });
  }, 
  remove_image: function(id, $item){
    var wrapper = this;
    var params = {
      image_id: id
    }

    $.ajax(base_url + 'index.php/api/products/delete_image/', {
        type: 'post',
        data: params,
        success: function(data, textStatus, jqXHR){
          console.log(data);
          if(data.status == 'fail'){
            alert(data.message);
          }else{
            console.log('ok');
            $item.fadeOut('slow', function(){
              var $carousel = $('#win_new_post .left .photos');
              $carousel.trigger('removeItem', $item);
            });
          }
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert('Error:' + jqXHR.responseText + '; ' + textStatus);
        }
    });
  }
}