user1004277
user1004277

Reputation: 37

Ruby on Rails $.ajax({dataType: 'script'}) form submission with respond_to format.js and format.json

i have a form submitting via ajax. if form successfully submits, the page redirects elsewhere. if the form fails i rerender the form with partials (.js.erb) and inline errors.

this works fine.

the issue im having is i want to have to send some type of json response/data back to application.js when the page rerenders. Only, im not sure if this is possible.

//application.js

$(document).on('click','#sumbit_div',function(e) {
$.ajax({
   url: '/create',
   type: 'post',
   dataType: 'script',
   data: $('#the_form').serialize(),
   cache: false,
   success: function(xhr,data) {
     console.log('success');
   },
   error: function(data) {
     console.log('error')
     console.log(data.value_from_format_json);
   },
});
});

//create action in controller.

rescue ActiveRecord::RecordInvalid => e

respond_to do |format|
format.json {render :json => { :status => 403,:success => false }}  
format.js
end

I recognize that even a failed submission is a success in the .ajax response. i can deal with how to handle this after. Right now i'd just like to know if i can accomplish what im after.

last note is this is on rails 2.3 (still in the process of upgrading). But i have all jquery libs (rails.js/jquery.js/etc) update to work with ujs.

thanks

Upvotes: 2

Views: 3619

Answers (2)

mathieugagne
mathieugagne

Reputation: 2495

You should not send data to application.js but rather have application.js pull from your DOM. Make your create.js.erb modify the DOM so that application.js catches it.

Or even better, call your desired function from your create.js.erb passing along the parameters you want.

Upvotes: 2

cpuguy83
cpuguy83

Reputation: 5993

I'd imagine you need to change your dataType to json to get a "json" response or "js" for a js response.

Upvotes: 1

Related Questions