From a68e7eca56459d1418bd7d87efcf4c75bd7020f1 Mon Sep 17 00:00:00 2001 From: Ilya Konanykhin Date: Wed, 18 Jan 2017 17:18:32 +0600 Subject: [PATCH 1/7] User avatar upload at sign up --- Gemfile | 1 + Gemfile.lock | 11 +++++++++++ app/models/user.rb | 11 ++++++++++- app/views/devise/registrations/new.html.haml | 6 ++++++ .../20170118110330_add_attachment_avatar_to_users.rb | 11 +++++++++++ db/schema.rb | 6 +++++- 6 files changed, 44 insertions(+), 2 deletions(-) create mode 100644 db/migrate/20170118110330_add_attachment_avatar_to_users.rb diff --git a/Gemfile b/Gemfile index 2c43331..a18b60c 100644 --- a/Gemfile +++ b/Gemfile @@ -18,6 +18,7 @@ gem 'jquery-rails', '~> 2.0' gem 'pg', '~> 0.17.1' gem 'will_paginate', '~> 3.0.3' gem 'jbuilder', '~> 2.0.3' +gem 'paperclip', '~> 4.3' # Assets gem 'sass-rails', '~> 3.0' diff --git a/Gemfile.lock b/Gemfile.lock index 932a1cf..db4fb0a 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -57,7 +57,10 @@ GEM xpath (~> 2.0) childprocess (0.5.9) ffi (~> 1.0, >= 1.0.11) + climate_control (0.1.0) cliver (0.3.2) + cocaine (0.5.8) + climate_control (>= 0.0.3, < 1.0) coderay (1.1.1) coffee-rails (3.2.2) coffee-script (>= 2.2.0) @@ -129,6 +132,7 @@ GEM treetop (~> 1.4.8) method_source (0.8.2) mime-types (1.25.1) + mimemagic (0.3.0) mini_portile2 (2.0.0) momentjs-rails (2.15.1) railties (>= 3.1) @@ -148,6 +152,12 @@ GEM nenv (~> 0.1) shellany (~> 0.0) orm_adapter (0.0.7) + paperclip (4.3.7) + activemodel (>= 3.2.0) + activesupport (>= 3.2.0) + cocaine (~> 0.5.5) + mime-types + mimemagic (= 0.3.0) pg (0.17.1) poltergeist (1.5.1) capybara (~> 2.1) @@ -261,6 +271,7 @@ DEPENDENCIES netzke-basepack (~> 0.8.0) netzke-cancan netzke-core (~> 0.8.0) + paperclip (~> 4.3) pg (~> 0.17.1) poltergeist (~> 1.5.0) pry (~> 0.9.8) diff --git a/app/models/user.rb b/app/models/user.rb index a455258..b5fd9d0 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -1,4 +1,6 @@ class User < ActiveRecord::Base + MAX_AVATAR_SIZE_KB = 1024 + acts_as_loggable # Include default devise modules. Others available are: # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable @@ -8,7 +10,7 @@ class User < ActiveRecord::Base # Setup accessible (or protected) attributes for your model attr_accessible :email, :password, :password_confirmation, :remember_me, :first_name, :last_name, :bike_id, - :user_profiles_attributes, :username + :user_profiles_attributes, :username, :avatar has_many :transactions, as: :customer has_many :transaction_logs, through: :transactions, source: :logs @@ -20,11 +22,18 @@ class User < ActiveRecord::Base belongs_to :bike + has_attached_file :avatar, :styles => {:thumb => '100x100>'} + default_scope order('username ASC') validates :first_name, :presence => true validates :last_name, :presence => true + validates_attachment :avatar, :content_type => {:content_type => %w{ image/jpeg image/gif image/png }}, + :file_name => {:matches => [/png\Z/, /jpe?g\Z/, /gif\Z/]}, + :size => {:in => 0..MAX_AVATAR_SIZE_KB.kilobytes} + + def to_s "#{first_name} #{last_name}" end diff --git a/app/views/devise/registrations/new.html.haml b/app/views/devise/registrations/new.html.haml index 823795a..05269ab 100644 --- a/app/views/devise/registrations/new.html.haml +++ b/app/views/devise/registrations/new.html.haml @@ -23,6 +23,12 @@ = f.fields_for :user_profiles, profile_builder do |builder| = render 'user_profile_fields', f: builder + %fieldset + .form-group + %label You may upload your photo to be used as an avatar + = f.file_field :avatar + .help-block #{User::MAX_AVATAR_SIZE_KB} Kb max + %fieldset .form-group = f.password_field :password, placeholder: 'Password', class: 'form-control' diff --git a/db/migrate/20170118110330_add_attachment_avatar_to_users.rb b/db/migrate/20170118110330_add_attachment_avatar_to_users.rb new file mode 100644 index 0000000..1d87ba8 --- /dev/null +++ b/db/migrate/20170118110330_add_attachment_avatar_to_users.rb @@ -0,0 +1,11 @@ +class AddAttachmentAvatarToUsers < ActiveRecord::Migration + def self.up + change_table :users do |t| + t.attachment :avatar + end + end + + def self.down + remove_attachment :users, :avatar + end +end diff --git a/db/schema.rb b/db/schema.rb index 217d6a2..4cd03fb 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -11,7 +11,7 @@ # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 20131019170248) do +ActiveRecord::Schema.define(:version => 20170118110330) do create_table "bike_actions", :force => true do |t| t.string "action", :limit => 128, :null => false @@ -198,6 +198,10 @@ ActiveRecord::Schema.define(:version => 20131019170248) do t.string "first_name", :default => "", :null => false t.string "last_name", :default => "", :null => false t.string "username" + t.string "avatar_file_name" + t.string "avatar_content_type" + t.integer "avatar_file_size" + t.datetime "avatar_updated_at" end add_index "users", ["bike_id"], :name => "index_users_on_bike_id", :unique => true From 5f7eb43f63618cac0cbc364d54643fa750476cde Mon Sep 17 00:00:00 2001 From: Ilya Konanykhin Date: Wed, 18 Jan 2017 18:38:29 +0600 Subject: [PATCH 2/7] Bike photo upload --- app/assets/javascripts/application.js | 1 + app/assets/javascripts/bikes.js | 28 +- app/assets/javascripts/utils.js | 2 +- app/controllers/bikes_controller.rb | 1 + app/models/bike.rb | 7 +- app/views/bikes/new.html.haml | 123 +- app/views/bikes/show.html.haml | 63 +- ...118112258_add_attachment_photo_to_bikes.rb | 11 + db/schema.rb | 6 +- vendor/assets/javascripts/jquery.form.js | 1277 +++++++++++++++++ 10 files changed, 1410 insertions(+), 109 deletions(-) create mode 100644 db/migrate/20170118112258_add_attachment_photo_to_bikes.rb create mode 100644 vendor/assets/javascripts/jquery.form.js diff --git a/app/assets/javascripts/application.js b/app/assets/javascripts/application.js index f507af9..9c81081 100644 --- a/app/assets/javascripts/application.js +++ b/app/assets/javascripts/application.js @@ -16,4 +16,5 @@ //= require utils //= require moment //= require bootstrap-datetimepicker +//= require jquery.form diff --git a/app/assets/javascripts/bikes.js b/app/assets/javascripts/bikes.js index ba530d6..8347f10 100644 --- a/app/assets/javascripts/bikes.js +++ b/app/assets/javascripts/bikes.js @@ -1,31 +1,11 @@ $('.btn').button(); -$("#add_bike_submit").click(function(){ - - json_data = { bikes: [{ - serial_number: $("#serial_number").val(), - bike_brand_id: parseInt($("#bike_brand_id").val()), - shop_id: parseInt($("#shop_id").val()), - model: $("#model").val(), - bike_style_id: parseInt($('input[name=bike_style]:checked').val()), - seat_tube_height: parseFloat($("#seat_tube_height").val()), - bike_condition_id: parseInt($('input[name=bike_condition]:checked').val()), - bike_purpose_id: 1, - bike_wheel_size_id: parseInt($("#bike_wheel_size_id").val()), - }]}; - - $.ajax({ - url: $("#add_bike_submit").data("url"), - type: "POST", - data: JSON.stringify(json_data), - contentType: 'application/json', +$("#add_bike_form").ajaxForm({ dataType: "json", - success: function(data, status, xhr){ + success: function(data){ window.location = data.bikes[0].id + "?add_bike=1"; }, - error: function(data, status ){ + error: function(data){ displayFormErrors(data.responseJSON); } - }); - -}); +}) \ No newline at end of file diff --git a/app/assets/javascripts/utils.js b/app/assets/javascripts/utils.js index edbb656..fff333e 100644 --- a/app/assets/javascripts/utils.js +++ b/app/assets/javascripts/utils.js @@ -2,7 +2,7 @@ function displayFormErrors(data){ if(data.errors != undefined ){ $.each(data.errors, function(field, errorMsg) { $("#"+field).closest(".form-group").addClass("has-error"); - $("#"+field).siblings(".help-block").html(errorMsg); + $("#"+field).siblings(".help-block").html(errorMsg.join(", ")); }); } } diff --git a/app/controllers/bikes_controller.rb b/app/controllers/bikes_controller.rb index 4be68b9..754ebcf 100644 --- a/app/controllers/bikes_controller.rb +++ b/app/controllers/bikes_controller.rb @@ -1,6 +1,7 @@ class BikesController < AuthenticatedController def new + @bike = Bike.new bike_purpose_id: 1 @brands = BikeBrand.all.map{ |b| [b.brand, b.id] } @brands.unshift( ["Select a brand", -1] ) @wheel_sizes = BikeWheelSize.all.map{ |w| [w.display_string, w.id] } diff --git a/app/models/bike.rb b/app/models/bike.rb index 70f2277..ef6b1ba 100644 --- a/app/models/bike.rb +++ b/app/models/bike.rb @@ -1,7 +1,7 @@ class Bike < ActiveRecord::Base acts_as_loggable attr_accessible :shop_id, :serial_number, :bike_brand_id, :model, :color, :bike_style_id, :seat_tube_height, - :top_tube_length, :bike_wheel_size_id, :value, :bike_condition_id, :bike_purpose_id + :top_tube_length, :bike_wheel_size_id, :value, :bike_condition_id, :bike_purpose_id, :photo has_many :transactions @@ -13,6 +13,8 @@ class Bike < ActiveRecord::Base belongs_to :bike_purpose belongs_to :bike_wheel_size + has_attached_file :photo, :styles => {:thumb => '100x100>'} + validates :shop_id, :presence => true, :uniqueness => true, :numericality => { :only_integer => true } validates :serial_number, :length => { :minimum => 3 } validates :model, :length => { :maximum => 50 } @@ -24,6 +26,9 @@ class Bike < ActiveRecord::Base validates :bike_condition_id, :presence => true, :numericality => { greater_than: 0, message: "is not a valid condition" } validates :bike_purpose_id, :presence => true, :numericality => { greater_than: 0, message: "is not a valid purpose" } + validates_attachment :photo, :content_type => {:content_type => %w{ image/jpeg image/gif image/png }}, + :file_name => {:matches => [/png\Z/, /jpe?g\Z/, /gif\Z/]} + self.per_page = 15 after_create :create_task_list diff --git a/app/views/bikes/new.html.haml b/app/views/bikes/new.html.haml index 20bb3fc..fa74a38 100644 --- a/app/views/bikes/new.html.haml +++ b/app/views/bikes/new.html.haml @@ -4,70 +4,77 @@ .row .col-xs-12.col-sm-6.col-lg-4 - %fieldset - .form-group - = number_field_tag nil, nil, id: 'shop_id', placeholder: 'Shop ID', min: 0, class: 'form-control' - .help-block + = form_for @bike, as: 'bikes', index: '', url: api_create_bike_path, method: :post, enctype: 'multipart/form-data', html: {id: 'add_bike_form'} do |f| + = f.hidden_field 'bike_purpose_id' + %fieldset + .form-group + = f.number_field 'shop_id', placeholder: 'Shop ID', min: 0, class: 'form-control', id: 'shop_id' + .help-block - .form-group - = select_tag :bike_brand_id, options_for_select(@brands), class: 'form-control' - .help-block + .form-group + = f.select 'bike_brand_id', options_for_select(@brands), {}, class: 'form-control', id: 'bike_brand_id' + .help-block - .form-group - = text_field_tag nil, nil, id: 'model', placeholder: 'Model', class: 'form-control' - .help-block + .form-group + = f.text_field 'model', placeholder: 'Model', class: 'form-control', id: 'model' + .help-block - .form-group - = text_field_tag nil, nil, id: 'serial_number', placeholder: 'Serial Number', class: 'form-control' - .help-block + .form-group + = f.text_field 'serial_number', placeholder: 'Serial Number', class: 'form-control', id: 'serial_number' + .help-block - .form-group - .btn-group(data-toggle="buttons") - %label.btn.btn-default - = radio_button_tag 'bike_style', 3 - RD - %label.btn.btn-default - = radio_button_tag 'bike_style', 1 - MTN - %label.btn.btn-default - = radio_button_tag 'bike_style', 2 - HYB - %label.btn.btn-default - = radio_button_tag 'bike_style', 4 - OTHER - = hidden_field_tag nil, nil, id: 'bike_style_id' - .help-block + .form-group + .btn-group(data-toggle="buttons") + %label.btn.btn-default + = f.radio_button 'bike_style_id', 3 + RD + %label.btn.btn-default + = f.radio_button 'bike_style_id', 1 + MTN + %label.btn.btn-default + = f.radio_button 'bike_style_id', 2 + HYB + %label.btn.btn-default + = f.radio_button 'bike_style_id', 4 + OTHER + = hidden_field_tag nil, nil, id: 'bike_style_id' + .help-block - .form-group - = select_tag :bike_wheel_size_id, options_for_select(@wheel_sizes), id: :bike_wheel_size_id, class: 'form-control' - .help-block + .form-group + = f.select 'bike_wheel_size_id', options_for_select(@wheel_sizes), {}, class: 'form-control', id: 'bike_wheel_size_id' + .help-block - .form-group - .btn-group(data-toggle="buttons") - %label.btn.btn-default - = radio_button_tag 'bike_condition', 2 - Poor - %label.btn.btn-default - = radio_button_tag 'bike_condition', 3 - Fair - %label.btn.btn-default - = radio_button_tag 'bike_condition', 4 - Good - %label.btn.btn-default - = radio_button_tag 'bike_condition', 5 - Excellent - = hidden_field_tag nil, nil, id: 'bike_condition_id' - .help-block + .form-group + .btn-group(data-toggle="buttons") + %label.btn.btn-default + = f.radio_button 'bike_condition_id', 2 + Poor + %label.btn.btn-default + = f.radio_button 'bike_condition_id', 3 + Fair + %label.btn.btn-default + = f.radio_button 'bike_condition_id', 4 + Good + %label.btn.btn-default + = f.radio_button 'bike_condition_id', 5 + Excellent + = hidden_field_tag nil, nil, id: 'bike_condition_id' + .help-block - .form-group - .input-group - = number_field_tag nil, nil, id: 'seat_tube_height', placeholder: 'Seat Tube', min: 0, max: 100, class: 'form-control' - .input-group-addon cm - .help-block + .form-group + .input-group + = f.number_field 'seat_tube_height', placeholder: 'Seat Tube', min: 0, max: 100, class: 'form-control', id: 'seat_tube_height' + .input-group-addon cm + .help-block - -# Commenting this out until description is added to Bike - /.form-group - %input{id: "bike_description", placeholder: "Short description", type: "text", class: "input-lg" } + .form-group + %label Bike photo (optional) + = f.file_field 'photo', id: 'photo' + .help-block - .form-group - = button_tag 'Add Bike', id: 'add_bike_submit', class: 'btn btn-primary', data: {url: api_create_bike_path} \ No newline at end of file + -# Commenting this out until description is added to Bike + /.form-group + %input{id: "bike_description", placeholder: "Short description", type: "text", class: "input-lg" } + + .form-group + = button_tag 'Add Bike', class: 'btn btn-primary' \ No newline at end of file diff --git a/app/views/bikes/show.html.haml b/app/views/bikes/show.html.haml index a80aa2e..2374aad 100644 --- a/app/views/bikes/show.html.haml +++ b/app/views/bikes/show.html.haml @@ -7,34 +7,49 @@ %h1 #{@bike.shop_id}: #{@bike.bike_brand} %h4= @bike.model -%dl.dl-horizontal - %dt Type - %dd= @bike.bike_style - - %dt Wheel Size - %dd= @bike.bike_wheel_size.display_string - - %dt Condition - %dd= @bike.bike_condition - - %dt Seat Tube (cm) - %dd= @bike.seat_tube_height - - %dt Purpose - %dd= @bike.bike_purpose +.form-horizontal + - if @bike.photo? + .form-group + %label.col-sm-2.control-label Photo + .col-sm-10 + = link_to @bike.photo.url, target: '_blank' do + %img{src: @bike.photo.url(:thumb), class: 'img-thumbnail'} + + .form-group + %label.col-sm-2.control-label Type + .col-sm-10.form-control-static= @bike.bike_style + + .form-group + %label.col-sm-2.control-label Wheel Size + .col-sm-10.form-control-static= @bike.bike_wheel_size.display_string + + .form-group + %label.col-sm-2.control-label Condition + .col-sm-10.form-control-static= @bike.bike_condition + + .form-group + %label.col-sm-2.control-label Seat Tube (cm) + .col-sm-10.form-control-static= @bike.seat_tube_height + + .form-group + %label.col-sm-2.control-label Purpose + .col-sm-10.form-control-static= @bike.bike_purpose - unless @bike.value.nil? - %dt Value - %dd= @bike.value + .form-group + %label.col-sm-2.control-label Value + .col-sm-10.form-control-static= @bike.value - unless @bike.color.nil? - %dt Color - %dd - .bike-color(style="background-color: ##{@bike.color}")= @bike.color + .form-group + %label.col-sm-2.control-label Color + .col-sm-10.form-control-static + .bike-color(style="background-color: ##{@bike.color}")= @bike.color - if @task_list - tasks = @task_list.tasks.to_a - %dt Task list - %dd - = link_to edit_task_list_path(@task_list.id) do - #{tasks.select(&:done).count}/#{tasks.count} \ No newline at end of file + .form-group + %label.col-sm-2.control-label Task list + .col-sm-10.form-control-static + = link_to edit_task_list_path(@task_list.id) do + #{tasks.select(&:done).count}/#{tasks.count} \ No newline at end of file diff --git a/db/migrate/20170118112258_add_attachment_photo_to_bikes.rb b/db/migrate/20170118112258_add_attachment_photo_to_bikes.rb new file mode 100644 index 0000000..e1c1259 --- /dev/null +++ b/db/migrate/20170118112258_add_attachment_photo_to_bikes.rb @@ -0,0 +1,11 @@ +class AddAttachmentPhotoToBikes < ActiveRecord::Migration + def self.up + change_table :bikes do |t| + t.attachment :photo + end + end + + def self.down + remove_attachment :bikes, :photo + end +end diff --git a/db/schema.rb b/db/schema.rb index 4cd03fb..c001ecc 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -11,7 +11,7 @@ # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 20170118110330) do +ActiveRecord::Schema.define(:version => 20170118112258) do create_table "bike_actions", :force => true do |t| t.string "action", :limit => 128, :null => false @@ -73,6 +73,10 @@ ActiveRecord::Schema.define(:version => 20170118110330) do t.string "model" t.integer "shop_id" t.integer "bike_wheel_size_id" + t.string "photo_file_name" + t.string "photo_content_type" + t.integer "photo_file_size" + t.datetime "photo_updated_at" end create_table "credit_conversions", :force => true do |t| diff --git a/vendor/assets/javascripts/jquery.form.js b/vendor/assets/javascripts/jquery.form.js new file mode 100644 index 0000000..591ad6f --- /dev/null +++ b/vendor/assets/javascripts/jquery.form.js @@ -0,0 +1,1277 @@ +/*! + * jQuery Form Plugin + * version: 3.51.0-2014.06.20 + * Requires jQuery v1.5 or later + * Copyright (c) 2014 M. Alsup + * Examples and documentation at: http://malsup.com/jquery/form/ + * Project repository: https://github.com/malsup/form + * Dual licensed under the MIT and GPL licenses. + * https://github.com/malsup/form#copyright-and-license + */ +/*global ActiveXObject */ + +// AMD support +(function (factory) { + "use strict"; + if (typeof define === 'function' && define.amd) { + // using AMD; register as anon module + define(['jquery'], factory); + } else { + // no AMD; invoke directly + factory( (typeof(jQuery) != 'undefined') ? jQuery : window.Zepto ); + } +} + +(function($) { +"use strict"; + +/* + Usage Note: + ----------- + Do not use both ajaxSubmit and ajaxForm on the same form. These + functions are mutually exclusive. Use ajaxSubmit if you want + to bind your own submit handler to the form. For example, + + $(document).ready(function() { + $('#myForm').on('submit', function(e) { + e.preventDefault(); // <-- important + $(this).ajaxSubmit({ + target: '#output' + }); + }); + }); + + Use ajaxForm when you want the plugin to manage all the event binding + for you. For example, + + $(document).ready(function() { + $('#myForm').ajaxForm({ + target: '#output' + }); + }); + + You can also use ajaxForm with delegation (requires jQuery v1.7+), so the + form does not have to exist when you invoke ajaxForm: + + $('#myForm').ajaxForm({ + delegation: true, + target: '#output' + }); + + When using ajaxForm, the ajaxSubmit function will be invoked for you + at the appropriate time. +*/ + +/** + * Feature detection + */ +var feature = {}; +feature.fileapi = $("").get(0).files !== undefined; +feature.formdata = window.FormData !== undefined; + +var hasProp = !!$.fn.prop; + +// attr2 uses prop when it can but checks the return type for +// an expected string. this accounts for the case where a form +// contains inputs with names like "action" or "method"; in those +// cases "prop" returns the element +$.fn.attr2 = function() { + if ( ! hasProp ) { + return this.attr.apply(this, arguments); + } + var val = this.prop.apply(this, arguments); + if ( ( val && val.jquery ) || typeof val === 'string' ) { + return val; + } + return this.attr.apply(this, arguments); +}; + +/** + * ajaxSubmit() provides a mechanism for immediately submitting + * an HTML form using AJAX. + */ +$.fn.ajaxSubmit = function(options) { + /*jshint scripturl:true */ + + // fast fail if nothing selected (http://dev.jquery.com/ticket/2752) + if (!this.length) { + log('ajaxSubmit: skipping submit process - no element selected'); + return this; + } + + var method, action, url, $form = this; + + if (typeof options == 'function') { + options = { success: options }; + } + else if ( options === undefined ) { + options = {}; + } + + method = options.type || this.attr2('method'); + action = options.url || this.attr2('action'); + + url = (typeof action === 'string') ? $.trim(action) : ''; + url = url || window.location.href || ''; + if (url) { + // clean url (don't include hash vaue) + url = (url.match(/^([^#]+)/)||[])[1]; + } + + options = $.extend(true, { + url: url, + success: $.ajaxSettings.success, + type: method || $.ajaxSettings.type, + iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank' + }, options); + + // hook for manipulating the form data before it is extracted; + // convenient for use with rich editors like tinyMCE or FCKEditor + var veto = {}; + this.trigger('form-pre-serialize', [this, options, veto]); + if (veto.veto) { + log('ajaxSubmit: submit vetoed via form-pre-serialize trigger'); + return this; + } + + // provide opportunity to alter form data before it is serialized + if (options.beforeSerialize && options.beforeSerialize(this, options) === false) { + log('ajaxSubmit: submit aborted via beforeSerialize callback'); + return this; + } + + var traditional = options.traditional; + if ( traditional === undefined ) { + traditional = $.ajaxSettings.traditional; + } + + var elements = []; + var qx, a = this.formToArray(options.semantic, elements); + if (options.data) { + options.extraData = options.data; + qx = $.param(options.data, traditional); + } + + // give pre-submit callback an opportunity to abort the submit + if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) { + log('ajaxSubmit: submit aborted via beforeSubmit callback'); + return this; + } + + // fire vetoable 'validate' event + this.trigger('form-submit-validate', [a, this, options, veto]); + if (veto.veto) { + log('ajaxSubmit: submit vetoed via form-submit-validate trigger'); + return this; + } + + var q = $.param(a, traditional); + if (qx) { + q = ( q ? (q + '&' + qx) : qx ); + } + if (options.type.toUpperCase() == 'GET') { + options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q; + options.data = null; // data is null for 'get' + } + else { + options.data = q; // data is the query string for 'post' + } + + var callbacks = []; + if (options.resetForm) { + callbacks.push(function() { $form.resetForm(); }); + } + if (options.clearForm) { + callbacks.push(function() { $form.clearForm(options.includeHidden); }); + } + + // perform a load on the target only if dataType is not provided + if (!options.dataType && options.target) { + var oldSuccess = options.success || function(){}; + callbacks.push(function(data) { + var fn = options.replaceTarget ? 'replaceWith' : 'html'; + $(options.target)[fn](data).each(oldSuccess, arguments); + }); + } + else if (options.success) { + callbacks.push(options.success); + } + + options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg + var context = options.context || this ; // jQuery 1.4+ supports scope context + for (var i=0, max=callbacks.length; i < max; i++) { + callbacks[i].apply(context, [data, status, xhr || $form, $form]); + } + }; + + if (options.error) { + var oldError = options.error; + options.error = function(xhr, status, error) { + var context = options.context || this; + oldError.apply(context, [xhr, status, error, $form]); + }; + } + + if (options.complete) { + var oldComplete = options.complete; + options.complete = function(xhr, status) { + var context = options.context || this; + oldComplete.apply(context, [xhr, status, $form]); + }; + } + + // are there files to upload? + + // [value] (issue #113), also see comment: + // https://github.com/malsup/form/commit/588306aedba1de01388032d5f42a60159eea9228#commitcomment-2180219 + var fileInputs = $('input[type=file]:enabled', this).filter(function() { return $(this).val() !== ''; }); + + var hasFileInputs = fileInputs.length > 0; + var mp = 'multipart/form-data'; + var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp); + + var fileAPI = feature.fileapi && feature.formdata; + log("fileAPI :" + fileAPI); + var shouldUseFrame = (hasFileInputs || multipart) && !fileAPI; + + var jqxhr; + + // options.iframe allows user to force iframe mode + // 06-NOV-09: now defaulting to iframe mode if file input is detected + if (options.iframe !== false && (options.iframe || shouldUseFrame)) { + // hack to fix Safari hang (thanks to Tim Molendijk for this) + // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d + if (options.closeKeepAlive) { + $.get(options.closeKeepAlive, function() { + jqxhr = fileUploadIframe(a); + }); + } + else { + jqxhr = fileUploadIframe(a); + } + } + else if ((hasFileInputs || multipart) && fileAPI) { + jqxhr = fileUploadXhr(a); + } + else { + jqxhr = $.ajax(options); + } + + $form.removeData('jqxhr').data('jqxhr', jqxhr); + + // clear element array + for (var k=0; k < elements.length; k++) { + elements[k] = null; + } + + // fire 'notify' event + this.trigger('form-submit-notify', [this, options]); + return this; + + // utility fn for deep serialization + function deepSerialize(extraData){ + var serialized = $.param(extraData, options.traditional).split('&'); + var len = serialized.length; + var result = []; + var i, part; + for (i=0; i < len; i++) { + // #252; undo param space replacement + serialized[i] = serialized[i].replace(/\+/g,' '); + part = serialized[i].split('='); + // #278; use array instead of object storage, favoring array serializations + result.push([decodeURIComponent(part[0]), decodeURIComponent(part[1])]); + } + return result; + } + + // XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz) + function fileUploadXhr(a) { + var formdata = new FormData(); + + for (var i=0; i < a.length; i++) { + formdata.append(a[i].name, a[i].value); + } + + if (options.extraData) { + var serializedData = deepSerialize(options.extraData); + for (i=0; i < serializedData.length; i++) { + if (serializedData[i]) { + formdata.append(serializedData[i][0], serializedData[i][1]); + } + } + } + + options.data = null; + + var s = $.extend(true, {}, $.ajaxSettings, options, { + contentType: false, + processData: false, + cache: false, + type: method || 'POST' + }); + + if (options.uploadProgress) { + // workaround because jqXHR does not expose upload property + s.xhr = function() { + var xhr = $.ajaxSettings.xhr(); + if (xhr.upload) { + xhr.upload.addEventListener('progress', function(event) { + var percent = 0; + var position = event.loaded || event.position; /*event.position is deprecated*/ + var total = event.total; + if (event.lengthComputable) { + percent = Math.ceil(position / total * 100); + } + options.uploadProgress(event, position, total, percent); + }, false); + } + return xhr; + }; + } + + s.data = null; + var beforeSend = s.beforeSend; + s.beforeSend = function(xhr, o) { + //Send FormData() provided by user + if (options.formData) { + o.data = options.formData; + } + else { + o.data = formdata; + } + if(beforeSend) { + beforeSend.call(this, xhr, o); + } + }; + return $.ajax(s); + } + + // private function for handling file uploads (hat tip to YAHOO!) + function fileUploadIframe(a) { + var form = $form[0], el, i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle; + var deferred = $.Deferred(); + + // #341 + deferred.abort = function(status) { + xhr.abort(status); + }; + + if (a) { + // ensure that every serialized input is still enabled + for (i=0; i < elements.length; i++) { + el = $(elements[i]); + if ( hasProp ) { + el.prop('disabled', false); + } + else { + el.removeAttr('disabled'); + } + } + } + + s = $.extend(true, {}, $.ajaxSettings, options); + s.context = s.context || s; + id = 'jqFormIO' + (new Date().getTime()); + if (s.iframeTarget) { + $io = $(s.iframeTarget); + n = $io.attr2('name'); + if (!n) { + $io.attr2('name', id); + } + else { + id = n; + } + } + else { + $io = $('