In case the user fills some invalid data, an ajax request is fired and error message is displayed. Now when the user again corrects the data/or enters invalid data again, 2 requests are fired, the next time 3 and it keeps on adding up.
This is probably because of the parsley js library. If I remove parsley code it works fine. Any idea?
Here is the ajax code
$('#upload-profile-button').on('click', function(e) {
$("#upload-profile-form").parsley().validate();
$("#upload-profile-form").parsley().on('form:validate', function (formInstance) {
var isFormValid = formInstance.isValid();
if(isFormValid){
e.preventDefault();
$('#upload-profile-button').html('Uploading...');
var fd = new FormData($("#upload-profile-form")[0]);
$.ajax({
type : 'POST',
url : '/mbatch/batch/uploadBatch',
data : fd,
processData : false,
contentType : false,
beforeSend : function() {
},
success : function(response) {
if (response.data.fetchTpodSuccess == true) {
window.location.href= "/mbatch/batch/listBatch";
} else {
new PNotify({
title: 'Notice',
text: response.message,
type: 'error',
styling: 'bootstrap3'
});
$('#upload-profile-button').html('Submit');
}
},
error : function(data) {
new PNotify({
title: 'Notice',
text: JSON.parse(data.responseText).message,
type: 'error',
styling: 'bootstrap3'
});
$('#upload-profile-button').html('Submit');
}
});
}
});
});
Here is the HTML code snippet
<button id="upload-profile-button" type="button"
class="btn btn-primary">Submit</button>
Any leads would be highly appreciated.
I just found out the solution.
This was because I was using data-parsley-validate in the form tag as well
and in the js as well
<form id="upload-profile-form" data-parsley-validate enctype="multipart/form-data"
name = "uploadBatchForm"
class="form-horizontal form-label-left"
>
Parsley looks at all data-parsley-validate occurrences in DOM on document load and automatically binds them if valid.
Once a form or field instance is bound by Parsley, doing $('#form').parsley(options); will update the existing options but not replace them.
Source - http://parsleyjs.org/doc/index.html
Maybe you render your script after each call, so it could append your click function to the click event multiple times.
If this is the case, first try to unbind your click event before appending one like this:
$('#upload-profile-button').unbind('click').on('click',...
Related
$('#addProduct').click(function (e) {
$('#qty').attr('required', 'required');
$('#product_id').attr('required', 'required');
e.preventDefault();
var product_id = $('#product_id').val();
var data = $("#editOrderContent").serializeArray();
data.push(addProduct);
$.ajax({
type: 'POST',
dataType: 'JSON',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: $('#editOrderContent').attr('action'),
data: data,
success: function (html) {
if (html.error) {
$('.wrap_result')
.text(html.error)
.fadeIn(500).delay(3000).fadeOut(500);
}
else if (html.success) {
$('#summary').before(html.tdProduct);
$('#summary_qty').text(html.summaries['qty']);
$('#summary_price').text(html.summaries['price'] + ' $.');
$('#summary_sum').text(html.summaries['sum'] + ' $.');
$('#product_id').val('');
$('#qty').val(1);
}
}
});
});
These 2 fields has required attributes but ajax still completing even with empty values in these fields, also ajax ignores min value of #qty field
Why is this happening?
Use $('#formid').valid() method before making ajax request read more about .valid()
e.preventDefault tells the event NOT to perform it's default action of submitting the form.
You're then making the fields required. That's fine - but they'll only be checked on submit. The form isn't actually being submitted at any point, you've told it to prevent that action.
You need to add a $('#form').submit(); Or add required directly to the html markup.
EDIT: Much more code added to the question. This may no longer apply.
I have a simple page that takes a form and makes a jsonp ajax request and formats the response and displays it on the page, this is all fine, but I wanted to add it so that if the form was populated (via php $_GET variables) then the form would auto-submit on page load but what happens instead is that the page constantly refreshes despite the submit function returning false.
Submit Button (just to show it doesn't have an id like submit or anything)
<button type="submit" id="check" class="btn btn-success">Check</button>
jQuery
$(document).ready(function() {
$('#my_form').on('submit', function() {
var valid = 1;
$('#my_form .required').each(function() {
if ($(this).val() == '') {
$(this).parents('.form-group').addClass('has-error');
valid = 0;
} else {
$(this).parents('.form-group').removeClass('has-error');
}
});
if (valid === 1) {
$.ajax({
url: '/some_url',
data: $('#my_form').serialize(),
type: 'GET',
cache: false,
dataType: 'jsonp',
success: function(data) {
var html = 'do something with data';
$('#results').html(html);
},
error: function() {
$('#results').html('An error occurred, please try again');
}
});
} else {
$('#results').html('Please fill in all required fields');
}
return false;
});
});
The part I added just after the $(document).ready(function(){ and before the submit was:
if ($('#input_1').val() != '' || $('#input_2').val() != '') {
// $('#check').trigger('click');
$('#my_form').submit();
}
Both those lines have the same effect but I am doing the same in another project and it works fine, as far as I can see, the only difference is the jQuery version, I'm using 1.11 for this page.
Update
Apologies, I seem to have answered my own question, I thought that since the programmatic submit was the first thing in $(document).ready(function(){ then maybe it was the case that the actual submit function wasn't being reached before the event was triggered so I simply moved that block after the submitfunction and it now works fine.
url: ''
it seems like you are sending your ajax request to nothing.
just an additional: if you want to submit your form through jquery without using AJAX, try
$("#myForm").submit();
it will send your form to the action attribute of the form, then redirect the page there.
I'm working on a login/registration for a simple web app. I'm using Foundation to do so. The index page shows a login screen and a register button, if the user clicks this a Reveal Modal appears which includes the register form. This form uses abide to do the data validation (email address, matching passswords etc.). I want the 'register' submit button to be disabled if there are any validation errors and then not disabled when everything is good.
I have used the code on the Foundation Docs where it says:
$('#myForm')
.on('invalid.fndtn.abide', function () {
var invalid_fields = $(this).find('[data-invalid]');
console.log(invalid_fields);
})
.on('valid.fndtn.abide', function () {
console.log('valid!');
});
For some reason (that I can't find after much searching) these events aren't firing. My form has the correct ID, my js file is loading correctly (I put console.log messages either side of that jquery code) and I've tried calling:
$(document).foundation('abide','events');
as suggested here. But I'm still not getting any events.
Any ideas? Could it be because I've got it in a modal or something?
Thank you for your time.
EDIT: I found this page here which says to add:
$('#your_form_id').foundation({bindings:'events'});
instead of:
$(document).foundation('abide','events');
But that doesn't seem to change anything either.
Try using $.getScript after loading the form to run the javascript.
eg:
$('#myModal').foundation('reveal', 'open', {
url: 'form.html',
close_on_background_click:true,
success: function(data) {
$.getScript( "form.js", function() {});
}
});
I had the same problem with fancybox and ajax check before submit.
This is my solution that works for sure
<form id="my_form" action="...." method="POST" class="popup" data-abide="ajax">
<input type="text" name="check_this_field_with_ajax" id="check_this_field_with_ajax">
....
</form>
<script type="text/javascript" src="..../js/foundation.min.js"></script>
<script type="text/javascript" src="..../js/foundation/foundation.abide.js"></script>
<script type="text/javascript">
$('#my_form')
.on('invalid.fndtn.abide', function() {
console.log('NOT Submitted');
})
.on('valid.fndtn.abide', function() {
console.log('VALID');
})
.on('submit', function(e) {
var ajaxRequest = $.ajax({
type: 'GET',
url: "....",
data: {xxx: yyy},
cache: false,
dataType: 'json',
});
....
ajaxRequest.done(function() {
if (ok) {
$('#check_this_field_with_ajax').parent().removeClass('error');
$('#my_form').attr({'submit_this_form': 'yes'});
$(document).foundation('abide', 'reflow');
$('#my_form').trigger('submit.fndtn.abide');
}
});
}
</script>
in foundation.abide.js search line "validate : function (els, e, is_ajax) {" and add:
if (
is_ajax &&
form.attr('submit_this_form') === 'yes'
) {
return true;
}
before
if (is_ajax) {
return false;
}
I'm attempting to learn to make use of AJAX. I removed most of the complexity of the program to just isolate the problem I'm having. So I have a text area and beneath that a div that has "STATUS" printing out. On button submit using AJAX I want to change the word "STATUS" to the value of my variable, status, which in this case should be "SUCCESS".
What happens instead when I click is it prints out the word STATUS. It appears like nothing is happening when I click my submit button. Any ideas what I am doing wrong?
$(document).ready(
function () {
$('#sub').live('click',
function () {
url = 'http://whatever.php'
success = "Success!"
$.ajax({
url: url,
type: 'POST',
data: null
dataType: 'xml',
async: false,
success: function (data, statusText, reqObj) {
status = $(data).find('status').text()
if (status == 'SUCCESS') {
$('#succ').html(status)
} //if( status == 'SUCCESS' ) {
else {
msg = $(data).find('msg').text()
alert('NOT ADDED: ' + msg)
return
} // else
} //function()
}) //$.ajax( {
} /* function */ ) //live(
} //function()
) //$(document).ready
HTML:
<div id="buttonArea">
<textarea name="txtarea" cols=80 rows=30>>THIS TEXT BOX
IS USED FOR THINGS I WILL WORK ON LATER
</textarea><br/>
<input type=submit value='Submit Textbox Info!' id='sub'>
</div>
<div class="float-left" id='succ'>STATUS</div>
I think your find is empty. Try to replace with
status = $(data).text()
I'm not sure you use .find() the right way. it's used on html elements and expects to be passed a jquery selector or element or jquery object.
here's more details http://api.jquery.com/find/
what you want is to get your response text, so assign your ajax call to a variable:
xmlhttp = $.ajax({
then on success use your response text:
status = xmlhttp.responseText;
Your code works fine for me, on the proviso that:
(i) you add the missing comma from the line:
data: null,
(ii) the content-type returned by your php handler is text/xml
So i have this function in JS, sending a request to insert a new Status message to the database.
function DoStatusInsert(){
var wrapperId = '#statusResponseNow';
$.ajax({
type: "POST",
url: "misc/insertStatus.php",
data: {
value: 'y',
uID : $('#uID').val(),
message : $('#message').val()
},
success: function(msg){
$('#message').val("");
$('#statusResponse').toggle();
$(wrapperId).prepend(msg);
$(wrapperId).children().first().fadeIn('slow');
}
});
}
With this form:
<input name="message" type="text" id="message" value="" size="60">
<input type="hidden" name="uID" id="uID" value="<?php echo $v["id"]; ?>">
<input name="submit" type="submit" id="submit" value="Spara">
<div id="statusResponseNow"></div>
Now I wish to do something like blocking the submit button or the message field to "read-only" until you receive response / success, so you don't have the opportunity to like press submit alot of times so it inserts alot.. (i know you could make a php for checking after doubleĀ“s in DB)
So: when you click on submit then it makes either message field and/or submit button to read only
How should i do it?
function DoStatusInsert(){
$('#IdOfYourSaveButton').attr('disabled', 'disabled');
var wrapperId = '#statusResponseNow';
$.ajax({
type: "POST",
url: "misc/insertStatus.php",
data: {
value: 'y',
uID : $('#uID').val(),
message : $('#message').val(),
success: function(msg){
$('#IdOfYourSavebutton').removeAttr('disabled');
$('#message').val("");
$('#statusResponse').toggle();
$(wrapperId).prepend(msg);
$(wrapperId).children().first().fadeIn('slow');
}
});
}
enabled and disable the button. nice and easy :)
On calling the function, set the disabled property of the button, and then set it back on success.
function DoStatusInsert(){
$('#submit').attr("disabled", "true");
var wrapperId = '#statusResponseNow';
$.ajax({
type: "POST",
url: "misc/insertStatus.php",
data: {
value: 'y',
uID : $('#uID').val(),
message : $('#message').val()
},
success: function(msg){
$('#message').val("");
$('#statusResponse').toggle();
$(wrapperId).prepend(msg);
$(wrapperId).children().first().fadeIn('slow');
$('#submit').attr("disabled", "false");
}
});
}
My initial thoughts would be to insert
$('input[type=submit]', this).attr('disabled', 'disabled');
before the ajax call is started and then removed the disabled attribute with the success function of the ajax request.
Manually toggling the disabled state of the button works well enough, but jQuery has a couple helper events to make that a bit nicer: .ajaxStart() and .ajaxStop(). You can use those two handlers on your submit button and not have to worry about maintaining that manual code around your $.ajax() request.
Just throw this in with your other initialization code, probably in $(document).ready():
$('#submit').ajaxStart(function() { this.disabled = true; });
$('#submit').ajaxStop(function() { this.disabled = false; });
You can use for example jQuery BlockUI Plugin from http://jquery.malsup.com/block/ (see demo on http://jquery.malsup.com/block/#element and http://jquery.malsup.com/block/#demos).
If a div with all your form elements which you need to block has id formDiv then you can call
jQuery('#formDiv').block({ message: '<h1>Just a moment...</h1>' });
before jQuery.ajax and call
jQuery('#formDiv').unblock();
as the first line in both success and error handler of the jQuery.ajax.