title: Processing an AJAX call in Rails 4 (success, error, beforeSend, complete)
body: <p>I would like to know what is the correct way of processing an ajax call in Rails 4 (when using remote: true option), the problem is that I would like to use all classic steps during the processing, such as success, error, beforeSend and complete.</p>
  
  <p>So let's say I have this button, which loads a modal window with some ajax in it:</p>
  
  <p>view (products/index): </p>
  
  <pre><code>&lt;%= link_to('Order this', new_order_path(product: product), remote: true) %&gt; 
  </code></pre>
  
  <p>orders_controller:</p>
  
  <pre><code>  def new
          @order = Order.new
          @product = Product.find(params[:product])
  
          respond_to do |format|
            format.html
            format.js
          end
        end
  </code></pre>
  
  <p>new.js.erb:</p>
  
  <pre><code>(function(){
    var $modalWindow = ...
    // some code that loads the modal window and closes it
  
    $modalWindow.html("&lt;%= j render('form') %&gt;"); // puts the needed product form 
                                                     into my modal window
  }());
  </code></pre>
  
  <p><strong>This works fine, but where does the before/after/success/error go in this code?</strong> </p>
  
  <p>And next, when the 'order product' button is clicked I have this in my orders controller:</p>
  
  <pre><code>def create
      @product = Product.find_by(params[:id])
      @order = current_office.orders.build(order_params)
  
      respond_to do |format|
        if @order.save
  
          format.html { 
            flash[:success] = 'Order created'
            redirect_to products_url
          }
          format.js
        else
          render :new
          format.html { render :new }
          format.js   { render :js=&gt;'alert("ajax error");' }
        end
      end
    end
  </code></pre>
  
  <p>Again, when the button "Create" is clicked, how do I go with processing? My create.js.erb only closes the modal window, but I would like it to process the request fully, with showing a preloader beforeSend, then success/error, and then after.</p>
  
  <p>Hope not too chaotic!</p>