Reputation: 36773
Here is a simple Tell a Friend form I made in HTML, it's correctly POSTING the data back to my server and submitting correctly.
Here's the javascript code (it's in CoffeeScript):
$('#tell-a-friend-form').submit (e) ->
e.preventDefault()
console.log "submitted form."
$.ajax
url: 'home/tellafriend'
type: 'POST'
data:
name: $(this).find("input[name='name']").val()
emails: $(this).find("input[name='emails']").val()
message: $(this).find("textarea[name='message']").val()
success: (result) ->
alert("ok")
$('#tell-a-friend-form').find(".loading-icon").hide()
error: (result) ->
alert("Sorry, we couldn't send your message.")
$('#tell-a-friend-form').find(".loading-icon").hide()
$('.tell-a-friend-submit').removeAttr("disabled")
$(this).find(".tell-a-friend-submit").attr("disabled", "disabled")
$(this).find(".loading-icon").show()
Now, in the Controller, I don't need to return any message at all, except maybe a "sent ok" type of boolean so the client side javascript can know whether to "success" or to "error".
Currently, the client side fires "error" every time.
Here's my Controller code:
def tellafriend
#send the actual email message. to be implemented.
respond_to do |format|
format.json { render :json => "success" }
end
end
Anything I'm doing wrong on the controller side? I'm sure the problem lies here. What do I need to return in case I want the "success" bit to fire?
Upvotes: 0
Views: 1830
Reputation: 17930
What do your logs show you when you make the request? This is important for diagnosing this sort of thing. There are three things I can think of that usually fix this:
Explicitly Request JSON
It might be as simple as explicitly requesting JSON from your AJAX call:
$.ajax
url: 'home/tellafriend'
type: 'POST'
dataType: 'json'
...
Check Your Routes:
Your route might not be configured to respond to POST requests. Ensure your route for 'tellafriend' accepts post. As a quick check you could change your AJAX request to 'GET' or visting /home/tellafriend.json
Return a Valid Object
Instead of simply returning "success" You might want to try returning an actual object:
respond_to do |format|
format.json { render :json => {:message => "success"} }
end
Upvotes: 2