Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 page reload after ajax call

I have an application that displays a large number of informational pages based on a location that I store in the session variable.

I am using a single select in a partial shared between varied pages from other controllers.

_location_select.html.erb

<%= select_tag(:location, options_for_select(Location.all.order('name ASC').collect { |l| [l.name, l.id] }, [session[:location]||'']), include_blank: true) %>

This makes an ajax call to:

locations_controller.rb

class LocationsController < ApplicationController
  def select
    session[:location] = params[:value]
    render js: ''
  end
end

Here is my coffescript:

home.js.coffee

$ ->
  $('#location').change ->
    $.get '/location/select', {value: $('option:selected', this).val()}

All of this code works great, but I need to have the page reload after the ajax call is complete, It would be too complicated to have the controller return the updated html since the location select will appear on such a large number of pages.

I have tried adding success:, and error: call back functions to the ajax call and have also played around with ajaxStop. I can get the ajax call to work or the page reload to work but cannot figure out the way to get both.

I have tried adding:

$(document).ajaxStop(function(){
    window.location.reload();
});

Where do I put location.reload() or is there a better way?

FYI, I am not using turbolinks in this app.

like image 376
Powertoaster Avatar asked Sep 18 '13 21:09

Powertoaster


1 Answers

locations_controller.rb

class LocationsController < ApplicationController
  def select
    session[:location] = params[:value]
    respond_to do |format|
        format.js   {}
    end
  end
end

views/locations/select.js

window.location.reload();
like image 138
Ayman Avatar answered Nov 14 '22 22:11

Ayman