0

I know this question has been asked several times but I am having following the trouble.

I am creating a simple hangman game, and I have created a keyboard, so there are 26 forms that look like this:

            <%= form_for @puzzle, :remote => true, :html => {:class => 'keyq'} do |f|%>
            <%= f.hidden_field :letters_guessed, value: "Q" %>
            <% end %>

I store the letters in an array type db field :letters_guessed

which I then use to loop to see if the user has guessed the letter.

<div class="mystery">
            <% @puzzle.word.length.times do |digit| %>
                <% letter = @puzzle.word[digit] %>
                <% if @puzzle.word[digit] == " " %>
                <br>
                <% elsif @puzzle.letters_guessed.include?(letter.upcase)%>
                    <%= letter %>
                <% else %>
                    <%= "_" %>
                <% end %>
            <% end %>
</div>

So essentially, I need to update the mystery div with the new array. As of now, when I submit the form, nothing happens (to be expected I suppose).

Here is my controller action

    def update
      @puzzle.letters_guessed = @puzzle.letters_guessed + [params[:puzzle][:letters_guessed]]
      @puzzle.save
      respond_to do |format|
        format.html
        format.js
    end

The idea here is that I create a new array, and save it. Now comes the part I'm not sure what to do with the renders.

I've created a _puzzle.js file in the same directory as the other views... How do I get the new array back to my view without actually refreshing the page?

Peege151
  • 1,518
  • 1
  • 20
  • 40

2 Answers2

1

try creating update.js.erb inside the app/views/YOUR_MODEL/ and simple put alert("Goes here");

It will be a great start.

Dan Rey Oquindo
  • 244
  • 1
  • 3
  • 11
0

Well, as you have already stated in your question, you need to use AJAX to submit the form and then on success callback, you get back the content of _puzzle.js.erb file. What you need to do after that is modify your DOM. This is most easiest done with jQuery. jQuery also has nice AJAX functionality with which you can do your AJAX requests. Please also read this as it shows you an example of submitting the form.

Good luck!

Community
  • 1
  • 1
Roope Hakulinen
  • 6,781
  • 4
  • 37
  • 63