mercredi 7 septembre 2016

Rendering partial on AJAX GET request - Ruby on Rails

In my index.hmtl.erb I'm passing the location found using navigator.geolocation.getCurrentPosition() back to index in my job_listings_controller.rb so I can use it for a query. It successfully returns the correct @job_listings to be mapped, but the html doesn't update on the AJAX call.. how would I go about rendering a partial when the GET call is sent?

index.html.erb 

<%= form_tag(job_listings_path, :method => 'get', class: 'form-inline', id: 'search-form') do %>
      <div class="col-md-7">
        <%= text_field_tag :search, params[:search], class: 'form-control', placeholder: 'Search Location', :required => true %>
      </div>
      <div class="col-md-3">
        <%= select_tag(:miles, options_for_select([['5 Miles', '5'], ['10 Miles', '10'], ['20 Miles','20'], ['30 miles', '30'], ['40 miles', '40'], ['50 miles', '50'], ['100 miles', '7']], '10')) %>
      </div>
      <div class="col-md-2">
        <%= submit_tag 'Search', class: 'form-control' %>
      </div>
    <% end %>

<script>

function success(position) {
 ...
 $.ajax({
    url: "/",
    type: "GET",
    dataType:"json",
    data: { lat:lat, lng:long },
    success:function(result){
      addCordinatesToMap([lat, long], result);
    }
 });
}

</script>


job_listings_controller.rb


def index

@display_footer = true
@miles = params[:miles] ? params[:miles].to_f : 10
@address = params[:search]

if params[:miles] && params[:search]
  @coordinates = Geocoder.coordinates(@address)
  @job_listings = JobListing.near(@coordinates, @miles)
else
  @local_coordinates = [params[:lat].to_f, params[:lng].to_f]
  @job_listings = JobListing.near(@local_coordinates, @miles)
end

respond_to do |format|
  format.html
  format.json { render json: @job_listings }
end
end

Aucun commentaire:

Enregistrer un commentaire