Jump to content

The ultimate community for Ruby on Rails developers.


Photo

What's wrong with my JQUERY/AJAX??

Javascript Ajax Rails Jquery Ruby

  • Please log in to reply
1 reply to this topic

#1 Saggy

Saggy

    Passenger

  • Members
  • 4 posts

Posted 01 April 2014 - 09:15 AM

Here is my View:

<h1>Edit holidays for <i><%= @group.name%></i>-group</h1>
    <table width="auto" border="0">
      <thead>
        <th  scope="col">Selected</th>
        <th width="50" scope="col">&nbsp;</th>
        <th  scope="col">Holidays</th>
      <td width="0"></thead>
      <tbody>
      <tr>
      <td>
          <%= form_tag({}, {}) do %>
        <% holidays_array = @group.holidays.all.map { |holiday| [holiday.name, holiday.id] } %>
        <%= select(:holiday_id, :name, options_for_select(holidays_array),{}, {:multiple => true, :style => "width: 300px; background-color: #9FE", :width => "300", :size => 20, :id=>"left" }  ) %>
          <% end %>
      </td>
      <td align="center">
          <a href="#" id="toleft" w_id= "<%=@group.id %>"><<</a>
          <br /><br />
          <a href="#" id="toright" w_id="<%=@group.id %>">>></a>
      </td>    
      <td>
          <%= form_tag({}, {}) do %>
        <% holidays_array = Holiday.all.map { |holiday| [holiday.name, holiday.id] } %>
        <%= select(:holiday_id, :name,  options_for_select(holidays_array),{}, { :multiple => true, :style => "width: 300px; background-color: #F99", :width => "300", :size => 20, :id=>"right" } ) %>
          <% end %>
      </td>
      </tbody>
    </table>

Here are my Javascript's, which are called by the links:

$(function () {
        $('#toleft').click(function () {
            var sel = document.getElementById("right");
            var len = sel.options.length;
            var w_id = this.getAttribute('w_id');
            for (var i = 0; i < len; i++)
                {
                if(sel.options[i].selected)
                    {
                    alert("test");
                    $.ajax("/groups/add_holiday", {holiday_id: sel.options[i].value, group_id: @group.id}).done(function(data){});
                    }
                }
            location.reload(true);  
        })
      });

&

$(function () {
        $('#toright').click(function () {
            var sel = document.getElementById("left");
            var len = sel.options.length;
            var w_id = this.getAttribute('w_id');
            for (var i = 0; i < len; i++)
                {
                if(sel.options[i].selected)
                    {
                    alert("test");
                    $.ajax("/groups/rem_holiday", {holiday_id: sel.options[i].value, group_id: w_id}).done(function(data){});
                    }
                }
            location.reload(true);  
        })
      });

This controlls this:

exchange.png

 

I've also added the routes to my groups routes:

  resources :groups do
    post 'add_holiday'
    delete 'rem_holiday'
    member do
      get 'search_admin'
      post 'search_admin'
      post 'add_admin'
      get 'remove_admin'
      post 'remove_admin'
    end
  end

I still can't find my mistake...
  

 



#2 Saggy

Saggy

    Passenger

  • Members
  • 4 posts

Posted 04 April 2014 - 06:56 AM

THE FULL JAVASCRIPT:

var toLeft=function()
	{
	var sel = document.getElementById("right");
	var lin = document.getElementById("toleft");
	var len = sel.options.length;
	var w_controller = lin.getAttribute("w_controller");
	var w_id = lin.getAttribute("w_id");
	var w_type = lin.getAttribute("w_type");
	var w_command = lin.getAttribute("w_command");
	for (var i = 0; i < len; i++) 
		{
		if(sel.options[i].selected) 
			{
  			$.ajax(
				{
    			type: w_type,
    			url: w_command,
				data: {sel_id: sel.options[i].value, w_id: w_id },
    			success:function()
					{
    				}
  				});
			}
		}
//	window.location.reload();
	}

var toRight=function()
	{
	var sel = document.getElementById("left");
	var lin = document.getElementById("toright");
	var len = sel.options.length;
	var w_controller = lin.getAttribute("w_controller");
	var w_id = lin.getAttribute("w_id");
	var w_type = lin.getAttribute("w_type");
	var w_command = lin.getAttribute("w_command");
	for (var i = 0; i < len; i++) 
		{
		if(sel.options[i].selected) 
			{	
  			$.ajax(
				{
    			type: w_type,
    			url: w_command,
				data: {to_find_id: sel.options[i].value, id: w_id},
    			success:function()
					{	
    				}
  				});
			}
		}
//	window.location.reload();
	}


$(document).ready(function(){
  $('#toright').click(toRight);
});

$(document).ready(function(){
  $('#toleft').click(toLeft);
});


THE SUBGROUP-CONTROLLER

class SubgroupsController < ApplicationController
  before_action :set_subgroup, only: [:show, :edit, :update, :destroy, :remove_user, :process_add_user, :add_timespan, :rem_timespan, :process_add_admin]
  before_action :login_required

  authorize_resource

  # GET /subgroups
  # GET /subgroups.json
  def index
    @subgroups = Subgroup.all.find_all{|sg| can? :read, sg }#TODO: optimize, only load where can? :read
    if(@subgroups.count == 0)
      flash[:info] = "You can't see any subgroups due to your status."
      redirect_to :welcome
    end
  end
  
  
  def add_timespan
	RTimespan.create(timespan_id: params[:to_find_id].to_s, subgroup_id: @subgroup.id)
  end
  
  def rem_timespan
	RTimespan.where(timespan_id: params[:to_find_id].to_s, subgroup_id: @subgroup.id).destroy
  end

  def add_user
    case params[:commit]
      when "Add as user" then return process_add_user
      when "Add as admin" then return process_add_admin
      else flash[:error] = "Invalid submit."
    end
    redirect_to action: :show 
  end

  def remove_admin
    authorize! :remove_admin, @subgroup
    if !params[:selected].nil? && !params[:selected].empty?
      params[:selected].each do |adminId, confirmed|
        if confirmed == "1"
          Membership.destroy(Membership.where(role: 2, subgroup_id: @subgroup.id, user_id: adminId).collect(&:id))
        end
      end 
      flash[:info] = "Success"
      redirect_to action: :show
    end
  end

  def remove_user
    authorize! :remove_user, @subgroup 
    if !params[:selected].nil? && !params[:selected].empty?
      params[:selected].each do |userId, confirmed|
        if confirmed == "1"
          Membership.destroy(Membership.where(role: 1, subgroup_id: @subgroup.id, user_id: userId).collect(&:id) )
        end
      end 
      flash[:info] = "Success"
      redirect_to action: :show
    end
  end

  def search_user
    @results = nil
    if params[:query]
      if params[:query].empty?
        @results = User.all
      else
        @results = User.find(:all, conditions: ['name like ?', "%".concat(params[:query]).concat("%")])
      end
    end
  end

  # GET /subgroups/1
  # GET /subgroups/1.json
  def show 
  end

  # GET /subgroups/new
  def new
    @subgroup = Subgroup.new
  end

  # GET /subgroups/1/edit
  def edit
  end

  # POST /subgroups
  # POST /subgroups.json
  def create
    @subgroup = Subgroup.new(subgroup_params)
    respond_to do |format|
      if @subgroup.save
        format.html { redirect_to @subgroup, notice: 'Subgroup was successfully created.' }
        format.json { render action: 'show', status: :created, location: @subgroup }
      else
        format.html { render action: 'new' }
        format.json { render json: @subgroup.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /subgroups/1
  # PATCH/PUT /subgroups/1.json
  def update
    respond_to do |format|
      if @subgroup.update(subgroup_params)
        format.html { redirect_to @subgroup, notice: 'Subgroup was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @subgroup.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /subgroups/1
  # DELETE /subgroups/1.json
  def destroy
    @subgroup.destroy
    respond_to do |format|
      format.html { redirect_to subgroups_url, notice: 'Subgroup was successfully deleted.' }
      format.json { head :no_content }
    end
  end

  private
    def process_add_user  
      authorize! :add_user, Subgroup.find(params[:id]) 
      params[:selected].each do |userId,confirmed|
        if confirmed == "1" 
          newRelation = Membership.create( subgroup_id: params[:id], user_id: userId) 
          if !newRelation.save
            flash[:error] = adding_error_message userId, params[:id] 
            redirect_to action: 'search_user'
            return
          end
        end
      end 
      flash[:info] = "Operation completed successfully"
      redirect_to action: :show 
    end

    def process_add_admin
      authorize! :add_admin, Subgroup.find(params[:id]) 
      params[:selected].each do |adminId,confirmed|
        if confirmed == "1" 
          newRelation = Membership.create( subgroup_id: params[:id], user_id: adminId, role: 2) 
          if !newRelation.save
            flash[:error] = adding_error_message adminId, params[:id] 
            redirect_to action: 'search_user'
            return
          end
        end
      end 
      flash[:info] = "Operation completed successfully"
      redirect_to action: :show 
    end


    # Use callbacks to share common setup or constraints between actions.
    def set_subgroup
		if params[:id].present?
			@subgroup = Subgroup.find(params[:id])
		elsif params[:subgroup_id].present?
			@subgroup = Subgroup.find(params[:subgroup_id])
		end
	end

    # Never trust parameters from the scary internet, only allow the white list through.
    def subgroup_params
      params.require(:subgroup).permit(:name)
    end
end







Also tagged with one or more of these keywords: Javascript, Ajax, Rails, Jquery, Ruby

1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users