0

In my Rails application, I add a certain user to the reader's list when he views a certain post.

PostsController#Show

@post = Post.find(params[:id])
if (current_user)
  @post.reader_links.create(reader_id: current_user.id)
end

However, I want to implement this from the client side, using javascript and ajax request. The feature will be slightly changed so that the user will be added to the list ONLY when he types into a certain form(presses a key).

So the original code will be replaced by the following code in posts/show.erb.html

function typeCatch(){
  $(this).off("keypress",typeCatch)//remove handler
  //I WANT TO ADD THE USER TO THE LIST AT THIS POINT
}

$("#field_id").on("keypress",typeCatch)

I need some help to implement the original feature in javascript and posting through ajax request. Any help will be greatly appreciated.

2

1 Answer 1

1

Something in this lines:

# on a controller
def update_links
  @post = Post.find(params[:id])
  if (current_user)
    @post.reader_links.create(reader_id: current_user.id)
  end
end


// on your javascript
function typeCatch(){
  $(this).off("keypress",typeCatch)//remove handler
  $.post('/path/to/controller/post_id/action')
 }

 $("#field_id").on("keypress",typeCatch)

Note that the javascript should not be the answer of your new action, but must be in the page that triggers the event of creating a new reader link.

If you have no idea of what you are doing, I recommend reading the links that @FlufflyJack commented in your question

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This helped me a ton! I also understand unobtrusive ajax request much better than before just by dealing with this example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.