jQuery Tips - StanfordBioinformatics/pulsar_lims GitHub Wiki
Use window.location.pathname
. I use this in my javascript files whenever I perform an AJAX request to an action routed on a member of a model, compared to the model collection as a whole. Since it's routed to a member of the model, the action needs to know what model record we're dealing with. By default, Rails will stick the record ID in the URL, i.e. http://localhost:3000/plates/4. Here, we have a Plate record whose ID is 4. In jQuery, I could type the following out as my relative URL to specify the destination of the request:
destination = "/plates/" + rec_id + "/some_action"
where rec_id
is a variable that stores the record ID (4 in this case). But how do we pass that information (value for the record ID) to jQuery? First, say that I have a checkbox and I want to perform my AJAX request when a user clicks on it:
<%= check_box_tag "show_failed_wells", "1", checked, id: "show_failed_wells" %><span> Show failed wells</span>
I can set some custom data attributes (see https://www.w3schools.com/tags/att_global_data.asp) on this input element, i.e.
<%= check_box_tag "show_failed_wells", "1", checked, id: "show_failed_wells", data: {plate_id: @plate.id} %><span> Show failed wells</span>
In jQuery, I can then access such data attributes as follows:
$checkbox = $("#show_failed_wells")
rec_id = $checkbox.data("plate-id")
An alternative, perhaps simpler, way to attaching data attributes to HTML elements is to reference the relative URL in the application that the user's browser is already visiting using, window.location.pathname
. If the user is visiting a plate record whose ID is 4, then we'd have this value set to "/plates/4". We can simplify the jQuery (this example uses CoffeeScript) to
get_path = window.location.pathname + "/some_action"
$.get get_path, (responseText,status,jqXHR) ->
alert(responseText)