I am trying lot to get it work but no luck..any jquery expert can share there view please.
i have form, for validation i use form validation plugin (jquery) which doese validation correctly when i put.
$("#contact").validationEngine(); // #contact is my form id.
now i want to submit the form using ajax on button click (submit form button) which is also happening correctly using following.
$(".button").click(function() {
ajax code goes here ...
}
here problem is when i click on submit button it goes and update database it does not wait for formvalidation plugin to validate it...
what actually i want to do is first validate the form if all okay then go and call ajax function to update the database. if validation fails then dont call ajax function to update data base.
could any one please share some clues.
Thank you in advance...
regards, Mona.
$(function() {
$("#contact").validate({
rules: {
},
submitHandler: function(form){
ajax call
}
});
});
orignal post jQuery: validate before submitting try if this helps to resolve your issue..
Related
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.
I have a form_for an #object with two buttons.
While the first button renders the 'show action', the second button renders the same form again. So I'd like the latter to be ajax-handled.
Is it possible to have a non-ajax button and an ajax button in the same form or do I have to change strategy?
Maybe I need a form_for with 'remote: true' so that both the buttons are ajax but then, how would I manage the first button to render the proper 'show view'?
Or maybe the only real solution is to have two different forms?
Thank you.
You could try to hook onto the buttons onClick event, remove the data-remote="true" attribute, submit the form and add data-remote="true" again. I dont know if this is really the best way but it should work.
function sendWithoutAjax() {
$('my_form_id').removeAttr("data-remote");
$('my_form_id').submit();
$('my_form_id').data( "remote", "true" );
}
Something like this...
I think the easiest approach would be to use the jQuery Form plugin. Then you can just create the form to submit to your non-ajax action, and the ajax functionality will be attached to the submit button itself:
$(".ajax_submit_button").click(function() {
$(this).closest("form").ajaxSubmit({
// options go here
...
});
return false;
});
I have a "change password" page that needs to hash any passwords entered on the page via Javascript before sending. To complicate it, the page is loaded via a jQuery load() call, and is submitted by a jQuery.Form ajaxForm() call. Had everything working in MVC2, but MVC3 is giving me trouble.
That is, I have a page with a "Change Password" link that when clicked, loads the change password page into a jQuery modal popup, then the form on the change password page get's submitted via the jQuery.Form library (Essentially just wraps a $.ajax call), and returns it's result into the modal same modal popup.
Essentially, I have a model with two properties, OldPassword and NewPassword. I have two hidden fields generated by by view for these. They hold the hashed value of two other fields, PrehashOldPassword and PrehashNewPassword, and get updated via keyup events (I know, this means it does a whole SHA256 hash on every keyup... inefficient, but got the job doen for testing). The key here is that the regex validation and required field validation needs to be executed on these Prehash fields, which exist on the client side only (As obviously I don't want to transmit these fields to the server in any way).
So I manually create these two and add on the data-val-* attributes to the elements, i.e. they are NOT generated by the MVC helpers, etc. I am guessing that this is where I'm missing something. When the form submits with all fields empty, all of the errors popup that should, but the form goes right ahead and submits anyway.
==
So the things I've tried:
Yes, the unobtrusive library parse() method already get's called to parse the AJAX loaded form contents, and it appears to get all of the data validation stuff correctly, since I see the errors show up as fields blur(), and when I hit submit (before the ajax request completes and replaces the content of the popup).
Possible note: this call to the unobtrusive library's parse method happens AFTER the AJAX successfully loads the change password page into the popup... the AJAX form submit binding is put on document.ready of the loaded content, ergo, the AJAX form submission binding MAY be binding prior to, and thus firing before, the validation calls that the parse method may bind to the submit event...
However, (1) I am doing this same sort of thing in other places without issue, the ONLY DIFFERENCE being that I am manually putting these data-val-* attributes on elements I am creating manually! And (2), if I cause some kind of error on the OldPassword or NewPassword fields, i.e. a required field validation error by not loading a value into them, they display their error, and successfully STOP the form from submitting through the jQuery.Form method.
So I think something has to be wrong here:
<input id="PrehashNewPassword" type="password" name="PrehashNewPassword" data-val-required="The password field is required." data-val-regex-pattern="<%= RegexHelper.PasswordRegularExpression %>" data-val-regex="<%= RegexHelper.PasswordRegularExpressionError %>" data-val="true" />
I know that jquery.validate is getting the rules right, since I DO see the errors. It's just not stopping the form from submitting when their is an error in these manually generated elements, unless I do something like this, and add a pre-submit callback on the form's AJAX submission:
$("#ChangePasswordForm").ajaxForm({
beforeSubmit: function () { if (!$('#ChangePasswordForm').valid()) { return false; } },
target: '#overlay'
});
While this works, it is kind of ugly and I believe it causes the validation to be called twice... Not a huge deal, but less than ideal. So is there some other call that I need to make in the unobtrusive library to bind these?
Not sure if you found the problem, but you may try to
return false
in there if the form is not valid...
.
.
.
if (!$('form').valid()) {
return false;
}
// JSON POST...
.
.
.
If that doesn't work, then you could try to use:
$.validator.unobtrusive.parse($("#dynamicData"));
after dynamically adding your custom inputs. "dynamicData" is the ID of an element wrapped around the form
above found from here: http://weblogs.asp.net/imranbaloch/archive/2011/03/05/unobtrusive-client-side-validation-with-dynamic-contents-in-asp-net-mvc.aspx
Out of interest, what happens if you just get the form to validate?
<script type="text/javascript">
$("form").submit(function (evt) {
// validate here should trigger invalid fields
$('form').valid();
// JSON POST...
// stop form submitting
evt.preventDefault();
});
</script>
on my page I have the following:
<span id="attach-file" class="link">Attach a file</span>
<div id="attach-file-form">
</div>
Give that attaching a file is not a common use case, I don't want the attach-file-form elements to be present on load, it would slow everything down.
What I would like to happen is the user clicks "Attach a file", jQuery AJAX GET to get the form and inject it inside of attach-file-form.
What's the right way in Rails to go about this?
in jQuery I have:
$("#attach-file").live("click", function() {
DO A GET TO A custom Method in the Attachment Controller
Inject inside the div
});
Does this sound right?
Having the file upload form present on the page but hidden will have pretty much zero impact on the performance of your site. I'd recommend just defaulting the file upload form to hidden, and triggering display of the form when your button is clicked.
Then your JQuery code can be as simple as:
$("#attach-file").live("click", function() {
$("#file_upload_form").show();
});
If you do need to get this from the server, you can use the jQuery.get method to make a call to a Rails controller, which can output the form for you:
$("#attach-file").live("click", function() {
$.get("/controller/action", function(html) {
$("#file_upload_form").html(html);
}
});
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.