简体   繁体   中英

How to respond to AJAX form submission in Rails?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM