How to use MicrosoftMvcValidation with jQuery.Ajax in ASP.net MVC2? - asp.net-mvc-2

using asp.net mvc2, Data Annotations,
MicrosoftAjax.js,MicrosoftMvcValidation.js,
jquery for ajax
I have contact form and i am using Data Annotations for the ContactFormModel.
I add this line <% Html.EnableClientValidation(); %> to top of the form.
When i click the submit button client validation works perfectly. Now i have changed my mind and want to post the form with jQuery.Ajax.
This time i want to accomplish this.
Click submit button.
MicrosoftMVCValidation does the client validation and renders the errors on the clientside.
If Model is valid i meant if the validation passed i want my jQuery ajax to get involved.
But when i clicked the submit button both ajax post and mvc client validation works.
How can i get the things in right order.
1.Mvc Client validation
2. Then jQuery.Ajax Post.

var myForm = $("#MainForm");
var formContext = myForm[0]['__MVC_FormValidation'];
var errors;
if (formContext) {
// validate the form
errors = formContext.validate("submit");
}
if (!formContext || errors.length == 0) {
// no errors so submit to server
...
}

Related

How to do a form submit in moodle from some other page?

In moodle, when you go to Quiz Administration-> User overrides -> Add user override, you get a form (overrideedit.php) to add the details of the user override to be created.
You need to fill that form and submit it. After you submit, the form is processed (in overrideedit.php itself) and then you are redirected to overrides.php page.
Now, I want that form to take post data from my plugin and process it in overrideedit.php and do the redirect.
How do I send post data in this case from my plugin?
You could set a different action for the form you're having in your plugin (this assumes you are using Moodle Form API for your custom form):
// Instantiate your form
// Data will be submitted to /mod/quiz/overrideedit.php
$mform = new custom_form_your_are_having(new moodle_url('/mod/quiz/overrideedit.php'));
Or simply change the action attribute of your custom for to point to /mod/quiz/overrideedit.php:
<form action="/mod/quiz/overrideedit.php" method="post">
...
</form>

loading html FORM asynchronously and adding it into DOM does'nt get validated by jQ validation plugin

A simple get request made to url on my server which returns HTML of form which is put inside td element .
$('form').validate(); // jquery validation plugin initialized
//user clicks some button and ajax request is send to load form
$.get(url,send,function(form){
$('td').html(form).show();
});
Problem is validation plugin do not work on the loaded form ?
The form you are trying to validate does not exist when you initialise the plugin. Place the initialisation code in the success handler of the $.get(...).

how to redirect a page through controller in zend

When I click on a submit button i want the page to redirect to the following page?
header('Location: /pdp/policy-info.phtml');
I wrote the above code in the controller code but I am not able to redirect to the above page. it stays on the same page.
the filename is called policy-info.phtml in the view.
Also once I redirect, would I be able access my form values through $_POST?
Or is there an alternative.
ok it sounds to me like you may be missing a few concepts:
You will never redirect to a phtml file. (unless you have written some custom rewrite/route rules) Zend uses the MVC architecture, urls exist in this fashion: /module/controller/view/key1/value1/keyx/valuex/
generally zend urls don't terminate with file extensions. Also you will never directly call a view file from your browser.
In your form tag, you specify where the form submits to with the action attribute. For your url i'm assuming the pdp controller and policy-info action
action="/pdp/policy-info/"
If you want to redirect after a form submit from with your controller you would use:
$this->_redirect('/pdp/policy-info/');
# maybe you want to execute some code and then execute
# additional code in another controller without re-bootstrapping
$this->_forward('policy-info', 'pdp');
http://framework.zend.com/manual/en/zend.controller.action.html#zend.controller.action.utilmethods
If you redirect you will not have access to your POST unless you saved those values elsewhere (like in your session). If you forward, I believe the values will still be available in the second action.
actually there maybe a few ways to do what you want to do. I haven't tried this first method yet but it should work.
Render a new veiw script from your controller/action if isPost():
public function myAction(){
$form = My_Form();
$this->view->form = $form;
//if form is posted and submit = Submit
if ($this_request->isPost() && $this_request->getPost()->submit == 'Submit') {
if ($form->isValid($this->_request->getPost()) {
//this is where you want to capture form data
$data = $form->getValues();
//render a new viewscript or _forward to a new action and perform your processing there.
$this->render('path to phtml file');
//if user needs to press a button to accept submit = accept
...do some more stuff...
}
}
}
I think this or some variation will work.Note: I don't think _forward resets the request object, so your $_POST data should not be affected.
Also if this policy-info does not require additional input from the user and is just informational you could easily just _forward('action') to a blank action and the router will display the view script.

How can I make ASP.NET MVC3 client side form validation run before custom form post event

I have a view with a form that uses the unobtrusive client side validation in asp.net mvc 3 to validate the form fields.
I also have a custom jquery script to submit the form via ajax
$(document).ready(function () {
$('#Submit').click(function (event) {
/* collect form input values as json*/
/* post the json data via ajax */
event.preventDefault();
event.stopPropagation();
});
});
My question is how can I change the order of the event handlers so that the asp.net mvc 3 client side validation gets called before my ajax form post handler so that the asp.net mvc handler can prevent my handler from getting called if there are any validation errors.
The problem I am having is that the asp.net mvc 3 unobtrusive javascript validation event handler is not triggered before my event handler.
By disabling the code at the end of my script that prevents further event propegation,
I can see that the asp.net mvc 3 client side validation is indeed getting triggered after my handler is executed.
You can call the method:
$('form').valid()
inside your event.
Maybe this posts helps:
jquery newbie: combine validate with hidding submit button
https://stackoverflow.com/questions/4539302?tab=newest#tab-top

Preventing form resubmission

Page one contains an HTML form. Page two - the code that handles the submitted data.
The form in page one gets submitted. The browser gets redirected to page two. Page two handles the submitted data.
At this point, if page two gets refreshed, a "Confirm Form Resubmission" alert pops up.
Can this be prevented?
There are 2 approaches people used to take here:
Method 1: Use AJAX + Redirect
This way you post your form in the background using JQuery or something similar to Page2, while the user still sees page1 displayed. Upon successful posting, you redirect the browser to Page2.
Method 2: Post + Redirect to self
This is a common technique on forums. Form on Page1 posts the data to Page2, Page2 processes the data and does what needs to be done, and then it does a HTTP redirect on itself. This way the last "action" the browser remembers is a simple GET on page2, so the form is not being resubmitted upon F5.
You need to use PRG - Post/Redirect/Get pattern and you have just implemented the P of PRG. You need to Redirect. (Now days you do not need redirection at all. See this)
PRG is a web development design pattern that prevents some duplicate form submissions which means, Submit form (Post Request 1) -> Redirect -> Get (Request 2)
Under the hood
Redirect status code - HTTP 1.0 with HTTP 302 or HTTP 1.1 with HTTP 303
An HTTP response with redirect status code will additionally provide a URL in the location header field. The user agent (e.g. a web browser) is invited by a response with this code to make a second, otherwise identical, request to the new URL specified in the location field.
The redirect status code is to ensure that in this situation, the web user's browser can safely refresh the server response without causing the initial HTTP POST request to be resubmitted.
Double Submit Problem
Post/Redirect/Get Solution
Source
Directly, you can't, and that's a good thing. The browser's alert is there for a reason. This thread should answer your question:
Prevent Back button from showing POST confirmation alert
Two key workarounds suggested were the PRG pattern, and an AJAX submit followed by a scripting relocation.
Note that if your method allows for a GET and not a POST submission method, then that would both solve the problem and better fit with convention. Those solutions are provided on the assumption you want/need to POST data.
The only way to be 100% sure the same form never gets submitted twice is to embed a unique identifier in each one you issue and track which ones have been submitted at the server. The pitfall there is that if the user backs up to the page where the form was and enters new data, the same form won't work.
There are two parts to the answer:
Ensure duplicate posts don't mess with your data on the server side. To do this, embed a unique identifier in the post so that you can reject subsequent requests server side. This pattern is called Idempotent Receiver in messaging terms.
Ensure the user isn't bothered by the possibility of duplicate submits by both
redirecting to a GET after the POST (POST redirect GET pattern)
disabling the button using javascript
Nothing you do under 2. will totally prevent duplicate submits. People can click very fast and hackers can post anyway. You always need 1. if you want to be absolutely sure there are no duplicates.
You can use replaceState method of JQuery:
<script>
$(document).ready(function(){
window.history.replaceState('','',window.location.href)
});
</script>
This is the most elegant way to prevent data again after submission due to post back.
Hope this helps.
If you refresh a page with POST data, the browser will confirm your resubmission. If you use GET data, the message will not be displayed. You could also have the second page, after saving the submission, redirect to a third page with no data.
Well I found nobody mentioned this trick.
Without redirection, you can still prevent the form confirmation when refresh.
By default, form code is like this:
<form method="post" action="test.php">
now, change it to
<form method="post" action="test.php?nonsense=1">
You will see the magic.
I guess its because browsers won't trigger the confirmation alert popup if it gets a GET method (query string) in the url.
The PRG pattern can only prevent the resubmission caused by page refreshing. This is not a 100% safe measure.
Usually, I will take actions below to prevent resubmission:
Client Side - Use javascript to prevent duplicate clicks on a button which will trigger form submission. You can just disable the button after the first click.
Server Side - I will calculate a hash on the submitted parameters and save that hash in session or database, so when the duplicated submission was received we can detect the duplication then proper response to the client. However, you can manage to generate a hash at the client side.
In most of the occasions, these measures can help to prevent resubmission.
I really like #Angelin's answer. But if you're dealing with some legacy code where this is not practical, this technique might work for you.
At the top of the file
// Protect against resubmits
if (empty($_POST)) {
$_POST['last_pos_sub'] = time();
} else {
if (isset($_POST['last_pos_sub'])){
if ($_POST['last_pos_sub'] == $_SESSION['curr_pos_sub']) {
redirect back to the file so POST data is not preserved
}
$_SESSION['curr_pos_sub'] = $_POST['last_pos_sub'];
}
}
Then at the end of the form, stick in last_pos_sub as follows:
<input type="hidden" name="last_pos_sub" value=<?php echo $_POST['last_pos_sub']; ?>>
Try tris:
function prevent_multi_submit($excl = "validator") {
$string = "";
foreach ($_POST as $key => $val) {
// this test is to exclude a single variable, f.e. a captcha value
if ($key != $excl) {
$string .= $key . $val;
}
}
if (isset($_SESSION['last'])) {
if ($_SESSION['last'] === md5($string)) {
return false;
} else {
$_SESSION['last'] = md5($string);
return true;
}
} else {
$_SESSION['last'] = md5($string);
return true;
}
}
How to use / example:
if (isset($_POST)) {
if ($_POST['field'] != "") { // place here the form validation and other controls
if (prevent_multi_submit()) { // use the function before you call the database or etc
mysql_query("INSERT INTO table..."); // or send a mail like...
mail($mailto, $sub, $body); // etc
} else {
echo "The form is already processed";
}
} else {
// your error about invalid fields
}
}
Font: https://www.tutdepot.com/prevent-multiple-form-submission/
use js to prevent add data:
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}