There is fairly complex php POST form with great deal of data validation using jQuery like below. However, I'm running into some problems cause it seems like form is getting submitted before the validation gets completed.
Question : Is it possible that the validation is taking so long, that the form is submitted by default, before jQuery has even returned true or false? If so, what is the best way to deal with this?
jQuery('#order-form').submit(function(){
// Validate many different fields in various ways
if (valid)
return true;
else
return false;
});
Since we can't see your code and how it validates, maybe you can try your function another way.
Try and use the click function on your submit button to validate your items, then if all is good, submit.
e.g.
$('#btn1').click(function(e){
var valid
if($('#ex1').val() == ""){
valid = false;
}else{
valid = true;
}
if(valid){
$("#testform").submit();
}else{
alert("not validated");
}
e.preventDefault();
});
See fiddle as example.
http://jsfiddle.net/em62Z/1/
Also I use this plugin to validate my forms. It can validate any size form and even some complex fields.
https://github.com/posabsolute/jQuery-Validation-Engine
It works well and might save your trouble doing your own validation if you are doing your own.
Here is the code snippet as an example for contact form that can help you, i used jqueryvalidation.org plugin and posting form using ajax
$(function() {
var form = $("#contact_form").validate();
$('#progressbar').hide();
$('#success').hide();
$('#failure').hide();
$(document).ajaxStart(function() {
$( "#progressbar" ).show();
});
$(document).ajaxStop(function() {
$( "#progressbar" ).hide();
});
$("form#contact_form").submit(function() {
if(form.valid())
{
//any other validations here
var name = $("#txtName").val();
var email = $("#txtEmail").val();
var phone = $("#txtPhone").val();
var message = $("#txtMessage").val();
$.ajax({
url: "process_contact.php",
type: "POST",
data: {'name': name,
'email': email,
'phone': phone,
'message': message},
dataType: "json",
success: function(data) {
if(data.status == 'success')
{
$('#contact_form').hide();
$('#success').show();
}
else if(data.status == 'error')
{
$('#failure').show();
}
}
});
return false;
}
});
});
As far as I know, only two conditions that your case could happen :
there is an error in your validation's code, or
javascript is turned off.
In regard of client side validation, have you tried jQuery Validation? It validate every elements in form on two events :
everytime elements are changed, and
when form is submitted.
You could also add custom method to do a unique validation for each condition in each element.
For more info and examples (with and without ajax) regarding jQUery Validation : here.
Related
I am using Codeigniter and i am creating a login registration form which check the email of user that it available or not. User can login with that id.
So I am Trying to use Ajax for it.
So I have Put this Ajax in my View.
$(document).ready(function() {
$("#email").keyup(function() {
var email = $(this).val();
if (email.length > 3) {
$("#result").html('checking...');
$.ajax({
type: 'POST',
url: emailAvailability,
data: { email: email },
success: function(data) {
console.log(data);
$("#result").html(data);
if (data.indexOf('Available')) {
emailAvaliable = 1;
//$('#candidateLogin').removeClass('disabled');
} else {
emailAvaliable = 0;
//$('#candidateLogin').addClass('disabled');
}
}
});
return false;
} else {
$("#result").html('');
}
});
});
I am Using parsley plugin for validation.
$(".formValidationClass").on('click', function (e) {
e.preventDefault;
$(this).parsley();
});
Now the Controller Code.
public function check_email_availability(){
$data = $this->input->post();
// Now I want to check email is unique or not without going to database.
}
The Second Problem is i want to disable the form till email is available & valid.
I have tried this script to disable the form to submit but it's not working and form get submitted. I have done the server side validation to not submit but still i want to prevent it form the client side.
this is the script.
$(".formValidationClass").on('click', function(e) {
e.preventDefault;
$(this).parsley().validate();
console.log('on form click, After validation');
// return false;
});
var emailAvaliable = 0;
$(".formValidationClass").submit(function(event) {
// Validate form fields
if (emailAvaliable == 1) {
console.log('Email Avaliable');
$(this).parsley();
return true;
} else {
console.log('Email not Avaliable');
return false;
}
});
All the suggestion related improving the code is acceptable. Thanks.
if you want to prevent the form submit event then please use: e.PreventDefault(); Check this Using JQuery - preventing form from submitting for more information. I think this is useful for you.
I have an application that I'm writing that, in one aspect of it, you click on a checkmark to complete a task, a popup window is displayed (using bootstrap), you enter your hours, and then that is sent to a PHP page to update the database. I'm using FF (firebug) to view the post. It's coming up red but not giving me an error. The only thing I'm doing is echoing out "sup" on the PHP page, and it's still showing errors, and I can't figure out why.
This is my initial click function:
$('.complete').on('click', function(event) {
var id = $(this).attr('data-id');
var tr = $(this).parent().parent();
var span = $(tr).children('td.task-name');
var r = (confirm('Are you sure you want to complete this task?'));
if (r){
addHours(id);
} else {
return false;
} // end else
});
That works fine, and it fires my next function which actually fires the bootstrap modal:
function addHours(id) {
var url = 'load/hours.php?id='+id;
$.get(url, function(data) {
$('<div class="modal hide fade in" id="completeTask">' + data + '</div>').modal()
.on('shown', function() {
pendingTask(id);
}); // end callback
}).success(function() {
$('input:text:visible:first').focus();
});
} // end function
This is also working, and the modal is displayed just fine. However, whenever I post the form to my logic page, it fails for no reason. This is the function to post the form to the logic page:
function pendingTask(id) {
$('.addHours').on('click', function(event) {
var formData = $('form#CompleteTask').serializeObject();
$.ajax({
url:'logic/complete-with-hours.php',
type: 'POST',
dataType: 'json',
data: formData,
success: function(data) {
if (data.status == 'error') {
$(this).attr('checked', false);
//location.reload();
} // end if
else {
$(this).attr('checked', true);
//location.reload();
} // end else
},
dataType: 'json'
});
}); // end click
} // end function
When this is fired, I see this in my Firebug console:
I know this is a lot of information, but I wanted to provide as much information as I could. Every other post function in the application is working fine. It's just this one. Any help would be appreciated.
Thanks in advance.
The jQuery.ajax data parameter takes a simple object of key value pairs. The problem could be that the object created by serializeObject() is too complex. If that's the case, you could either process the formData object to simplify it or try data: JSON.stringify(formData)
Does serializeObject() even exist in jQuery? is that a function you wrote yourself? Can you use jQuery functions like serialize() or serializeArray() to serialize the form data and see how it goes.
Usually the red indicates a 404 response error. We can't tell in this screen shot. Check your php code by directly calling the requested page and getting a proper response.
Also make sure your dataType is application/json which is the proper mime type header (though I don't think this is causing the error). You also should only have dataType once (you have it again at the bottom)
I figured it out. I changed the post type from the structure I entered above to a standard post:
$("#CompleteTask").validate({
submitHandler: function(form) {
var hours = $('#hours').val();
$.post('logic/complete-with-hours.php', {'hours': hours, 'id':id},
function(data){
if (data.status == 'success') {
$(checkmark).attr('checked', false);
$('.message').html(data.message).addClass('success').show();
} // end if
if (data.status == 'error') {
$('.message').html(data.message).addClass('error').show();
} // end else
},
"json"
); //end POST
} // end submit handler
}); // end validate
That seemed to do the trick
In this basic jQuery, AJAX, PHP form I want to display errors next to inputs instead of the bottom of the form. I use if(empty(something)) { jQuery here }. Why won't this work? Whats the best practice to do this? Thank you.
HTML:
Name:<input type="text" id="name" /> <span id="name_error"></span>
<input type="button" value="Update!" id="update" /> <span id="name_error"></span>
<span id="update_status"></span>
PHP
<?php
include('init.inc.php');
if(isset($_POST['name'])) {
$name = mysql_real_escape_string(htmlentities($_POST['name']));
if(empty($name)) {
?>
// Why wont this work here? It just outputs the the whole thing as text. in the update_status div (You can see that in the ajax part at the bottom of the code).
<script>
$('#name_error').text('Name required');
</script>
<?php
if(!empty($name)) {
$query = mysql_query("UPDATE users SET
name = '$name'
WHERE user_id = ".$_SESSION['user_id']."
");
if($query === true) {
echo 'Your settings have been saved';
} else if($query === false) {
echo 'Unable to save your settings';
}
}
}
// This is the jQuery / AJAX part -- no issues here. Just have it to include both parts.
$('#update').click(function() {
var name = $('#name').val();
$('#update_status').text('Loading...');
$.ajax({
type: 'POST',
url: 'page.php',
data: 'name='+name,
success: function(data) {
$('#update_status').text(data);
}
});
});
CODE UPDATED
Why aren't you checking for empty before the form submit?
You can stop the form submission and check for empty values with javascript, if all is clear then you can submit the form.
You can do this, but you are specifiying .text()
What you need to do is jQuery("#update_status").html(data);
jQuery("#update").click( function(){
if(jQuery.trim(jQuery("#name").val()) == ''){ alert("empty"); return false; }
jQuery.post("page.php", {name:jQuery("#name").val()}, function(html){
jQuery("#update_status").html(html);
});
});
Note that you PHP page is going to return more than just your intended code as it is now. It is going to try and return the form again also.
You need to wrap your processing and from in separate if/else statement. Better to put them in two separate files and keep ajax stuff separate.
That's a really bad way to do it. The reason it doesn't work is because that JavaScript needs to be parsed and run by the browser first, that's a whole different story and would involve using eval(). The better way to do it would be to send back a JSON object, then use it in your JavaScript to display the message to the user.
I want to do the validation on my PHP side and then have my JQuery code display your changes have been saved when the submit button is clicked but the JQuery code states that the changes have been saved even when the validation fails.
How can i fix this so that PHP can do the validation and then JQuery can do its thing when PHP has finished its validation?
Here is my Jquery code.
$(function() {
$('#changes-saved').hide();
$('.save-button').click(function() {
$.post($('#contact-form').attr('action'), $('#contact-form').serialize(), function(html) {
$('div.contact-info-form').html(html);
$('#changes-saved').hide();
$('#changes-saved').html('Your changes have been saved!').fadeIn(4000).show();
});
$('a').click(function () {
$('#changes-saved').empty();
$('#changes-saved').hide();
});
return false; // prevent normal submit
});
});
Here is part of my PHP code.
// Check for an email address:
if (preg_match ('/^[\w.-]+#[\w.-]+\.[A-Za-z]{2,6}$/', $_POST['email'])) {
$email = mysqli_real_escape_string($mysqli, strip_tags($_POST['email']));
} else {
echo '<p class="error">Please enter a valid email address!</p>';
}
in the jquery you can add a if statment that check if the php validation pass,
in the php you need to return a value like 1\0 or true \ false.
and check this parameter in jquery
i add example its using json but is the same issue
jquery :
$.post($('#contact-form').attr('action'), $('#contact-form').serialize(), function(data_pack){
if(data_pack.msg ==1){
# success do something ....
.........
}
alert(data_pack.html);
}, 'json');
the php code like :
if($validation_ok){
$arr = array('msg'=>1,'html'=>$html);
}
else {
$arr = array('msg'=>0,'html'=>$error_msg);
}
echo json_encode($arr);
exit;
You should validate it with both client-side and server-side (ie. with both JavaScript and PHP). If this is not possible, I'd consider posting the form asynchronously and parsing the reply from the server with javascript to determine whether the changes were saved.
I have a form which has a input textbox and submit button.
On submission of the form the textbox value should get pass to an php script and check the values whether it exists in the Mysql Database. If it exists then we need to show an alert box stating that "Entered Value is already exists, Try something new". If the value not exists the form can be submitted to the php script which is in the form action.
I tried with the jquery and the code is below:
$(document).ready(function() {
$("#form_add").submit(function () {
var pval = $("#name").val();
var datastring = 'pname'+pval;
$.post("unique_valid.php", {pname:pval }, function (data){
alert('duplicate');
});
return false;
});
});
Problem with this code is It shows alert box on every case but its not allowing to submit the form if the values is not exists in the database.
Php code :
$pname = $_POST['pname'];
if( $pname == $row['name']){
echo "success";
}else{
echo "failure";
}
Suggest the better solution for this problem.
That's because you're alerting 'duplicate' no matter what the PHP output is. Try checking the value of data before alerting, like this:
$(document).ready(function() {
$("#form_add").submit(function () {
var pval = $("#name").val();
var datastring = 'pname'+pval;
$.post("unique_valid.php", {pname:pval },
function (data){
if(data == 'failure'){
alert('duplicate');
}else{
alert('not a duplicate');
}
});
return false;
});
});
And I'm assuming your PHP code will actually be saving the record if it's not a duplicate (your code doesn't indicate as much, though)?