How can I update a hidden form field on AJAX submit in Rails 3? - ruby-on-rails

Questions on Rails 3.0.7, and JQuery 1.5.1
Overview
I'm trying to do the following thing. I have a web page with a form on one side that lets me create a category, and a list of items on the other side, with a checkbox for each item. I would like to be able to check the check box, for each item, so that when I submit the form to create the category, the newly created category also creates a has_many through association with each item.
So the association part works almost, I can submit a list of checked checkboxes, and Rails creates the association on the backend if I send the list of checked items.
Problem:
Here's what doesn't work:
I am trying to submit the form via Ajax, so I wanted to bind an event handle to the rails.js 'ajax:beforeSend' event, so that it would scan through my list of checked checkboxes and at the checked ids to a hidden form field.
The problem is: I try to get a list of all the checked boxes, and add them to the hidden field when the user clicks the Submit button. Therefore, I figured I'd place the code to do so in the ajax:beforeSend event handler. What I "THINK" I'm noticing however, is that rails.js has somehow already processed the form fields, and constructed the HTTP query before this handler fires. I notice this through the following behavior:
Observed Behavior
1) I can reload a fresh page, click the button to submit the form, the alert boxes from my handler pop up saying that no boxes are checked, and the created category in my db has no associated items (CORRECT BEHAVIOR)
2) I then click 1 checkbox, the alert boxes pop up showing which boxes are checked (CORRECT). But then when I submit thee form, the category in the DB still has no associate items. And I can see through firebug and the server logs that and HTTP query was sent containing the old parameter list, not the newer one. (WRONG)
3) I then submit the same form again, changing nothing, and it shows me the correct number of items.
So I get the impression that the parameter construction is lagging. I hope this wasn't too long, an someone can help me figure out what is going on.
My Question:
What event do I need to bind to, so that the form gets submitted with the correct parameters? Or is there another way to go about it completely?
Thanks
Here's my code below.
Thanks,
$('#my_form')
/* Now we need to configure the checkboxes to create an association between
* the items, and the interaction that is being created. First we will bind a
* function to the click event, and if the box is then checked, we will add
* the item id to the list of interaction items. If it is unchecked, we will
* remove the item from the list of interaction items.
*/
.live('ajax:beforeSend', function(event){
// First get a list of all the checked Items
var checked_items = new Array();
$('#items input[type="checkbox"]:checked').each(function(){
checked_items.push(this.getAttribute('data-item-id'));
});
// Then add this list of items to the new_interaction form to be submitted
$('#interaction_new_items').val(checked_items);
alert(checked_items);
alert($('#interaction_new_items').val());
})

Bind to the click event on the submit button itself. The click event will be processed before your ajax beforeSend event.
$('#my_form .submit').click(function() {
// rest of your code here
});

A more flexible solution (say, in case you wanted to submit the form with something other than a click) would be to bind to the form's submit event.
$('#my_form').submit(function() {
// Tweak your form data here
})

Related

Displaying Data on Page without refreshing

MVS 2010 MVC 3:
I have a Submit page that has severial checkboxes that are been built dynamically as soon as the page load. The user can check one or more checkbox before submitting the form. On the right hand side of the page, there is somewhat a summary of all the previous selections that the user chose. The summary is available from the Submit page and will carry to the other pages. There is an "Add Comment" button at the very top of the page. When the user click it, a popup window with a textbox will display allowing the user to type a comment. How do I display this comment on the page without having a refresh the page?
The main reason for not wanting to do a refresh is because the user could have selected one or more checkboxes, they will lose their states as soon as the page is refreshed.
I tried parent.document.getElementById('DivCommentResult').html(data); - It displayed this message "Microsoft JScript runtime error: Unable to get value of the property 'html': object is null or undefined"
If I understand well, you have to bind the change of your check box to a function that submit a synchone ajax request that obtain the summary you need and replace target content with the result data of your request.
Is it what you want ?
I had to get the parent doucment and retrieve the div id from it.
Once I have it in hand, I set its innerHTML text to the data that I want to display.
var parentDocument = parent.document;
var el = parentDocument.getElementById('commentResult');
Once I have this, I simpley call el.innerHTML = data;

How can I manipulate a form / inputs to be ignored when a form is submitted

I'm using ExpressionEngine and SafeCracker along with Ajax (plugin: jquery.form.js - http://jquery.malsup.com/form/).
Best I can tell, SafeCracker will only allow for updating a single entry at a time. However, the UI / UX necessitates that a list be displayed. I've proof of concept'ed an entry by entry on-demand form. That is, click a particular edit link next to each entry and a snippet of jquery creates a form along with displaying a submit button. Click submit and that single entry updates. The inputs don't exist until the Update link is clicked
What I would prefer to do, if possible, is to create the non-form and form versions of each entry as the page is renbered and use some sort of toggle to display one or the other. Again, doable. Then, when I click the Edit link I'd add the necessary attributes to the input so that entry's form elements will be read but the other (display: none) elements for the other entries will be ignored. I'm thinking (out loud) that if I add the attr("name", some-value) that would work. That is, an input with no name will be ignored.
Yes, I can test this and I will. However, even if it works I'm not sure if it's a best practice and/or there's a more ideal way of accomplishing my ends. I'm here looking for validation and/or additional expertise and input.
Thanks in advance.
Just set disabled property to inputs and they will excluded from Form submission, whatever input fields are hidden or visible. Different jQuery methods, like submit() and serialize() follow specification of HTML 4 and exclude all disabled controls of a forms. So one way is to set
$('your_input').prop('disabled', true);
or ,
$('your_input').attr('disabled', 'disabled');
Check following link:
http://www.w3.org/TR/html401/interact/forms.html#successful-controls
Also, you may use a general button instead of a submit, as result you can handle click event on it and within that event you can make exclusion, validation, manipulation on values and what ever you like.
You can put a disabled attribute on them server side or set the property via jQuery:
$(".hidden input").prop("disabled", true);

Sending javascript array with form data

i have 2 <g:select> elements in my gsp and both allow multiple selection (listboxes). I wrote some javascript that adds the option clicked by the user to the other select.
I build an array of items in select2.
I also have a form, that consist of checkboxes and such and submit button.
My problem is that I need to send that javascript array along other form data ( when i press submit ), to the controller. I just can't figure out a way, to send it.
Select box will get serialized and send with other form components, if you set every option to "selected = true".

How to get multiple and individual update actions on product lines in mvc?

I've got a list of products in an admin section of my website. I have the product title and then an icon for delete and an icon for set visible/set invisible. I have both icons wrapped in their own form elements so they fire seperate Actions. I now one to add some checkboxes to each line so I can do a bulk delete. Following this:
How to handle checkboxes in ASP.NET MVC forms?
I'd need to wrap the whole list in a form tag to return the checkbox values, but then I have the icons on each row wrapped in form tags. I'm not sure what to do or how to handle this so it all works. How can I maintain the line form tags but still get bulk update functionality?
It's probably going to require some JavaScript. I would create a form outside of the table with a hidden element. When a box is checked, update the hidden element to contain a comma-separated list of all the IDs for rows that have the checkboxes checked (this would be pretty straightforward with jQuery). When that form is submitted, parse the values of the hidden element and delete accordingly.
Another option is to wrap the whole thing in one form and make the names of the delete buttons unique, then check for that when the form is submitted. When doing a bulk delete, you'll have all the checkbox values submitted like normal and you'll know it's a bulk delete based on which button they pressed to submit the form.

How do I repopulate everything in a wizard style page for ASP.NET MVC?

I've got a page that creates a ticket in our help desk system. It acts as a wizard with the following steps:
Step 1
User selects the customer from a dropdown list. There is a jquery onchange event that fires and generates the list for step 2 and hides the step1 div and shows the step2 div.
Step 2
User selects the location from a dropdown list. This is generated based on the customer selected in step 1. There is a jquery onchange event that fires and generates the list for step 3 and hides the step2 div and shows the step3 div.
Step 3
User selects the type from a dropdown list and enters text into 3 different text boxes. If the user fails to enter text or enters invalid text my controller changes the model state to invalid and returns the view.
How can I get all the dropdowns to repopulate again with the correct selection the user chose and get the page to redisplay on Step 3?
My first thought was to use ajax and when the user clicks the Create button, I could create the ticket from there and if successful send them to the ticket detail. If unsuccessful, well just display an error message and i'm still on the page so no big deal. Now that I write it out I think this is best. Are there any major issues using ajax? It seems most sites use some type of javascript or ajax these days.
Second thought is to not use ajax at all and submit all the pages to the server.
What do you suggest?
The 3 steps display completely different markup.
There is possibly not much you can gain by an AJAX-version, except the avoided page flicker when you change the steps.
If you go the non-AJAX way you gain:
nice bookmarkable links ( www.ticketsystem.com/Customer -> www.ticketsystem.com/Customer/Microsoft/ -> www.ticketsystem.com/Customer/Microsoft/Location -> www.ticketsystem.com/Customer/Microsoft/Location/Redmond )
browser history works
easier testing
To redisplay the lists after step 3 you would load all of them and set the selected item according to the parameter in the URL.
I agree with you. Use AJAX to submit the ticket.

Resources