javascriptruby-on-railswistia

Trigger a form on javascript event


I have a good understanding of ruby and rails, but lack knowledge in javascript. What I'd like to do is track when a user completes viewing a video.

I'm using wistia and my code currently looks like this:

:javascript
  wistiaEmbed = Wistia.embed("#{@chapter.video_id}", {
    autoPlay: true,
    videoFoam: true,
    playerColor: '000000'
  });
  wistiaEmbed.bind("end", function () {
    document.getElementById('target').style.display = 'none';
    document.getElementById('finished').style.display = 'block';
  });

What I wish to accomplish is to call a create action for my chapter_completion model. That accepts user_id and chapter_id at the 'end' of the video.

So I could make this work in a form by doing:

form_for current_user.chapter_completions.new do |f|
 f.hidden_field :chapter_id, value: @chapter.id
 f.submit
end

However I want this to be submitted automatically in the background at the end of the wistia video.


Solution

  •  wistiaEmbed.bind("end", function () {
        document.getElementById('target').style.display = 'none';
        document.getElementById('finished').style.display = 'block';
        document.getElementById('formID').submit(); // or
        //document.getElementsByName('formName').submit();
      });