Sending form contents as both html and ajax? - ruby-on-rails

I have an admin form that updates a model via a html submit. I'd like to be able to send the form's contents to an Ajax modal dialog for a 'preview' via a link or button in the admin form.
Is there a way to send the form's contents to the modal dialog via Ajax without breaking the html submit? So far all I can do is get the data into the modal as html which breaks the js rendering. All the Ajax submit examples I find attach to the form which will break the html submit.
Suggestions and/or pointers are appreciated.
We are using Rails 3.2.12 for what it's worth.

I suppose it depends on how you are rendering your modal. If you're doing it server side and just need to get the form values to your ajax controller action you could do something like this with jquery"
$.post(ajaxUrl + "?" + $("#myform").serialize())
to generate a query string of your form values that you could sent to you ajax model.
Or if you're building the modal client side try
$("#myform").serializeArray()
to get an array of name, value pairs

This is what it took to get this to work under Rails 3.2.12
View:
<%= link_to 'Preview Promotion UI', admin_preview_promotion_url, id: :promotion_preview %>
The above link is inside the form do/end.
Javascript in application.js
$("#promotion_preview").live('click', (function (event) {
event.preventDefault();
$.post("/store/admin/promotions/preview",
$(event.currentTarget.parentElement).serialize().replace('=put&', '=post&'),
{},
"script"
);
}));
Rails.js injects some hidden code in the page that sets the type of response to PUT and then gets in the way of the routing. At least in this case simply replacing PUT with POST fixes things.
With this bit of code I can post my form updates as usual and activate a modal dialog "preview" using the form data.

Related

Select & onChange | Ruby on Rails

In my view, I have this form with the select function:
<form id="form_id">
<%= form.select('id','name', #document.informations.find(:all).collect {|u| [u.name] },
options={},{:onChange => 'submit()'}) -%>
</form>
How can I use the selected name in the rest of my view ?
I saw this in other topics:
$('#id_name').val();
But it didn't work for me, it says:
`$(' is not allowed as a global variable name
You're getting that particular error because the $('#id_name').val() is JavaScript, not Ruby, but you've put it within erb tags.
When you visit a page /documents/3 in your browser, Rails will run the code in your controller, and send back some HTML to your browser. That HTML can load CSS and JavaScript, but that's run after your Ruby program has finished - and may not be run at all, depending on the browser. How you use the name of the selected item in your view depends on what you're doing with it.
If you're storing it in the database somewhere, then you should start by getting this working just in Ruby. For instance, if your #document has a selected_informations attribute, you could use that in the rest of your page, and pass it to your form.select to pre-select it in the page. The Rails Guides documentation has more info on this.
If you're not storing it in the database, then you can get the value of your box out with JavaScript whenever it changes. Here's some sample code that prints out the name of the selected item to the JavaScript console whenever a <select> box gets changed. I've included it in <script> tags so you can drop it straight into your view for testing, but you should put it into a dedicated JavaScript file if you adapt it for your project.
<script>
$('select').on('change', function(ev) {
var selected_item = $(ev.currentTarget).val();
console.log("Your select value is " + selected_item);
});
</script>
One final thing to note is that your existing form.select tag is set up to call a method submit() whenever its value gets changed. submit is just a name, so that function could do anything... but I'd guess it's submitting the form whenever an item is selected. This sends a request to your Rails server and refreshes the page, so beware - if you're using an event listener on change to update the current page, you won't see those changes on the new, refreshed page (and should use a server-side solution instead).

Ajax Dropdown Selection to change TextArea Contents

I'm trying to use Ajax in one of my Rails applications to have a form_tag textarea change its contents according to the selected value of a dropdown that is out of that form_tag.
I would like to ask, what is the correct way of handling this ? Is it possible to respond to js in my show action and have a js.rjs ? Do you happen to know of any resources or can offer some insight ?
You should write a javascript, which triggers on the dropdown menu's onchange event, and start an ajax process. With jQuery it is something like this (in your show code within a script tag):
$("#dropdownMenuName").change(function(){
$.get("controller/action.txt", function(data){ $("#textareaName").val(data); } );
});
This simply sends a request to your app on the controller/action.txt action, and the result is pasted into the textarea's text property. Of course you should write the answer as a simple text, as the result is printed in the textarea instantly.

Rails and modal jquery dialog form

I'm new to using jquery modal dialog boxes with rails and was wondering how I can :
show a jquery modal dialog box
with 1 field (eg "title")
post this form to a rails controller (via
ajax)
have the modal dialog form
redisplay if field is not filled in
(with normal red css in error field)
Any tutorials or examples welcome.
Using Rails 3 and jQuery. Thanks for your time.
Here's an example of how I'd do it: https://github.com/ramblex/modal-form.
You should be able to:
download the app
run bundle
rake db:migrate
rails s
Go to localhost:3000/articles and the modal form should come up when you click on the 'New article' link.
An error message should be shown when the title field is left empty. Otherwise it should create the article and display it.
Hope it helps.
For modal box I use jQuery Tools.
Once you set that up, next step is to bind an ajax request when the form is submitted (eg: form.submit(function(){ $.post... })) and post the form's data to controller.
Third step is setting up your Rails controller to respond to ajax request (using respond_to block) and render something as response (probably using :layout => false).
If validation failed, you will replace content of your modal box with this response body, or if successful (let's say response was just head :ok), you will display a success message.
I hope this makes sense to you.

Submit form and clear value of text field (Rails)

I have a rails form to simply post data and using ajax, reload.
format.js{ render :update do |page|
page.reload
end}
I want to also, clear the value of a textbox inside the form because right now, the textboxes just keep the same value. If they were "hello" and the other was "world", I would click submit, it would run reload, and keep the same textbox values.
EDIT I'm using the default javascripts produced by rails. Prototype.js, application.js (etc.)
Try resetting for form like so:
page[:the_form].reset
You can also update a specific text field value:
page[:foo].value = 'Hello!'
If this is an AJAX call, I suspect the right way to clear the form is in your success callback from the ajax call. If you're using ExtJS or jQuery, this should be pretty easy to do, but without letting us know which JS library you use we can't be much more explicit.

How to submit without having a submit button on the form?

Can I have a submit in <% using (Ajax.BeginForm("ChangePassword", new AjaxOptions { OnComplete = "ChangePasswordComplete" })) without having a submit button on the form?
I yes, how? Let's say I want to submit the above when a user click on an input of type button simply?
You'd have to use Javascript to post back the form, jQuery has a submit method you can use.
$("#FormId").submit();
But really, an input of type button is the same as submit, only it submits automatically so you might as well use that.
Progressive Enhancement
Alternatively, you can use the jQuery Form plug-in to post a standard form (using Html.BeginForm or manually outputting the <form />) and that will work for people who don't have Javascript enabled on their browser.

Resources