0

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..

Rufilix
  • 253
  • 3
  • 22

2 Answers2

2

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) %>
Surya
  • 15,703
  • 3
  • 51
  • 74
  • this works fine if I put the javascript in the view, but not on a separate .js file. It give me an error… strange. – Rufilix Oct 30 '14 at 20:08
  • 1
    @MAGE that's because Rails helper methods are not available in assets directory. For that you can either have them in available: http://stackoverflow.com/a/26615645/645886 or create a `data-url` attribute on `#badgebutton ` element and then call it in JavaScript: `$(this).data('url')`, if you ask me then I'd prefer latter. – Surya Oct 30 '14 at 20:16
1

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.

kroky
  • 1,266
  • 11
  • 19
  • 1. By partial, do you mean my view ? because I don't have partial ? 2. I don't understand how to change my JS file like you propose, sorry – Rufilix Oct 30 '14 at 20:09
  • Yes, I meant your view. ERB files are either partials or normal views. I also updated my answer with the full JS file implementation. – kroky Oct 30 '14 at 20:44