Success message after form submission - javascript

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()".

Related

Submit HTML form through AJAX

I'm experiencing a problem with my form. Im trying to post data to a PHP file using Ajax, but i stumbled across a problem with form validations.
My Form
<form id="kt_modal_new_target_form" class="form" name="kt_modal_new_target_form" method="post" action="test.php">
....
<button type="submit" id="kt_modal_new_target_submit" class="btn btn-primary">
<span class="indicator-label">Submit</span>
</button>
</form>
Part of my Modal with form hander file (the part which validates the form.) As you see, after it validates the form, the is a form submit function, but i cant seem to make it work as ajax. I've tried $.ajax, I've tried submitting through the html file, but then it doesn't validate the form...
submitButton.addEventListener('click', function (e) {
e.preventDefault();
// Validate form before submit
if (validator) {
validator.validate().then(function (status) {
console.log('validated!');
if (status == 'Valid') {
submitButton.setAttribute('data-kt-indicator', 'on');
// Disable button to avoid multiple click
submitButton.disabled = true;
setTimeout(function() {
submitButton.removeAttribute('data-kt-indicator');
// Enable button
submitButton.disabled = false;
// Show success message. For more info check the plugin's official documentation: https://sweetalert2.github.io/
Swal.fire({
text: "Nurašymas atliktas!",
icon: "success",
buttonsStyling: false,
confirmButtonText: "Gerai!",
customClass: {
confirmButton: "btn btn-primary"
}
}).then(function (result) {
if (result.isConfirmed) {
modal.hide();
}
});
form.submit(); // Submit form
}, 2000);
} else {
// Show error message.
Swal.fire({
text: "Pildant nurašymą rasta klaidų, bandykite dar kartą.",
icon: "error",
buttonsStyling: false,
confirmButtonText: "Gerai!",
customClass: {
confirmButton: "btn btn-primary"
}
});
}
});
}
});
Anyone able to help me out? I need this form to validate through the .js file and then to send the data using Ajax to a PHP file.

Submit form using JS and AJAX

I have little problem with JS and AJAX, i dont know this languages. I know php and i have applied for position php developer, now i have some tasks to do and i stucked at one. It is simple task, form, submit, process information, store in DB, and send. Only problem is i have to use AJAX to submit form, i done little research and somehow i made wrote this code but it doesnt work.
<div>
<form method="POST" action="add.php" id="form">
<input type="email" name="email" id="email" value="Email">
<textarea name="content" id ="content">Message</textarea>
<input type="submit" value="Submit" id="submit">
</form>
Send messages from database
</div>
<script>
$(document).ready(function() {
// When click on button store values from form fields into variables
$("form").submit(function(event) {
event.preventDefault();
var email = $("#email").val();
var content = $("#content").val();
// Check if fields are empty
if (email=="" || content="") {
alert("Please fill all fields");
}
// AJAX code to submit form
else {
$.ajax ({
type: "POST",
url: ("#form").attr('action');
data: { "email": email, "content": content},
cache: false,
success: function() {
alert("Data successfully forwarded to add.php");
}
});
}
return false;
});
});
</script>
</body>
IN form can i use input type button instead of submit (so no need for preventDefault in JS) and in JS i do it
$("#submit").click(function.....
I think i have tried all combinations and when form is submited it goes with default, no JS activated...
SOLVED: problem was in IF statment, content="" instead of content=="", OMG how i overlooked that...
To answer your questions, yes you are right, you can use an input of type button and you don't necessary need to depend on submitting the form. Here is how you'd write it without form submission:
<div>
<form method="POST" action="add.php" id="form">
<input type="email" name="email" id="email" value="Email">
<textarea name="content" id ="content">Message</textarea>
<input type="button" value="Submit" id="submit" onclick="SendAjax();">
</form>
Send messages from database
</div>
<script>
// When click on button store values from form fields into variables
function SendAjax() {
var email = $("#email").val();
var content = $("#content").val();
// Check if fields are empty
if (email=="" || content=="") {
alert("Please fill all fields");
}
// AJAX code to submit form
else {
$.ajax ({
type: "POST",
url: "type your URL here",
data: { "email": email, "content": content},
cache: false,
success: function() {
alert("Data successfully forwarded to add.php");
}
});
}
}
</script>
As you can see, I prefer to specify the URL in AJAX instead of taking it from the form's action which I sometimes have it set to a different URL from the AJAX. However, if you want to take the URL from the form's action, then fix that line in your code to be:
url: $("#form").attr('action'),
Use the serialize() method (described bellow) instead of manually getting the value of each field of your form in order to build the JSON object.
$('#form').submit(function() {
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function() {
alert("Data successfully forwarded to add.php");
}
});
return false;
});
You have a syntax error in your ajax call.
$.ajax ({
type: "POST",
url: ("#form").attr('action'); // This is bad JSON
data: { "email": email, "content": content},
cache: false,
success: function() {
alert("Data successfully forwarded to add.php");
}
});
Replace that line with:
url: $("#form").attr('action'),

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.

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

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

How to remove AJAX from jQuery validation plugin function

This is going to be a stupid question but I have spent an inordinate amount of time trying to remove the AJAX part from the jQuery validation plugin function below but still have the validation work. Suffice to say I haven't succeeded.
$(document).ready(function(){
$("#myform").validate({
debug: false,
rules: {
group: {required: true},
},
messages: {
group: {required: " Choose a group."},
},
submitHandler: function(form) {
$('#results').html('Loading...');
$.post('', $("#myform").serialize(), function(data) {
$('#results').html(data);
});
}
});
});
So yeah, I'm dumb. Can anyone help me out?
When you send the object back, send it as a JSON object.
Here's an example where we're going to use the serialized elements, conditionalize some data, and then send something back with our new page.
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
if(isset($name) && isset($email) && isset($phone)){
return json_encode(array('filled' => 'yes', 'loc' => 'newpage.php'));
}
?>
Then in the validator, we can parse data.loc to the window.location to mimic the redirect.
$(document).ready(function(){
$("#myform").validate({
debug: false,
rules: {
group: {required: true},
},
messages: {
group: {required: " Choose a group."},
},
submitHandler: function(form) {
$('#results').html('Loading...');
$.post('', $("#myform").serialize(), function(data) {
if(data.filled == 'yes'){
window.location = data.loc;
}
});
}
});
});
You just need to replace the submitHandler function!
submitHandler: function(form) {
$('#results').html('Loading...');
// $.post('', $("#myform").serialize(), function(data) {
// $('#results').html(data);
// });
}
And after calling .validate(), call the .valid() function on #myform this way:
$('#myform').valid();
Just make sure you are removing the default action of submit on the form by adding this:
<form onsubmit="if (!$(this).valid()) return false;">
Explanation: This doesn't submit the form when it is not valid and shows the errors. If the form is valid, this function submits as a normal form submit.
But why do you wanna do that? What else you wanna do?

Categories

Resources