I have obviously done something stupid or failed to understand some fundamental process. Very early days playing with this.
I am trying to check for a form being validated, when the Submit Button is clicked with the onClick method.
<input class="submit" type="submit" value="Submit" onClick="submitForm()" />
I am using Jquery and the plug-in Validate. The problem I have is validating on each field is occurring, but if I click on submit with no data or not every field has been tested, I would need to validate the whole form, before submitting, I should get a return of false from validate().form(). This is not occurring as the else statement in submitForm() is never being executed.
On an empty form, after clicking submit the field error messages are shown, but my testing of a return for false, does not seem to work.
$(document).ready(function() {
$('#formEnquiry').validate();
});
function submitForm() {
$('#msgid').append('<h1>Submitting Form (External Routine)</h1>');
if ($('#formEnquiry').validate().form()) {
$("#msgid").append("<h1>(Outside Ready) VALIDATED send to PHP</h1>");
}
else {
$('#msgid').append('<h1>(Outside Ready) NOT VALIDATED</h1>');
}
};
An example of Ajax
$(function() {
$("#ipenter").submit(function() {
var ip = $("#ip").val();
var date = $("#date").val();
var spammer = $("#spammer").val();
var country = $("#country").val();
var total = $("#total").val();
var dataString = $('#ipenter').serialize();
$.ajax({
url: "/test/process",
data: dataString,
type: "POST",
success: function(msg) {
$('#ipenter').append('<h3 class="gotin">Post succesfull!');
$('h3.gotin').delay(8000).fadeOut(500);
},
error: function(data){
$('#ipenter').prepend('<h3 class="didnt">Post sucked!');
$('h3.didnt').delay(8000).fadeOut(500);
}
});
return false;
});
});
You dont really even need the val() part
You can also throw some validation into this script before the ajax
if (spammer == "") {
$("#spammer_error").show();
$("input#image").focus();
return false;
This is a basic example of ajax(I'm using codeigniter so you may need to use a valid URL for the url)
Related
In my form i am checking if there is same value in database or not when form submitted. The code below works fine and is giving the rigth result of AJAX post but the problem is when giving alert according to the wrong result, javascript alert and focus works but form still submits after these.
Button for submit:
<input type="submit" name="kaydet" class="btn btn-success form-control"
onClick="return kaynak_kontrol()" value="Kaydet">
AJAX:
<script type="text/javascript">
function kaynak_kontrol(){
Form=document.forms['depo_kayit'];
var depo_sube_no = document.getElementById('depo_sube_no').value;
var depo_firma_no = document.getElementById('depo_firma_no').value;
var depo_kodu = document.getElementById('depo_kodu').value;
var dataString ="depo_sube_no="+depo_sube_no+"&depo_firma_no="+depo_firma_no+"&depo_kodu="+depo_kodu;
$.ajax({
type: "POST",
url: "depo_kodu_kontrol.php",
data: dataString,
success: function(result){
if(result != 0){
alert("Aynı şubede aynı isimde iki depo olamaz!");
document.getElementById('depo_kodu').focus();
return false;
} else {
return true;
Form.submit();
}
}
});
}
</script>
Can you help me why i return false is not working and form still submits?
you need to prevent the form submission manually using jQuery event.preventDefault()
here is a small fix
function kaynak_kontrol(event){ // notice the new parameter !
event.preventDefault();
//the rest of your code
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.
WHAT IM DOING
I'm using jquery to validate form before it is send to server.
I'm validating every input, and if any of them return false i call event.preventDefault() and show the errors.(if it returns true I do nothing...)
THE PROBLEM
It was working fine, the script always run before the form send itself, but now I'm validating email, using ajax - checking if email isnt already in db or if the domain exists... but when the ajax starts, the the form wont wait until its finished and sends itself before the ajax finish and the input validates.
SOME SOLUTIONS MAYBE
I could call event.preventDefault() and after the validation is completed and it returns true I could try to undo the preventDefault perhabs by unbind and then submit through jquery submit the form again.
Or perhabs I could do onsubmit="checkInputs();" and it should wait until it returns true or false...
Solution - Adapted from the accepted answer by user Mirage
function validate(){
$.ajax({
url: 'http://google.nl',
async: false,
type: "POST",
data: {test:'request'},
success: function(data){
console.log(data);
}
});
return data; // important
}
try to add
async: false
example:
$.ajax({
url: 'http://google.nl',
async: false,
type: "POST",
data: {test:'request'},
success: function(data){
console.log(data);
}
});
you want:
onsubmit="checkInputs(); return false;"
Then you would grab the form e.g:
var frm = document.getElementById("myfrm");
frm.submit();
You would place the above in the else condition of your validation logic. Hope this helps.
Your script flow should be something like this:
Bind onsubmit handler
Send vars to server with ajax
Check results
When validates: remove handler and post form
When false: show error messages and start over again.
And in code:
var handleValidationResponse = function(data) {
if(data.errors != 0) {
alert('Sorry my dear user, but you made a mistake');
return false;
}
// aight, so it's all fine
$('#myForm').off('submit').trigger('submit'); // unbind custom submit handler and post the form
};
$('#myForm').on('submit', function(e) {
e.preventDefault();
var $this = $(this);
var serializedFormData = $this.serializeArray();
$.post($this.attr('action'), serializedFormData, function(data) {
handleValidationResponse(data);
});
});
That should be it!
I have been trying to solve a simple but, for me, really hard problem.
I have a form and I need to add data from the form to a database, but with form validation. For validation I use the parsley plugin and for some input fields I use select2 plugin.
I try to add form in this way (Comments is in code):
//try to see is zemljiste or vrsta_rada = null to do not add data to database
var zemljiste = $("#parcele").select2("data");
var vrsta_rada = $("#vrsta_rada").select2("data");
//Now when I click on #dodaj I need to chech is zemljiste or vrsta_rada == null to do not start function for adding data but DONT work
$("#dodaj").click(function () {
if (zemljiste == null || vrsta_rada == null) {
alert('PLEASE fill the fields');
} else {
//HERE if zemljiste and vrsta_rada != null start validation and this also dont work
$('#myForm').parsley().subscribe('parsley:form:validate', function (formInstance) {
formInstance.submitEvent.preventDefault(); //stops normal form submit
if (formInstance.isValid() == true) { // check if form valid or not
zemljiste = $("#parcele").select2("data").naziv;
id_parcele = $("#parcele").select2("data").id;
vrsta_rada = $("#vrsta_rada").select2("data").text;
//code for ajax event here
//Here is ajax and when I fill all fields I add data to database but here success and error into ajax dont work???
$.ajax({
url: "insertAkt.php",
type: "POST",
async: true,
data: {
naziv: $("#naziv").val(),
parcele: zemljiste,
vrsta_rada: vrsta_rada,
opis: $("#opis").val(),
pocetak: $("#pocetak").val(),
zavrsetak: $("#zavrsetak").val(),
status: $("#status").val(),
id_parcele: id_parcele,
}, //your form data to post goes here as a json object
dataType: "json",
success: function (data) {
//SO if success I add data but this code below dont work also in error dont work
$('#myModal').modal('hide');
drawVisualization();
console.log('YESSSSSSS');
console.log(data);
},
error: function (data) {
console.log(data);
}
});
}
});
}
});
With this, I have a few problems...
1. When submit code, the page refreshes and I don't want to do that.
2.When I fill in all the fields, I add data to the database but also add all the previous attempts with incorrect information. Why?
3. Why can I not see what return my success and error into .ajax in console.log ???
Look the pictures:
I have this function(to make my form work with ajax):
$(function() {
$('#restore_form').ajaxForm({
beforeSubmit: ShowRequest,
success: SubmitSuccesful,
error: AjaxError
});
});
function ShowRequest(formData, jqForm, options) {
var queryString = $.param(formData);
alert('BeforeSend method: \n\nAbout to submit: \n\n' + queryString);
return true;
}
function AjaxError() {
alert("An AJAX error occured.");
}
function SubmitSuccesful(responseText, statusText) {
alert("SuccesMethod:\n\n" + responseText);
}
my form(django form) only contains a file upload field. i want also check validation and i have this function for this purpose:
function TestFileType( fileName, fileTypes ) {
if (!fileName) {
alert("please enter a file");
return false;
}
dots = fileName.split(".")
fileType = "." + dots[dots.length-1];
if(fileTypes.join(".").indexOf(fileType) != -1){
alert('That file is OK!') ;
return true;
}
else
{
alert("Please only upload files that end in types: \n\n" + (fileTypes.join(" .")) + "\n\nPlease select a new file and try again.");
return false;
}
}
now when i try to use validation function(TestFileType) in the first function, it doesn't work. both of them works seperately. fore example if i write the below line in onclick of submit button, it works:
onclick="TestFileType(this.form.file.value, ['tar.gz']);"
I also want instead of alerting user, show a hidden div in success function:
i have:
and i want in success function do:
$('.response').html(responseText);
$('.response').show();
EDIT:
Here is my template:
<form id="restore_form" enctype="multipart/form-data" method="POST" action="restore/">
{{ form.non_field_errors }}
{{ form.as_p }}
{{ form.file.errors }}
<p id="sendwrapper"><input type="submit" value="{% trans "Send" %}" id="submitButton" style="margin-bottom:10px; cursor:pointer; background-color:#F90;"/></p>
</form>
<div class="response" style="display: none;"></div>
but it doesn't work! it seems only alert works in this function. Can you please help me?
really thanks :)
I've attempted to use the AjaxForm plugin in the past and found that unless you have a very specific reason to use it, it's typically easier to write the ajax form submit code without the plugin. This is a simplified/commented version of a previous jquery ajaxform that I created using Jquery without the plugin:
$('form').submit(function(event) {
var form = $(this);
// creates a javascript object of the form data
// which can be used to validate form data
var formArray = form.serializeArray();
// (validate whatever values in formArray you need to check here);
if (form_is_valid) {
var formData = form.serialize(); // a URL-encoded version of the form data for the ajax submission
$.ajax({
type: "POST",
url: someUrl,
data: formData,
success: function(data) {
// update success message boxes here
}
});
} else {
// update client-side validation error message boxes
}
event.preventDefault(); // prevent the form from actually navigating to the action page
});
Hopefully this helps, I've found that the plugin can be useful at times, however I've typically found that this leads to easier to understand code and avoids the use of plugins..