How to submit a form after confirming submit? jQuery, AJAX - javascript

Good day, I have a simple html page containing this form:
<form:form method="post" action="details" modelAttribute="code">
<form:input path="code"/>
<br/>
<input type="submit" value="Submit" />
</form:form>
When I press the Submit button I need to check whether there are some records in the database for given code using jQuery AJAX. If yes then popup jQuery UI dialog to ask user whether he really wants to display record details (because it's a paid service). If he confirms I need to submit the form. This is my script on the html page:
$(document).ready(function() {
// Bind an event handler to the submit event
$('form#code').submit( function() {
// Check whether there are some records in the DB using AJAX
$.ajax({
url: 'getResultCount',
type: 'post',
dataType: 'html',
data: $("form#code").serialize(),
success: function(result) {
if(result == 'null') {
$('div#results').html('<p>No records found for ' + $('input#code').val() + '.</p>');
} else {
// At leat one record was found so ask the user
$('#dialog-confirm').dialog({
resizable: false,
draggable: false,
height: 240,
width: 450,
modal: true,
buttons: {
"Display details": function() {
// User confirmed, submit the form
$('form#code').submit();
},
Cancel: function() {
$(this).dialog("close");
}
}
});
}
}
});
return false;
});
});
When I press "Display details" button nothing happens. I think it is because I'm entering the same submit handler which returns false. How to solve it so that form submit is executed? Please advise.
Thank you in advance.
Vojtech

Change
$('form#code').submit();
to
$('form#code')[0].submit();
It will skip the jQuery onsubmit function.
Basic example: http://jsfiddle.net/4Ax6m/

There is one simple answer: Do not use <input type="submit" ... />.
You can instead use <button onlick="handler()">Submit</button>, where handler() is your function bound to the submit-event of the form in the above code. If your handler decides that the form should be submitted just submit it programmatically. Edit: Which is actually already in your code.

You'd need to wait for the .ajax to succeed since it is currently running in async mode.
So disable it using the async option on ajax. Documentation Here
ANSWER SPECIFICALLY FOR YOU
JS
$(document).ready(function () {
// Bind an event handler to the submit event
$('form#code').submit(function () {
// Check whether there are some records in the DB using AJAX
$.ajax({
url: 'getResultCount',
type: 'post',
dataType: 'html',
data: $("form#code").serialize(),
async: false,
success: function (result) {
if (result == 'null') {
$('div#results').html('<p>No records found for ' + $('input#code').val() + '.</p>');
//No Records found, submitting!!
return true;
} else {
// At leat one record was found so ask the user
$('#dialog-confirm').dialog({
resizable: false,
draggable: false,
height: 240,
width: 450,
modal: true,
buttons: {
"Display details": function () {
// User confirmed, submit the form
return true;
},
Cancel: function () {
//TODO: Don't think you need this line?
$(this).dialog("close");
//CANCEL!!!
return false;
}
}
});
//User skipped Dialog somehow...ignoring....DO NOT SUBMIT
return false;
}
}
});
});
});
Note: This will return true and false to continue the submit process to the server

Related

How to run JavaScript code on Success of Form submit?

I have an Asp.Net MVC web application. I want to run some code on the successful response of the API method which is called on form submit.
I have the below Code.
#using (Html.BeginForm("APIMethod", "Configuration", FormMethod.Post, new { #class = "form-horizontal", id = "formID" }))
{
}
$('#formID').submit(function (e) {
$.validator.unobtrusive.parse("form");
e.preventDefault();
if ($(this).valid()) {
FunctionToBeCalled(); //JS function
}
}
But FunctionToBeCalled() function gets called before the APIMethod(), but I want to run the FunctionToBeCalled() function after the response of APIMethod().
So I made the below changes by referring this link. But now the APIMethod is getting called twice.
$('#formID').submit(function (e) {
$.validator.unobtrusive.parse("form");
e.preventDefault();
if ($(this).valid()) {
//Some custom javasctipt valiadations
$.ajax({
url: $('#formID').attr('action'),
type: 'POST',
data: $('#formID').serialize(),
success: function () {
console.log('form submitted.');
FunctionToBeCalled(); //JS function
}
});
}
}
function FunctionToBeCalled(){alert('hello');}
So I am not able to solve the issue.
If you want to execute some work on success, fail, etc. situation of form submission, then you would need to use Ajax call in your view. As you use ASP.NET MVC, you can try the following approach.
View:
$('form').submit(function (event) {
event.preventDefault();
var formdata = $('#demoForm').serialize();
//If you are uploading files, then you need to use "FormData" instead of "serialize()" method.
//var formdata = new FormData($('#demoForm').get(0));
$.ajax({
type: "POST",
url: "/DemoController/Save",
cache: false,
dataType: "json",
data: formdata,
/* If you are uploading files, then processData and contentType must be set to
false in order for FormData to work (otherwise comment out both of them) */
processData: false, //For posting uploaded files
contentType: false, //For posting uploaded files
//
//Callback Functions (for more information http://api.jquery.com/jquery.ajax/)
beforeSend: function () {
//e.g. show "Loading" indicator
},
error: function (response) {
$("#error_message").html(data);
},
success: function (data, textStatus, XMLHttpRequest) {
$('#result').html(data); //e.g. display message in a div
},
complete: function () {
//e.g. hide "Loading" indicator
},
});
});
Controller:
public JsonResult Save(DemoViewModel model)
{
//...code omitted for brevity
return Json(new { success = true, data = model, message = "Data saved successfully."
}
Update: If SubmitButton calls a JavaScript method or uses AJAX call, the validation should be made in this method instead of button click as shown below. Otherwise, the request is still sent to the Controller without validation.
function save(event) {
//Validate the form before sending the request to the Controller
if (!$("#formID").valid()) {
return false;
}
...
}
Update your function as follows.
$('#formID').submit(function (e) {
e.preventDefault();
try{
$.validator.unobtrusive.parse("form");
if ($(this).valid()) {
$.ajax({
url: $('#formID').attr('action'),
type: 'POST',
data: $('#formID').serialize(),
success: function () {
console.log('form submitted.');
FunctionToBeCalled(); //JS function
}
});
}
}
catch(e){
console.log(e);
}
});
Check the browser console for fetching error. The above code will prevent of submitting the form.
I think line $.validator.unobtrusive.parse("form") were throwing error.
For that use you need to add the following jQuery libraries.
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.11/jquery.validate.unobtrusive.min.js"></script>
I think you should remove razor form tag if you want to post your form using ajax call and add post api URL directly to ajax request instead of getting it from your razor form tag using id:
Here is the revised version of your code :
<form method="post" id="formID">
<!-- Your form fields here -->
<button id="submit">Submit</button>
</form>
Submit your form on button click like:
$('#submit').on('click', function (evt) {
evt.preventDefault();
$.ajax({
url: "/Configuration/APIMethod",
type: 'POST',
dataType : 'json',
data: $('#formID').serialize(),
success: function () {
console.log('form submitted.');
FunctionToBeCalled(); //JS function
}
});
});
function FunctionToBeCalled(){alert('hello');}
You need to use Ajax.BeginForm, this article should help [https://www.c-sharpcorner.com/article/asp-net-mvc-5-ajax-beginform-ajaxoptions-onsuccess-onfailure/ ]
The major thing here is that I didn't use a submit button, I used a link instead and handled the rest in the js file. This way, the form would nver be submitted if the js file is not on the page, and with this js file, it initiates a form submission by itself rather than th form submitting when the submit button is clicked
You can adapt this to your solution as see how it respond. I have somthing like this in production and it works fine.
(function() {
$(function() {
var _$pageSection = $('#ProccessProductId');
var _$formname = _$pageSection.find('form[name=productForm]');
_$formname.find('.buy-product').on('click', function(e) {
e.preventDefault();
if (!_$formname.valid()) {
return;
}
var formData = _$formname.serializeFormToObject();
//set busy animation
$.ajax({
url: 'https://..../', //_$formname.attr('action')
type: 'POST',
data: formData,
success: function(content) {
AnotherProcess(content.Id)
},
error: function(e) {
//notify user of error
}
}).always(function() {
// clear busy animation
});
});
function AnotherProcess(id) {
//Perform your operation
}
}
}
<div class="row" id="ProccessProductId">
#using (Html.BeginForm("APIMethod", "Configuration", FormMethod.Post, new { #class = "form-horizontal", name="productForm" id = "formID" })) {
<li class="buy-product">Save & Proceed</li>
}
</div>

Success message after form submission

I am having a form to get the user details.
Once form is submitted the page gets loaded. I want to display a success message after page loading.
<form name="myForm" class="contactus-template" method="post" onsubmit="return Formvalidation()">
</form>
function Formvalidation(){
var validate = validateForm();
if( validate == true ){
alert("success");
}
else{
alert("not success");
}
return validate;
}
This is script I am using now. This gives alert before page reload. I want to do this after that return function.
Use Bootstrap Notify: http://bootstrap-notify.remabledesigns.com/
And this script:
Alert = {
show: function(type, title, message, url, delay) {
$.notify({
title: title,
message: message,
url: url,
target: "_blank"
},{
type: type,
showProgressbar: false,
placement: {
from: "bottom",
align: "center"
},
delay: delay
});
},
}
Then you can calling a message with PHP if page is reloaded:
echo '<script>Alert.show("success", "", "Form submit success!", "", 3000);</script>';
Have considered redirect user to another page success/failure, and display result in that page?
If you want to call Formvalidation() when the user clicks the submit button, onsubmit="return Formvalidation()" should simply be onsubmit="Formvalidation()".

Triggering event on clicking OK button in Jquery Modal dialog box

I am trying to display a dialog box with just an OK button on response of an ajax call. When the user clicks OK, it should reload the page. But now page reload is immediately happening after the dialog box is popped up. It is not waiting for the user to click OK. FYI I am using Jquery Modal dialog box.
Simple browser alert() does the job for me, but I don't like the appearance of alert().
Any help is highly appreciated!
$.ajax({
url: "modules/mymod/save.php",
type: "POST",
data: $('#requestForm').serialize(),
statusCode: {404: function () {alert('page not found');}},
success: function (data) {
// alert(data);
modal({type: 'alert', title: 'Alert', text: data});
window.location.href = window.location.href;
}
});
Reference:
$.ajax({
url: "modules/mymod/save.php",
type: "POST",
data: $('#requestForm').serialize(),
statusCode: {404: function () {alert('page not found');}},
success: function (data) {
// alert(data);
modal({
type: 'alert',
title: 'Alert',
text: data,
buttons: [{
text: 'OK', //Button Text
val: 'ok', //Button Value
eKey: true, //Enter Keypress
addClass: 'btn-light-blue btn-square', //Button Classes
onClick: function() {
window.location.href = window.location.href;
}
}, ],
center: true, //Center Modal Box?
autoclose: false, //Auto Close Modal Box?
callback: null, //Callback Function after close Modal (ex: function(result){alert(result);})
onShow: function(r) {
console.log(r);
}, //After show Modal function
closeClick: true, //Close Modal on click near the box
closable: true, //If Modal is closable
theme: 'xenon', //Modal Custom Theme
animate: true, //Slide animation
background: 'rgba(0,0,0,0.35)', //Background Color, it can be null
zIndex: 1050, //z-index
buttonText: {
ok: 'OK',
yes: 'Yes',
cancel: 'Cancel'
},
template: '<div class="modal-box"><div class="modal-inner"><div class="modal-title"><a class="modal-close-btn"></a></div><div class="modal-text"></div><div class="modal-buttons"></div></div></div>',
_classes: {
box: '.modal-box',
boxInner: ".modal-inner",
title: '.modal-title',
content: '.modal-text',
buttons: '.modal-buttons',
closebtn: '.modal-close-btn'
}
});
}
});
Because your reload runs irrespectively of what is clicked. If you want to assign a callback function to the modal window:
jQuery UI dialog with boolean return - true or false
Also, there is no need to make location.href equal itself (or use the window object). location.reload() works just as well.
You can pass the dialog modal buttons attributes, each with a registered event, like this:
$.ajax({
url: "modules/mymod/save.php",
type: "POST",
data: $('#requestForm').serialize(),
statusCode: {404: function () {alert('page not found');}},
success: function (data) {
$("#dialog-confirm").dialog({
resizable: false,
height: 200,
modal: true,
buttons: {
Proceed: function() {
window.location.href = window.location.href;
},
Cancel: function() {
// Cancellation code here
}
}
});
}
});
Simple browser alert() does the job for me because alert() is an blocking call. If you omit the alert then your code is not bind with any event to check whether user clicked on a button or not, that's why the code block executes immediately and page reloads.
So bind the following code:
window.location.href = window.location.href;
inside some button click, to resolve the issue.
dont use window.location function in success.instead open the modal with ok button at success(how to do that, I think you know already) and assign some id to that button let say id="loction_btn".
then use just this
$('document').on('click','#location_btn',function(){
window.location.href = window.location.href;
});

Jquery validator module and function call after success

First I don't have much experience with javascript and jquery :) I am just trying to find a quick way to connect jquery email validator module with a function that checks recaptcha. Here is my code:
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$( "#myform" ).validate({
rules: {
field: {
required: true,
email: true
}
}
});
Works fine! Inputs are validated.
Now after validation I need two things: First I need to call recapVerify(), after recaptcha gets validated I need to submit my form. This is the example I use: email method. I know I need to use submitHandler now but I can't figure out where and how?
Btw. this is recapVerify() function that I want to use:
function recapVerify(){
$.ajax({
type:'post',
url: 'captcha_check.php',
data: {
recaptcha_challenge_field:$('#recaptcha_challenge_field').val(),
recaptcha_response_field:$('#recaptcha_response_field').val()
}
}).done(function(data, textStatus, jqXHR){
if (data == 'success'){
$('#err').addClass('hidden');
//document.forms[0].submit(); // uncomment this line to submit your form
alert('Success, the form and reCAPTCHA validated, your form was submitted');
} else {
$('#err').removeClass('hidden');
}
}).fail(function(jqXHR,textStatus,errorThrown){
console.log('recaptcha or service failure');
});
}
use submitHandler on your jquery validate function. Debug is not needed. In essence this is the javascript you need.
$(document).ready(function(){
$("#test-form").validate({
rules: {
name: {
required: true,
},
email : {
required : true,
email : true
}
},
submitHandler : recaptchaVerify
});
});
function recaptchaVerify(form){
console.log(form);
alert("in submit handler");
}
According to the documents at jQuery validate
submitHandler (default: native form submit)
Type: Function()
Callback for handling the actual submit when the form is valid. Gets the form
as the only argument. Replaces the default submit. The right place to
submit a form via Ajax after it is validated.
Have also created a fiddle so that you can use it.

JavaScript confirm dialog in Django

I have a Django form. And I need a confirm/cancel dialog on form submit. A had an idea of sending POST data from jQuery... but is it a way to use javascript dialog as middleware?
Add the bellow code according to your need in your Html
<form><input type="submit" value="Submit" id="confirm"/> </form>
and jQuery code for confirm dialog
<script>
jQuery("#confirm").click(function(){
$("<div></div>").appendTo('body')
.html('<div><h3> write your message for confirm dialog</h3></div>')
.dialog({
title: "Confotm Dialog" ,
width:500, height:300,
modal:true,
resizable: false,
show: { effect: 'drop', direction: "left" },
hide:{effect:'blind'}
buttons: {
Yes: function() {
jQuery.ajax({
type:"POST", //post data
data:{'key':key}, //if you want to send any data to view
url:'/get_viewerModal/' // your url that u write in action in form tag
}).done(function(result){
alert("am done") //this will executes after your view executed
})
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
<script>
here you need ajax knowledge and it is very easy to use am sure you do this :)

Categories

Resources