简体   繁体   中英

making rails respond_to format js for an Ajax request

I'm trying to make an Ajax request that makes an update upon a radio button click without reloading an entire page.

Update action definition in my controller. There really not that much info on this part in the Rails docs.

 def update
    if @rsvp.update(rsvp_params)
      respond_to do |format|
        format.js
      end
    end
  end

update.js.erb, not sure if this code even works, but I can't test it since Rails is not even finding it:

$(document).on('ready', function() {
    $('.rsvp').on('click', function(e) {
        e.preventDefault()

        var user_id = $(.rsvp).data('user-id')
        var rsvp_id = $(.rsvp_id).data('rsvp-id')

        $.ajax({
            type: 'POST',
            url: "users/" + user_id + "/rsvps/" + rsvp_id
        }).done(function(response){ console.log('hello?', response)
        })
    })
})

App currently breaks down with ActionController::UnknownFormat in RsvpsController#update at the respond_to line. This posting is an extension of this one, which is trying to solve too many problems at once .

log

Processing by RsvpsController#update as HTML
  Parameters: {"utf8"=>"✓", "rsvp"=>{"event_id"=>"16", "status"=>"attending"}, "user_id"=>"1", "id"=>"11"}
  Rsvp Load (3.3ms)  SELECT  "rsvps".* FROM "rsvps" WHERE "rsvps"."id" = $1 LIMIT $2  [["id", 11], ["LIMIT", 1]]
   (0.2ms)  BEGIN
  Event Load (2.5ms)  SELECT  "events".* FROM "events" WHERE "events"."id" = $1 LIMIT $2  [["id", 16], ["LIMIT", 1]]
  User Load (1.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  SQL (0.7ms)  UPDATE "rsvps" SET "status" = $1 WHERE "rsvps"."id" = $2  [["status", 2], ["id", 11]]
   (2.4ms)  COMMIT
Completed 406 Not Acceptable in 82ms (ActiveRecord: 20.6ms)



ActionController::UnknownFormat (ActionController::UnknownFormat):

app/controllers/rsvps_controller.rb:19:in `update'

UPDATE

in my routes file, I did resources :rsvps, defaults: { format: 'js' } . This got the app to process the request as JS, instead of HTML, but now it renders the update.js.erb file. DB gets updated, but no partial reload happens as desired.

try like this

$.ajax({
        type: 'POST',
        url: "users/" + user_id + "/rsvps/" + rsvp_id,
        contentType: "text/javascript"

    }).done(function(response){ 
       console.log('hello?', response)
    })

Or

 $.ajax({
        type: 'POST',
        url: "users/" + user_id + "/rsvps/" + rsvp_id.js
    }).done(function(response){ 
       console.log('hello?', response)
    })

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