Jquery Form on submit show success message - javascript

I have a form that uses Jquery to show a message for
*field required error message
I am trying to get it to show a success message if the form is submitted.
The form submits as long as the req fields are filled in.
Does anyone know how I can modify this code to show the "success" div if
all the "req" fields are filled out?
Thanks
$(function() {
function validateform() {
var valid = true;
$(".req").css("border","1px solid #ccc");
$(".req").each(function() {
if ( $(this).val() == "" || $(this).val().replace(/\s/g, '').length == 0 ) {
$(this).css("border","1px solided");$(".required").css("display","block");
valid = false;
}
});
return valid;
}
$("#submit").click( function() {
$('#myform').submit( validateform );
$('$name').submit();
});
});

submitHandler: function(form){
$(form).ajaxSubmit({
target: '#preview',
success: function() {
$('#form id').slideDown('slow'),
<!-- RESET THE FORM FIELDS AFTER SUBMIT STARTS HERE-->
$("#form")[0].reset();
<!--RESET THE FORM FIELDS AFTER SUBMIT ENDS HERE--->
}
});
}

There are two simple ways that will allow you to render a success message. You can either use ajax with the callback success function, or if you want a full post, you you can check at the top of your file if a certain POST was set, and if so, render a success message.
Here is an example of checking POST:
if(isset($_POST['name attribute posting'])) {
$util->showSuccessMessage();
//OR echo "<div class='popup'></div>"
}
And here is an example of using Ajax's success callback function:
function submitForm() {
$.ajax({
url : 'this_file.php',
type: 'POST',
success : showSuccessMessage //function call
})
}

$(function() {
function validateform() {
var valid = true;
$(".req").css("border","1px solid #ccc");
$(".req").each(function() {
if ( $(this).val() == "" || $(this).val().replace(/\s/g, '').length == 0 ) {
$(this).css("border","1px solided");
$(".required").css("display","block");
valid = false;
}
});
return valid;
}
$("#submit").click( function() {
$('#myform').submit(function()
{
if( validateform)
{
$('$name').submit();
}
} );
});
});
reference submit

Related

How to prevent form submit?

I have a login form and a captcha field. I need a javascript source to check this captcha input then send post data to action but my code seems to be wrong, the e.preventDefault function doesn't work because captcha field true or false post data's still sent. please help.
This my javascript Function:
$(document).ready(function () {
$("#signupform").submit(function (event) {
var captchacode = $("#captchatexbox").val();
if (captchacode != "") {
var url = "/Account/ValidateCaptcha?Code=" + captchacode;
$.ajax({
url: url,
cache: false,
success: function (data) {
if (data == 0) {
alert("Invalid captcha");
event.preventDefault();
//Form post data still sent?
}
}
});
}
else alert("Captcha not null");
});
});
You need to move event.preventDefault(); up so it comes before the ajax call.
Use $("#signupform").submit(); in an else block to programmatically submit the form.
$(document).ready(function () {
$("#signupform").submit(function (event) {
event.preventDefault();
var captchacode = $("#captchatexbox").val();
if (captchacode != "") {
var url = "/Account/ValidateCaptcha?Code=" + captchacode;
$.ajax({
url: url,
cache: false,
success: function (data) {
if (data == 0) {
alert("Invalid captcha");
//Form post data still sent?
} else {
$("#signupform").submit();
}
}
});
}
else alert("Captcha not null");
});
});
You would need have the form event.preventDefault(); before making the ajax request.
$("#signupform").submit(function (event) {
event.preventDefault();
When the ajax request is returned, you can submit the form using:
if (data != 0) {
$("#signupform").submit();
}

Ajax JSON malfunction

EDIT:
So I ended up with this code here, but as always, can't get it to work properly.
Basically it has to check that all input fields are filled, once this check is true, it calls the JSON url to check validity of the VAT number. If the VAT number check returns true, submits the form, else it inform the customer that there is an error and let the customer choose if to ignore the exception (then submits) or cancel submission and stay on the page.
Here is the JS code, and below is the JSON returned from the call.
$(document).ready(function() {
$('#create_customer').submit(function(){
var canSubmt = true;
$("form#create_customer :input").each(function(){
var input = $(this);
if($(input).val() == '') {
$(input).css("border",'1px solid red');
canSubmt = false;
}else{
$(input).css("border",'1px solid #000');
}
});
if(!canSubmt){ $("#errMsg").text("Errors detected! Please check your form and try again.").show().fadeOut(7000); return canSubmt; }
var vatNum = document.getElementById('VatNum').value;
var validVat;
var vatConfirm;
$.getJSON("http://apilayer.net/api/validate?&access_key=<api-key>&vat_number="+vatNum, function(response) {
validVat = response.valid;
})
.fail(function(){
console.log("failed");
});
if (!validVat) { vatConfirm = confirm("Your VAT number doesn't seem to be valid or in a correct format!\nDo you wish to continue anyway?"); }
if (!vatConfirm) { canSubmt = false; }
return canSubmt;
});
});
and the JSON data, from which I only need the "valid" key:
{ "valid": true, "format_valid": true, "query": "LU26375245", "country_code": "LU", "vat_number": "26375245", "company_name": "AMAZON EUROPE CORE S.A R.L.", "company_address": "5, RUE PLAETIS L-2338 LUXEMBOURG" }
any idea on how to get this working?
Ther're two issues:
Ajax is asynchronous, so before it returns the value of validVat execution probably has already reached the return statement
validVat's scope is inside the ajax function so it will undefined on the line "return ..."
The simplest thing you could do, is to make the ajax request synchronous, see following please:
var validVat = false;
$.ajax({
var vatNumber = document.getElementById("VatNum").value;
url: 'http://apilayer.net/api/validate?access_key=6ab1579cc9e968a65429d7f351375f35&vat_number='+vatNumber,
dataType: 'jsonp',
async: false,
success: function(json) {
// Access and use your preferred validation result objects
if (!json.valid) {
var r = confirm("Your VAT number doesn't seem to be valid or in a correct format!\nDo you wish to continue anyway?");
if (r == true) {
validVat = true;
} else {
validVat = true;
}
}
}
});
return validVat;
The best thing instead, should to use the callback function in order to submit the form or do anything you need after the response of ajax request.
Here's a complete example with a mock of ajax request, please see following:
var validated = false;
$("form").submit(function( event ) {
if(!validated){
event.preventDefault();
var mock = {
ajax: function() {
return mockAjax({
success: $("#test").val() === "correct",
response: { ok: $("#test").val() === "correct" },
timeout: 500
});
}
};
mock.ajax()
.done(function(valid) {
if(valid) {
$("#err").text("Validated... do submit").show();
validated = true;
return $("form").submit();
} else {
event.preventDefault();
}
})
.error(function(json) {
$("#err").text("Not valid!").show().fadeOut(1000);
});
}
});
function mockAjax(options) {
var that = {
done: function done(callback) {
if (options.success)
setTimeout(callback, options.timeout, options.response);
return that;
},
error: function error(callback) {
if (!options.success)
setTimeout(callback, options.timeout, options.response);
return that;
}
};
return that;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Type 'correct' to validate.</p>
<form action="javascript:console.log( 'success!' );">
<div>
<input id="test" type="text">
<input type="submit">
</div>
</form>
<span id="err"></span>
I hope it helps you, bye.

avoid sending if any field empty Axax

In my form I have various fields including (input and selects) in which I want to check any empty field and prevent ajax call if any of the field is empty and focus on empty fields. so far I am trying this way, It alerts but also makes an ajax call.
$('#submit').click(function() {
$('input').each(function() {
if (!$(this).val()) {
alert('Some fields are empty');
return false;
}
});
event.preventDefault(); // using this page stop being refreshing
$.ajax({
type: 'POST',
url: "<?php echo site_url(''); ?>/shipment/create_shipment",
data: $('form').serialize(),
cache: false,
success: function(data) {
$('#F_id').val('');
$('#v_id').val('');
$('#shp_no').val('');
$('#shipDate').val('');
$('#sup').val('');
$('#sup-quantity').val('');
$('#box').val('');
$('#box-quantity').val('');
$("#sup").prop('disabled', true);
$("#sup-quantity").prop('disabled', true);
$("#box").prop('disabled', true);
$("#box-quantity").prop('disabled', true);
$('.alert-success').fadeOut(200).show();
$('.alert-danger').fadeOut(200).hide();
/// alert('form was submitted');
},
error: function(data) {
$('.alert-success').fadeOut(200).hide();
$('.alert-danger').fadeOut(200).show();
}
});
});
The return false returns from the each function and not the click function.
Try having a bool variable denoting valid, and return false if not.
var valid = true;
e.prevent.preventDefault(); // e being event variable in submit
$('input').each(function() {
if(!$(this).val()){
alert('Some fields are empty');
valid = false;
return false;
}
});
if(!valid) return false;
//.....
Hope this helps.

Message about sent is not working

I have code that checks whether the address is ok and sends it. After sending the information appears that the message was sent.
When I give the wrong email address format - appears the message.
Then when I give the correct address - the message you sent is not working.
What is wrong?
jQuery code:
<script type="text/javascript">
{literal}
function validateEmail(email) {
return /^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/.test(email);
}
{/literal}
$(document).ready(function() {
$('#mybtn').click(function() {
var sEmail = $('#email').val();
if ($.trim(sEmail).length == 0) {
alert('Please input your email');
//e.preventDefault();
}
if (validateEmail(sEmail)) {
$('#contact').submit(function() {
$.ajax({
url : '/contact/process',
data : $('#contact').serialize(),
type: "POST",
success : function(){
$('form').find('#name, #email, #message').val('');
$('#messageAfterSend').addClass('alert alert-success').text("Thank you for send email").slideUp(3200);
}
});
return false;
});
}
else {
$('#messageAfterSend').addClass('alert alert-success').text("Invalid email.").slideUp(3200);
$('form').find('#email').val('');
}
});
});
</script>
<script type="text/javascript">
function validateEmail(email) {
return /^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/.test(email);
}
$(document).ready(function() {
$('#contact').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : '/contact/process',
data : $(this).serialize(),
type: "POST",
success : function(){
$('form').find('#name, #email, #message').val('');
$('#messageAfterSend').addClass('alert alert-success').text("Thank you for send email").slideUp(3200);
}
});
});
$('#mybtn').on('click', function(e) {
e.preventDefault();
var sEmail = $('#email').val();
if ($.trim(sEmail).length == 0) {
alert('Please input your email');
}
if (validateEmail(sEmail)) {
$('#contact').trigger('submit');
} else {
$('#messageAfterSend').addClass('alert alert-success').text("Invalid email.").slideUp(3200);
$('form').find('#email').val('');
}
});
});
Try this way, first set listener on your contact form, second listen for event on "send button"
If it's "simple form" you could just put everything in on('submit') listener
Fiddle

Exiting from javascript function not working

I have this javascript function:
function displayMessage() {
var message = $("#msg").val();
if (message == "") {
alert("You need to enter a message");//alert the user
return false;
}
postData = {
"message": message,
};
...
}
What am hoping this achieves is, if the input field is empty, display the alert and remain in the function.If it isn't then continue.
My submit button is linked to another page but this page is displayed anyways regardless of what happens in the if statement.
This is the form code:
<form id="post" action="http://localhost:8080/uploadNewMessage" method="post">
<fieldset>
<div data-role="fieldcontain">
<label for="msg" class="input">Message:</label>
<input type="text" name="msg" id="msg" size="10"/>
</div>
Submit
</fieldset>
</form>
and the full javascript code just incase:
$(document).ready(function() {
// 1. The Registration button
$("#submit").bind('click', function(event) {
displayMessage();
});
});
function doPostRequest(postData) {
$.ajax({
type: "POST",
url: URL,
dataType: "json",
data: postData
});
}
function displayMessage() {
var message = $("#msg").val();
if (message == "") {
alert("You need to enter a message");//alert the user
return false;
}
postData = {
"message": message,
};
...
doPostRequest(postData);
}
You may try something like this:
$("#submit").bind('click', function(event) {
var message = $.trim($("#msg").val());
if(!message.length) {
alert("You need to enter a message");
return false;
}
else {
event.preventDefault();
doPostRequest({"message":message});
}
});
demo
$(function() {
$("#submit").on('click', function(event) {
event.preventDefault(); // prevent default anchor behavior
displayMessage();
});
});
and also:
function displayMessage() {
var message = $.trim( $("#msg").val() ); // trim whitespaces
if (message === "") {
alert("You need to enter a message");
}else{ // Use the else statement
doPostRequest({
"message" : message
});
}
}
The event variable that is passed via your click event handler contains a function named preventDefault. If you don't want the form to submit, call this (event.preventDefault()). This will prevent the submit button from submitting the form.

Categories

Resources