views:

2732

answers:

2

I'm using this in a Rails app. and I have some code that changes the response type to javascript.

jQuery.ajaxSetup({
    'beforeSend': function(xhr) {
        xhr.setRequestHeader("Accept", "text/javascript")
    }
})

This works fine when submitting a form, but it doesn't seem to be called when submitting the javascript form generated by AJAX to click on a link (the code continues to go through the Rails html responder).

Probably a simple fix. Any ideas?

A: 

I'm not sure what you mean by "javascript form generated by AJAX" -- is it possible that you are generating a form in the DOM with javascript then doing a regular submission with it by clicking (via javascript) a button? If so, then it's not being submitted via AJAX, but rather as a normal post. The beforeSend handler is only invoked when the form is submitted via AJAX. Your set up call is adding a default beforeSend function that sets the Accept header so that javascript is returned, but it only does so on requests submitted via AJAX.

This is what an AJAX submission looks like:

$.ajax({
   url: '/controller/action',
   type: 'post',
   dataType: 'json',
   data: $('form').serialize(),  // this gets the form data
   success: function() {
   },
   ...
});

This is a javascript-created form and submission (non-AJAX).

$('<form><input type="hidden" name="inp" value="somedata" /></form>')
    .appendTo(document.body)
    .submit();

or (via a button click)

$('form #submitButton').click( function() {
    $('form').submit()
});
tvanfosson
+1  A: 

The XHR header setting is required with JQuery if you want to use Rails' respond_to ... format blocks. Prototype sets this by default, but you need to set it manually in JQuery, as the format.js option gets executed when text/javascript is in the accept header.

Are you sure your AJAX request is actually firing? Perhaps you handler isn't attached and the link is sending a normal HTTP GET?

Ian Webb