Reputation: 634
I have a nested resource, project/:id/keys
and on .../keys/new
I have a form_for
, the behaviour of this form was modified in JS and its suppose to do a POST request on submit.
The POST request is working fine, but the problem is that it redirects me to another page, more exactly the form action which is 'projects/:id/keys' with the error that create template was not found.
def create
word = word_params[:name]
Word.creates_words word, @project
respond_to do |format|
format.html
format.json {render json: word}
end
end
$('#new_word').on "submit", (event) ->
event.preventDefault()
url = $(this).attr('action')
data = $('#word_name').val()
add_words(url, data)
add_words = (url, data_param) ->
$.ajax
type: 'POST'
url: url
data: word: {name: data_param}
dataType: 'JSON'
success: (json) ->
console.log(json)
Upvotes: 0
Views: 200
Reputation: 2441
Instead of making a manual AJAX request, I advise you to use the remote: true
parameter of the form_for:
<%= form_for ..., remote: true do |f| %>
# your form
Then, in your create action, you can simply do:
def create
# ...
respond_to do |format|
format.html
format.js {render json: word}
end
end
You can read more about the remote option here
However, if you still want to submit your data with your own AJAX request, you can just disable your submit button:
<button type='button' id='some_id'>Submit</button>
Upvotes: 1