As I mentioned in a question last week, I’m working with @coreyward‘s excellent walk-through for modal edit windows in Rails 3. However, I’m a relative novice with Coffeescript, and I’m having trouble with the code which is supposed to display the modal window on a successful Ajax response. This is the relevant function (drawn from Corey’s gist):
$ ->
$modal = $('#modal')
$modal_close = $modal.find('.close')
$modal_container = $('#modal-container')
# Handle modal links with the data-remote attribute
$(document).on 'ajax:success', 'a[data-remote]', (xhr, data, status) ->
$modal
.html(data)
.prepend($modal_close)
.css('top', $(window).scrollTop() + 40)
.show()
$modal_container.show();
$(document).on 'click', '#modal .close', ->
$modal_container.hide()
$modal.hide()
false
I’ve established that all the code inside the function works; it just never gets called. I can see the Ajax query in the Chrome network panel, and verify that it returns a proper response.
I simplified the code to pop up an alert on an ajax:success event:
$(document).on 'ajax:success', () ->
alert('Ajax success event!')
…and nothing. So I think the `ajax:success’ event is never happening.
Trying to extract the simplest possible code that duplicates the problem, I set up this jsFiddle with the following code:
<a href="javascript:$.ajax('/echo/js/?delay=2&js=WHEEEEE!');" data-remote="true">Edit</a>
$(document).on 'ajax:success', () ->
alert('Ajax success event!')
…yeah. Nothing. The jsFiddle Ajax echo returns what it should, but the function never gets called. So I’m doing something wrong with .on('ajax:success'). (This is sort of the opposite problem as this question, so that answer isn’t helpful. This question, about the mime-type of the response, looks promising, but doesn’t explain why the jsFiddle doesn’t work, because that doesn’t touch my controllers.) What is it?
ETA: I should probably mention the stack involved here. facepalm
- Rails 3.2.8
- jquery-rails 2.1.3
- …which means jQuery 1.8.2
OK, got it. I needed to make two changes:
text/jsonMIME type on the response. My action previously looked like this:To get a
text/jsonresponse I wound up with this:That change triggered
ajax:successand therefore ran the open-modal functions.data.htmlrather than justdata, I needed to tweak themodal.js.coffeeto actually put markup in the modal: