Unobtrusive javascript with Rails 2.3.5

This is my handy little bit of javascript to make it easier to do UJS in Rails 2.3.5. Create a file within your public/javascripts folder called ajax.js containing the following:

//unobtrusive javascript replacements
//setup for format.js block
$.ajaxSetup({
	'beforeSend': function(xhr) { xhr.setRequestHeader('Accept', 'text/javascript') }
});

//for replacing remote_form_form
$.fn.submitWithAjax = function(){
	this.live('submit',function(){
		$.ajax({
			url: $(this).attr("action"),
			type: ($(this.form).find("[name=_method]").attr('value') == undefined) ? 'post' : $(this.form).find("[name=_method]").attr('value'),
			data: $(this).serialize(),
			dataType: 'script'
		});
		return false;
	});
}

//for replacing link_to_remote
$.fn.linkWithAjax = function(){
	//add new click binding
	this.live('click',function(){
		$.ajax({
			url: this.href,
			type: $(this).is('.delete') ? 'delete' : 'get',
			dataType: 'script'
		});
		return false;
	});
}

//Bind links and forms on load
$(function(){
	$('a.remote').linkWithAjax();
	$('form.remote').submitWithAjax();
});

Then include jquery 1.4.2 min and ajax.js in your header, my javascript include line looks like this:

  javascript_include_tag 'jquery','jquery-ui','jrails','ajax', :cache => true

Then all you have to do is give the form_for or link_to tags a class of remote, if you want to delete make sure you give the link a class of delete too. Please note the ajax.js file I have created expects a script back, but you can pass expect html or text content by removing dataType: ‘script’

If you do remove the dataType: ‘script’ option you may want to add a success function. so…

     this.live('click',function(){
		$.ajax({
			url: this.href,
			type: $(this).is('.delete') ? 'delete' : 'get',
			success: function(data){
                             alert(data);
                        }
		});
		return false;
	});

Hope it helps, post a comment if you have a question.

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay
  • StumbleUpon
  • Twitter

About Danny

Primarily a Ruby On Rails developer, but I can do other cool stuff too.
This entry was posted in Development, Javascript and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>