Rails 3: update url parameters with an AJAX request

I have a filter and a list of products (id, name, creation_date).

I can filter by id, name or creation_date. With an AJAX request, I update the content of the div ... but obviously the url doesn't change.

How do I add parameters to the URL? For example:

localhost:3000/dashboard/catalog?name=radio&?date_creation=23-06-2013

      

I know history.pushState (html5) exists ... but I need my app to work in html4 browsers like IE9.

I've tried Wiselinks ( https://github.com/igor-alexandrov/wiselinks ) which uses History.js but doesn't use AJAX request.

Any ideas?

thank

+2


source to share


3 answers


+3


source


You are using some AJAX call facility, you had to call the AJAX part when changing the radio button

So, I am assuming you did it using a radio button and the button name is "select_product"

You can add a hidden field to your view where you can store the current date.



<div id='parentDiv'>
 <%= hidden_field_tag 'current_date', Time.now.strftime('%d-%m-%Y') %>
 Your radio button code
</div>

      

In javascript add the following code. This is just an example of an incomplete solution.

$(document).ready(function(){
 var showProducts = function(){
  $("#parentDiv").on('click', "input[name='choose_product']", function(){
   var ajax_url = 'localhost:3000/dashboard/catalog';
   var url_param = '';

   switch($(this).val()){
    case 'creation_date':
     var param_date = $('#current_date').val();
     url_param = '?name=radio&date_creation=' + param_date;     
     break;
    case 'name':
     // Your code goes here
    default:
     //Your code goes here
   }

   // Here you will get the modified url dynamically
   ajax_url += url_param

   $.ajax({
    url: ajax_url,
    // your code goes here
   }); 
  });
 }

 showProducts();
});

      

0


source


It's been a long time, but it might be helpful. The code is also being updated, so if you have more than one ajax \ remote link, you should be able to concatenate parameters from multiple urls. Based on user1364684 answer and this for combining urls.

# change ".someClassA" or "pagination" to the a link of the ajax elemen
$(document).on('click', '.someClassA a, .pagination a', function(){
    var this_params = this.href.split('?')[1], ueryParameters = {},
        queryString = location.search.substring(1), re = /([^&=]+)=([^&]*)/g, m;

    queryString = queryString + '&' + this_params;

    #Creates a map with the query string parameters
    while m = re.exec(queryString)
        queryParameters[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);

    url = window.location.href.split('?')[0] + "?" + $.param(queryParameters);

    $.getScript(url);
    history.pushState(null, "", url);

    return false;
});

# make back button work 
$(window).on("popstate", function(){
    $.getScript(location.href);
});

      

0


source







All Articles