I have a form that uses a formvalidation.io class. I Have a if statement that says if the field is valid use a jQuery post to submit the data and prepend the data on a table. For Some reason it is submitting twice. If I remove the $.post and prepend the data under the if statement the prepend only does one time. I have the e.preventDefault() at the start of the function. That seams to be the only solution on other forums. Any Help Appreciated:
barcode: {
onSuccess: function(e, data) {
e.preventDefault();
setTimeout(function() {
if (!$('#move_bin').data('formValidation').isValidField('bin')) {
$("#barcode").val("");
$('#move_bin').data('formValidation').updateStatus('barcode', 'NOT_VALIDATED');
$('#move_bin').data('formValidation').updateStatus('bin', 'INVALID');
} else {
setTimeout(function() {
if ($('#move_bin').data('formValidation').isValidField('barcode')) {
$.post( "/?a=scantobin", { bin: $("#bin").val(), barcode: $("#barcode").val() }, function( data ) {
if(data.valid == true){
$("#bin_info tbody").prepend("<tr><td>" + $("#bin").val() + "</td><td>" + $("#barcode").val() + "</td></tr>");
$('#move_bin').data('formValidation').resetField('barcode', true);
$("#barcode").focus();
} else {
alert("Internal Error");
}
}, "json");
}
}, 750);
}
}, 500);
},
There is nothing wrong in your code, may be somewhere in your project you are invoking that function twice.
http://formvalidation.io/examples/form-submit-twice/
This helped me out. I had to place the code in a Form Level instead of the field level on the formvalidation.
Related
I have a script that sends a form to a controller method, and I was trying to make it a POST request, but I get a "too much recursion" error. Here´s the code:
var modalConfirm = function(callback) {
$("#modal-btn-si").on("click", function() {
callback(true);
$("#modal-confirm").modal('hide');
});
$("#modal-btn-no").on("click", function() {
callback(false);
$("#modal-confirm").modal('hide');
});
};
function confirmar(form, text) {
$("#modal-confirm").modal('show');
modalConfirm(function(confirm) {
if (confirm) {
$.post("NuevaOpcion", {
data: $('#' + form)
});
}
});
};
The line I modified is
$.post("NuevaOpcion",{ data: $('#' + form) });
After I added the $.post() I got:
too much recursion[Saber más] jquery-3.3.1.js:8423:24
I'm quite lost, don't know how I'm making such mistake. Thanks in advance.
Why all the code?
This should work
You need to serialize the form too
var currentForm;
$("#modal-btn-si").on("click", function() {
$.post("NuevaOpcion", {
data: $('#' + currentForm).serialize()
});
$("#modal-confirm").modal('hide');
});
$("#modal-btn-no").on("click", function() {
$("#modal-confirm").modal('hide');
});
function confirmar(form, text) {
currentForm = form;
$("#modal-confirm").modal('show');
};
If you only have one form, remove the global var and use the ID
data: $('#actualID').serialize()
I have many answer forms on a page with different classes for all the forms.
all the forms got 2 buttons to send the parent form.
I send the form if #avote_down or #avote_up is clicked, then got the parent form class of the button clicked and save the class inside the var clase, then add the . before the class name (I know is weird the dot thing but if I don't do it, this doesn't work), after this I save the class edited before on the var called answervotes so we can work with it.
//declare variables outside the functions to use them
//inside others
var answerdata;
var answervotes;
var clase;
var clasedot;
$('#avote_down, #avote_up').on("click",function(e) {
e.preventDefault();
clase = $(this).parents("form:first").attr('class');
clasedot = '.'+clase;
answervotes = $(clasedot);
answerdata = answervotes.serializeArray();
answerdata.push({name: encodeURI($(this).attr('name')), value: encodeURI($(this).attr('value'))});
answervotes.submit();
answerdata.pop();
});
if everything goes well I can send the form using the ajax function bellow, as you see the ajax function is using the vars declared before.
answervotes.bind('submit',function () {
$.ajax({
url: answervotes.attr('action'),
type: answervotes.attr('method'),
cache: false,
dataType: 'json',
data: answerdata,
success: function(data) {
if(data.message == "plus")
{
$("#avote_up").attr('class','options options-hover');
$("#avote_down").attr('class','options');
$("#atotal-votes").html(data.votes);
console.log(data.votes);
}
if(data.message == "sub")
{
$("#avote_down").attr('class','options options-hover');
$("#avote_up").attr('class','options');
$("#atotal-votes").html(data.votes);
console.log(data.votes);
}
if(data.name == "register")
{
$('.theme-actions').append('<div class="should-login"><span>' + data.message + '</span><div id="close"></div></div>');
setTimeout(function() {
$('.should-login').fadeOut(300);
},4000);
setTimeout(function() {
$('.should-login').remove();
},4300);
}
if(data.name == "limited_votes")
{
$('.theme-actions').append('<div class="should-login"> <span>' + data.message + '</span><div id="close"></div></div>');
setTimeout(function() {
$('.should-login').fadeOut(300);
},4000);
setTimeout(function() {
$('.should-login').remove();
},4300);
}
if(data.name == "repeated_vote")
{
$('.theme-actions').append('<div class="should-login"><span>' + data.message + '</span><div id="close"></div></div>');
setTimeout(function() {
$('.should-login').fadeOut(300);
},4000);
setTimeout(function() {
$('.should-login').remove();
},4300);
}
},
error: function(xhr, textStatus, thrownError) {
console.log(data.message);
alert("error");
}
});
return false;
});
The problem: When I try to send the form like this, it just send me to the form action page like if there is no e.preventDefault() method being used to prevent the normal action, but in fact it is there you see it.
important facts: When I assign the the value to the answervotes var outside the click function using a direct name like so var answervotes = $(".parent-form1"); it works perfectly, but if I assign the name directly inside the click function, it just doesn't work either (I need this to be dynamic depending of the parent form).
console error: Uncaught TypeError: Cannot read property 'bind' of undefined, probably because isn't getting the answervotes until the button is clicked, but I suppose this would be solved with the var problem.
here is a jsfiddle: https://jsfiddle.net/EnmanuelDuran/cyvpkvkk/22/
I think your selector for answervotes doesnt match, use console.log or alert to be sure you got the right one:
$(document).ready(function() {
var answervotes = $(".parent-form1");
$('#avote_down, #avote_up').on("click",function(e) {
e.preventDefault();
answervotes.submit();
});
answervotes.on("submit", function(e) {
e.preventDefault();
//do ajax
});
});
here is a jsfiddle:
https://jsfiddle.net/cyvpkvkk/
Solved.
I nested the submit function into the click function and execute the form submit and the following actions after executing the submit function:
$('#avote_down, #avote_up').on("click",function(e) {
e.preventDefault();
clase = $(this).parents("form:first").attr('class');
clasedot = '.'+clase;
answervotes = $(clasedot);
answerdata = answervotes.serializeArray();
answervotes.bind('submit',function () {
$.ajax({
url: answervotes.attr('action'),
type: answervotes.attr('method'),
cache: false,
dataType: 'json',
data: answerdata,
success: function(data) {
if(data.message == "plus")
{
$("#avote_up").attr('class','options options-hover');
$("#avote_down").attr('class','options');
$("#atotal-votes").html(data.votes);
console.log(data.votes);
}
if(data.message == "sub")
{
$("#avote_down").attr('class','options options-hover');
$("#avote_up").attr('class','options');
$("#atotal-votes").html(data.votes);
console.log(data.votes);
}
if(data.name == "register")
{
$('.theme-actions').append('<div class="should-login"><span>' + data.message + '</span><div id="close"></div></div>');
setTimeout(function() {
$('.should-login').fadeOut(300);
},4000);
setTimeout(function() {
$('.should-login').remove();
},4300);
}
if(data.name == "limited_votes")
{
$('.theme-actions').append('<div class="should-login"> <span>' + data.message + '</span><div id="close"></div></div>');
setTimeout(function() {
$('.should-login').fadeOut(300);
},4000);
setTimeout(function() {
$('.should-login').remove();
},4300);
}
if(data.name == "repeated_vote")
{
$('.theme-actions').append('<div class="should-login"><span>' + data.message + '</span><div id="close"></div></div>');
setTimeout(function() {
$('.should-login').fadeOut(300);
},4000);
setTimeout(function() {
$('.should-login').remove();
},4300);
}
},
error: function(xhr, textStatus, thrownError) {
console.log(data.message);
alert("error");
}
});
return false;
});
answerdata.push({name: encodeURI($(this).attr('name')), value: encodeURI($(this).attr('value'))});
answervotes.submit();
answerdata.pop();
});
it solved the basics problem, then I used unique forms classes and call the elements inside of it by using the form parent class so I can call just that element, even if they are some more ids called like that one it doesn't show problems because every form has an unique class to call the nested elements on it.
for the record: the variables stayed outside the functions, on the document.ready
I am still quite new to JQuery and I am trying to make a simple pop-up message to confirm a delete, but I want the table row to turn red during this process.
I found this code that seems sweet, short, and simple.
$(document).ready(function(){
$('.confirm').click(function(){
var answer = confirm("Are you sure you want to delete this item?");
if (answer){
return true;
} else {
return false;
}
});
});
from: http://brettgregson.com/programming/how-to-make-a-are-you-sure-pop-up-with-jquery/138
And I am "attempting" to add it onto my current deleteFunction(), but I am still pretty new to JQuery and I am having some "bugs" with it.
My deleteFunction (no confirmation - but color updating works fine)
function deleteFunction(element) {
var newID = $(element).closest("td").find("span.ID").text();
$(element).closest("tr").css('background-color', 'red');
$.post(
'#Url.Action("customDelete", "Movie")',
{
'id': newID
},
function (data) { },
"json"
);
$(element).closest("tr").hide();
}
My insertion of the confirmation box works, but does not update the tr background color, nor does it revert the color back to the default upon cancellation.
function deleteFunction(element) {
var newID = $(element).closest("td").find("span.ID").text();
$(element).closest("tr").css('background-color', 'red');
$(document).ready(function () {
var answer = confirm("Are you sure you want to delete this item?");
if (answer) {
$.post(
'#Url.Action("customDelete", "Movie")',
{
'id': newID
},
function (data) { },
"json"
);
$(element).closest("tr").remove();
return true;
} else {
$(element).closest("tr").css('background-color', 'default');
return false;
}
});
}
If someone could explain why the CSS color is not being touched until after the confirmation box appears (or why it does not remove the color after Cancel is pressed) it would be very much appreciated.
I've created a jsfiddle for you: working sample. As for clearing the color, you should use css('background-color', 'initial'). As for highlighting - it should highlight, as sample does. If it does not help, then feel free to reveal your html markup, most likely the issue is there
You can call your delete function if user wants to delete, like this way
here is your delete function:
function deleteFunction(element) {
var newID = $(element).closest("td").find("span.ID").text();
$(element).closest("tr").css('background-color', 'red');
$.post(
'#Url.Action("customDelete", "Movie")',
{
'id': newID
},
function (data) { },
"json"
);
$(element).closest("tr").hide();
}
and here is cofirm to delete:
$(document).ready(function(){
var ans=confirm("Are you sure you want to delete this item?");
if(ans)
{
deleteFunction(element);
}
else
{
return false;
}
});
when I click on the log in button the pop up open correctly. But when I close it and again click on the log in button without refreshing the page, it doesn't appear.
my code is:
<script type="text/javascript">
load_login_page = function() {
$.get(HOST_NAME + "e_commerce/ECommerces/ecommerce_login", {}, function(data) {
$("#temp_login_box").html(data);
$.blockUI({
message:$('#temp_login_box'),
css:{
top:($(window).height() - 300) / 2 + 'px',
left:($(window).width() - 800) / 2 + 'px',
width:'620px',
border:'none',
background:'none',
cursor:'default'
},
overlayCSS:{ backgroundColor:'#333' }
});
load_login_ajax_form();
});
};
load_login_ajax_form = function () {
var options = {
beforeSubmit:show_login_request, // pre-submit callback
success:show_login_response // post-submit callback
};
$('#product_info_form').ajaxForm(options);
};
show_login_request = function (formData, jqForm, options) {
return true;
};
show_login_response = function (responseText, statusText, xhr, $form) {
if (responseText == 'ok') {
// $("#temp_login_box").html(responseText);
window.location.href = HOST_NAME + "e_commerce/ECommerces/user_desboard";
//load_login_ajax_form();
} else {
$("#temp_login_box").html(responseText);
load_login_ajax_form();
}
};
hide_login_info = function() {
$.unblockUI();
};
hide_login_info is form closing function. temp_login_box is id to targeted div. please help me out with this code.
Please trace your function load_login_page to check whether $.get called every time.
because you are creating $.blockUI in success of $.get
To check more i need $.unblockUI Code.
But what i suggest is, in unblockUI function either you do empty the div or hide it.
If you hide it then to show on click you have to write $().show(); in $.blockUI function
if it is not the reason
provide $.unblockUI code then might be i can help you.
Note is jquery selector for the div you hide
I'm not too sure what's going on here and feel I may be missing something that is probably quite obvious, but I have an if else in which both statements are being called. If someone could shed some light on this that would be great. The code below is using asual and should be detecting whether or not a div $('#' + $.address.hash() has already been loaded. However both if and else events are being fired in order. In fact the else statement fires twice...
$('#lmit_back').show(400, function() {
if($('#' + $.address.hash() ).length == 0) {
$('#init').load('inithandler.php', { 'address' : $.address.hash() }, function() {
$('#' + $.address.hash()).fadeIn(1000, function() {
$('#remn').load('pagehandler.php',{ 'address' : $.address.hash() });
});
});
}
else {
alert('hey');
}
});
Here is all the code..I can't really work out what could cause it to execute twice, unless it has something to do with address.change which im not as familiar with as I would like to be.
if (($.address.hash() == '')) {$.address.hash('home');}
$('#lmit_back').click(function() {
$.address.hash('home');
});
$.address.change( function() {
if (!($.address.hash() == 'home'))
{
var exception = '.' + $('[href="#' + $.address.hash() + '"]').parent().attr('class');
$('#left_menu_bar li:not(' + exception + ')').hide(300,function() {
$(exception).show( function() {
$('#left_menu_bar').animate({ width:'100%'},400, function() {
$('#lmit_back').show(400, function() {
if ($('#' + $.address.hash() ).length === 0)
{
$('#init').load('inithandler.php', { 'address' : $.address.hash() } , function() {
$('#' + $.address.hash()).fadeIn(1000, function() {
$('#remn').load('pagehandler.php',{ 'address' : $.address.hash() });
});
});
}
else
{
alert('nigs');
}
});
});
});
});
}
else
{
$('#left_menu_bar').animate({ width:'251px'}, function() {
$('#left_menu_bar li').show( function() {
$('#lmit_back').hide();
});
});
$('#left_menu_bar').css('width','251px');
}
});
The problem here is not arising from the code you have pasted. The only way the code could be running multiple times and hitting multiple branches is if it is being executed more than once. Look to the surrounding code for places where this could be called more than once.
I faced similar issue, while debugging when if condition was true it also went in else block. Later I added alert and console.log in if/else block's & realized, else was not actually being executed but while debugging it looked like it was in else.
So, whoever faces same issue verify by adding alert or console.log.
I was seeing the same behavior, when I debugged step by step it worked. It ended up being that I was attaching multiple click events so the code fired n times.