2

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

8 Comments

are you basically saying not to use json? in controller @var = "something to send", then define it in a function in .js.erb and call that function in application.js?
my mistake. read this backwards, call the function in ap.js from js.erb. but using that method, how do i send the data from js.erb to be picked up in application.js ? someFunction(some,args,to,pass) ?
Silly example but you'll get it: If application.js defines a function called 'logRabbits()', you would have in your create.js.erb: logRabbits('<%= @rabbits.count %>')
i just mocked something up. i believe this will do what i need. i got too wrapped up with this json stuff to look at it from another angle. thank you for assisting.
just for what it's worth. is it just not possible to do send json back from a dataType: 'script' request?
|
1

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

2 Comments

changing data type to json breaks the .js.erb
Right, you set it to json in order to get the server to respond with json.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.