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,562
  • 2
  • 21
  • 45

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
  • 276
  • 1
  • 3
  • 11
  • I got that showing up thanks!... what about the call to get the array? – Peege151 Dec 17 '14 at 07:52
  • all instance objects are available in update.js.erb , try alert("<%= @puzzle %>"); – Dan Rey Oquindo Dec 17 '14 at 07:53
  • should I create a loop for js and not ruby then? to see if the player has guessed the letters? – Peege151 Dec 17 '14 at 08:01
  • Okay. It seems that this is your first time. What I normally do is to separate the view into a partial. Then i render it again. $("#container").html("<%= escape_javascript(render 'model/partial_name', object: @object) %>") – Dan Rey Oquindo Dec 17 '14 at 08:06
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
  • 7,326
  • 4
  • 43
  • 66