Rufilix
Rufilix

Reputation: 253

rails add object in javascript url

I use this function on a js file and it works

 $(function() {


$("#badgebutton").click(function() {
    var assertions = [
        "http://www.exemple.com/patents/5555/badge.json"
    ];
    OpenBadges.issue(assertions, function(errors, successes) {
        console.log("callback called");
        console.log("Errors:", errors);
        console.log("Successes:", successes);
    });
});
});

In place of the number :

"http://www.exemple.com/patents/5555/badge.json"

I would like to use the patent.id. I tried this :

"http://www.exemple.com/patents/#{@patent.id}/badge.json"

and some other solution without success..

Upvotes: 0

Views: 112

Answers (2)

kroky
kroky

Reputation: 1316

You should pass the patent id (or better the whole url) to the js file using JS context which can be done in a few ways:

  1. Using globals:

In your partial (erb):

<script type="text/javascript">
  window.patent_url = "http://www.exemple.com/patents/#{@patent.id}/badge.json"
</script>

Then use the global patent_url variable in the JS file.

  1. Redo your JS file to encapsulate the JS logic but receive proper parameters like this.

It could look something like this:

window.badgebutton_handler = function(url) {
  OpenBadges.issue(url, function(errors, successes) {
    console.log("callback called");
    console.log("Errors:", errors);
    console.log("Successes:", successes);
  });
}

and bind the handler like this in the erb file:

<script type="text/javascript">
  $("#badgebutton").click(function() {
    badgebutton_handler("http://www.exemple.com/patents/#{@patent.id}/badge.json");
  });
</script>

The issue is that you should pass the variable or url where you have it and that's the ERB template files.

Upvotes: 1

Surya
Surya

Reputation: 16012

Try doing this:

"http://www.exemple.com/patents/<%= @patent.id %>/badge.json"

But, it's advisable to use routing helper methods generated by Rails when you define them in your routes.rb file. For example:

<%= badge_patents_path(@patent, :format => :json) %>

Upvotes: 2

Related Questions