Could someone please help me in locating where i need to place this code below into my validation script.
The script works great, but users are clicking more than once and the form is sending multiple times.
I tried including the code just below the if(valid) line but still does not work.
This is the code i am trying to include:
form.submit.disabled = true;
form.submit.value = "Please wait...";
This is the script:
<script type="text/javascript">
$(document).ready(function (e){
$("#nominateForm").on('submit',(function(e){
e.preventDefault();
var valid;
valid = validateContact();
if(valid) {
$.ajax({
url: "contact_mail.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$("#mail-status").html(data);
},
error: function(){}
});
}
}));
function validateContact() {
var valid = true;
$(".nominateForm").css('background-color','');
$(".info").html('');
if(!$("#nominate-name").val()) {
$("#nominateName-error").html("Please enter a name of who you would like to nominate");
valid = false;
}
return valid;
}
});
</script>
You should put those two lins inside the if condition and after the success call, you should turn them back into the default values. Also the correct way of accessing the properties of your submit button is like below,
$('input[type="submit"]').prop('disabled', true);
$('input[type="submit"]').prop('value', 'Please wait...');
or if it has an id equal to mySubmitBtn
$('#mySubmitBtn').prop('disabled', true);
$('#mySubmitBtn').prop('value', 'Please wait...');
So your code should be,
if(valid) {
$('input[type="submit"]').prop('disabled', true);
$('input[type="submit"]').prop('value', 'Please wait...');
$.ajax({
url: "contact_mail.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$("#mail-status").html(data);
$('input[type="submit"]').prop('disabled', false);
$('input[type="submit"]').prop('value', 'Submit');
},
error: function(){}
});
}
You can add an HTML element showing something like 'processing' and if it is processing, then skip the function.
<script type="text/javascript">
$(document).ready(function (e){
$("#nominateForm").on('submit',(function(e){
var status = document.getElementById('someHTMLElement');
if (status.innerHTML != 'processing') {
status.innerHTML = 'processing';
e.preventDefault();
var valid;
valid = validateContact();
if(valid) {
$.ajax({
url: "contact_mail.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$("#mail-status").html(data);
},
error: function(){}
});
}
status.innerHTML = '';
}
}));
function validateContact() {
var valid = true;
$(".nominateForm").css('background-color','');
$(".info").html('');
if(!$("#nominate-name").val()) {
$("#nominateName-error").html("Please enter a name of who you would like to nominate");
valid = false;
}
return valid;
}
});
</script>
Related
I have this form that allows user to write an article also upload an image.
i use the ajax script below
$(document).ready(function() {
$("#publishArticle").on('submit', function() {
event.preventDefault();
var form = $(this);
var formData = new FormData($(this)[0]);
$.ajax({
url : "send.php",
type : "POST",
cache: false,
contentType : false,
processData: false,
data: formData,
success:function(response){
$("#result").fadeIn();
$("#result").html("");
$("#result").html(response);
$("#result").fadeOut(4000);
if (response == "Article Published") {
$("#publishArticle")[0].reset();
}
}
});
});
});
It works well. then i decided to have another button that drafts an article...
am trying to use an onclick event to differenciate between them. but it's not going through...
//Publish
$(document).ready(function() {
$("#publish").click(function(){
event.preventDefault();
var form = $(this);
var formData = new FormData($(this)[0]);
$.ajax({
url : "send.php",
type : "POST",
cache: false,
contentType : false,
processData: false,
data: formData,
success:function(response){
$("#result").fadeIn();
$("#result").html("");
$("#result").html(response);
$("#result").fadeOut(4000);
if (response == "Article Published") {
$("#publishArticle")[0].reset();
}
}
});
});
});
//Drafts
$(document).ready(function() {
$("#draft").click(function(){
event.preventDefault();
var form = $(this);
var formData = new FormData($(this)[0]);
$.ajax({
url : "draft.php",
type : "POST",
cache: false,
contentType : false,
processData: false,
data: formData,
success:function(response){
$("#result").fadeIn();
$("#result").html("");
$("#result").html(response);
$("#result").fadeOut(4000);
if (response == "Article Drafted") {
$("#publishArticle")[0].reset();
}
}
});
});
});
Please help me out...
Thanks in advance
You can attach a custom click handler to all buttons, and that way you can check which button is clicked before submitting the form:
Javascript:
$("#my-form button").click(function(event){
alert($(this).attr("value"));
event.preventDefault()// cancel form submission
if($(this).attr("value")=="button-publish"){
//do button 1 thing
var form = $(this);
var formData = new FormData($(this)[0]);
$.ajax({
url : "send.php",
type : "POST",
cache: false,
contentType : false,
processData: false,
data: formData,
success:function(response){
$("#result").fadeIn();
$("#result").html("");
$("#result").html(response);
$("#result").fadeOut(4000);
if (response == "Article Published") {
$("#publishArticle")[0].reset();
}
}
});
}
if($(this).attr("value")=="button-draft"){
//do button 2 thing
var form = $(this);
var formData = new FormData($(this)[0]);
$.ajax({
url : "draft.php",
type : "POST",
cache: false,
contentType : false,
processData: false,
data: formData,
success:function(response){
$("#result").fadeIn();
$("#result").html("");
$("#result").html(response);
$("#result").fadeOut(4000);
if (response == "Article Drafted") {
$("#publishArticle")[0].reset();
}
}
});
}
$("#my-form").submit(); // If you want to submit the form
});
I have been coding an ajax request and i have a problem with it.
var addonUploadForm = $('#addonUploadForm');
var addonUploadFormMessages = $('#addonUploadForm-messages');
$(addonUploadForm).submit(function(e) {
e.preventDefault();
//var formData = $(addonUploadForm).serialize();
//var formData = new FormData($(this)[0]);
var formData = new FormData($('#addonUploadForm')[0]);
$.ajax({
type: 'POST',
url: $(addonUploadForm).attr('action'),
data: formData,
xhr: function() { },
cache: false,
contentType: false,
processData: false // marked line of error
success: function(response) {
$(addonUploadFormMessages).removeClass('error');
$(addonUploadFormMessages).addClass('success');
$(addonUploadFormMessages).html(response);
$('#addonTitle').val('');
$('#addonDescription').val('');
$('#addonFile').val('');
grecaptcha.reset();
},
error: function(data) {
$(addonUploadFormMessages).removeClass('success');
$(addonUploadFormMessages).addClass('error');
grecaptcha.reset();
if (data.responseText !== '') {
$(addonUploadFormMessages).html(data.responseText);
} else {
$(addonUploadFormMessages).html('<div class="alert alert-danger fade in out">×<strong>Error!</strong> An error occured and your message could not be sent.</div>');
}
}
});
});
That is my code and on the marked line there is a missing , and this code works fine apart from doesnt display the request on the page and it instead just takes me to the ajax url but if i put the , in it does nothing when i submit the form no errors, no nothing.
Probably this line causes the error:
xhr: function() { },
without an xhr object you cannot send an ajax request.
So leave out this line.
Also you need to put the "," in at your marked line.
Your url opens because if you leave out the "," the function will throw an error and your e.preventDefault() won't work.
Also I would leave out these lines:
contentType: false,
processData: false
And you should probably escape the html content in this line:
$(addonUploadFormMessages).html(data.responseText);
Hope this helps.
I fixed it i had 2 versions of jquery runnning with noconflict and they where 1.11 and 1.4, and 1.4 was last loaded before this. So i had to change my no conflict to var jq1 = jQuery.noConflict(true); and then my ajax code to
var addonUploadForm = $('#addonUploadForm');
var addonUploadFormMessages = $('#addonUploadForm-messages');
$(addonUploadForm).submit(function(e) {
e.preventDefault();
var formData = new FormData($('#addonUploadForm')[0]);
jq1.ajax($(addonUploadForm).attr('action'), {
type: 'POST',
url: $(addonUploadForm).attr('action'),
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(response) {
$(addonUploadFormMessages).removeClass('error');
$(addonUploadFormMessages).addClass('success');
$(addonUploadFormMessages).html(response);
$('#addonTitle').val('');
$('#addonDescription').val('');
$('#addonFile').val('');
grecaptcha.reset();
},
error: function(data) {
$(addonUploadFormMessages).removeClass('success');
$(addonUploadFormMessages).addClass('error');
grecaptcha.reset();
if (data.responseText !== '') {
$(addonUploadFormMessages).html(data.responseText);
} else {
$(addonUploadFormMessages).html('<div class="alert alert-danger fade in out">×<strong>Error!</strong> An error occured and your message could not be sent.</div>');
}
}
});
});
I'm using this code to submit a form using Ajax:
$(document).ready(function(){
$("#SubmitTicket").submit(function(e){
CheckRequired();
e.preventDefault();
dataString=$("#SubmitTicket").serialize();
$.ajax({
type: "POST",
url: "?SubmitTicket=1",
cache: false,
data: dataString,
success: function(res) {
if(res.indexOf("success")!=-1) {
//window.location.href = res.substr(8);
$("#CreateNewTicket_Body").html(res);
$("#CreateTicket").hide();
}
}
});
});
});
This function checks for required classes in form elements
function CheckRequired(event) {
var $form = $(this);
var emptyElements = $form.find('.required').filter(function() {
return this.value === ''
});
if(emptyElements.length > 0) {
event.preventDefault();
emptyElements.addClass("EmptySelect").attr('title', 'This field is required');
//alert(emptyElements.attr("id"));
alert("One or more fields cannot be blank");
return false;
}
}
I then have this code which automatically checks all my forms for required fields using the above function:
$(document).ready(function () {
$('form').on('submit', CheckRequired);
});
It works fine on forms that POST to another page.
When using the Ajax submit code, its display the alert when there is an error, but its still submitting the form.
You might want to enclose the return of CheckRequired into an if() structure :
$(document).ready(function(){
$("#SubmitTicket").submit(function(e){
if(CheckRequired.call(this,e)) { // this should refer to the event target element, i.e. the form element, providing context for the function
e.preventDefault();
dataString=$("#SubmitTicket").serialize();
$.ajax({
type: "POST",
url: "?SubmitTicket=1",
cache: false,
data: dataString,
success: function(res) {
if(res.indexOf("success")!=-1) {
//window.location.href = res.substr(8);
$("#CreateNewTicket_Body").html(res);
$("#CreateTicket").hide();
}
}
}
});
});
});
You can simply add onSubmit="return CheckRequired()" in your form.
If the 'CheckRequired()' return false, you need to stop the script by returning false.
$(document).ready(function(){
$("#SubmitTicket").submit(function(e){
e.preventDefault();
if (!CheckRequired(e)) {
return false;
}
dataString=$("#SubmitTicket").serialize();
$.ajax({
type: "POST",
url: "?SubmitTicket=1",
cache: false,
data: dataString,
success: function(res) {
if(res.indexOf("success")!=-1) {
//window.location.href = res.substr(8);
$("#CreateNewTicket_Body").html(res);
$("#CreateTicket").hide();
}
}
});
});
});
Two ways to approach this:
A) Javascript
$(document).ready(function(){
$("#SubmitTicket").submit(function(e){
if(!CheckRequired()) return false; // THIS!
e.preventDefault();
dataString=$("#SubmitTicket").serialize();
$.ajax({
type: "POST",
url: "?SubmitTicket=1",
cache: false,
data: dataString,
success: function(res) {
if(res.indexOf("success")!=-1) {
//window.location.href = res.substr(8);
$("#CreateNewTicket_Body").html(res);
$("#CreateTicket").hide();
}
}
});
});
});
B) HTML:
<form id="SubmitTicket" onSubmit="return CheckRequired();">
I have some script in JS which should validate my form. It shows information like 'sent' or 'loading' when processing. I'd like to add one more feature. I want to prevent users from sending an e-mail with blank fields. What should I add to the code below to achieve this?
$(function() {
var form = $('#form');
var submit = $('#submit');
form.on('submit', function(e) {
e.preventDefault();
$.ajax({
url: '',
type: 'POST',
dataType: 'html',
data: form.serialize(),
beforeSend: function() {
document.getElementById("submit").value = "Loading...";
},
success: function() {
form.trigger('reset');
document.getElementById("submit").value = "Message sent!";
},
});
});
});
You could use HTML attribute required on the fields that cannot be empty
<input type="text" required/>
AND/OR
Have some javascript check before you submit
$(function() {
var form = $('#form');
var submit = $('#submit');
form.on('submit', function(e) {
e.preventDefault();
if($('input', this).val().trim() == ''){
//handle error message
}
else{
$.ajax({
url: '',
type: 'POST',
dataType: 'html',
data: form.serialize(),
beforeSend: function() {
document.getElementById("submit").value = "Loading...";
},
success: function() {
form.trigger('reset');
document.getElementById("submit").value = "Message sent!";
},
});
}
});
});
AND/OR
You do server side checking to make sure the value is not empty
in PHP:
if(empty($_POST['input_name'])){
//handle error
}
$(".update_button").click(function()
{
var updateval = $("#update").val();
var dataString = 'update='+ updateval;
if(updateval=='')
{
alertify.alert("Please Enter Some Text!");
}
else
{
$("#flashing").show();
$("#flashing").fadeIn(3000).html('<img src=../images/ajax-loader.gif>');
$.ajax({
type: "POST",
url: "message_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
$("#flashing").fadeOut('slow');
$("#loadcontainer").prepend(html);
$("#update").val('');
$("#update").focus();
}
});
}
return false;
});
i want the other users who are friend to the message sender to get alert after the above which actually append the new post on the message sender page only but not his/her friends.Is there simpler way than Comet or Long-polling?