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.
Related
I am using the Jquery form plugin to submit a login form data. This works well but I have problem redirecting a successful logged in user to the client panel from the login page in my PHP script, that is whenever the user is logged in successfully, I redirect using header("location:panel.php") in my php script, this page is sent back to the login page as a response and it will be embedded in the login page instead of showing as a whole page.
jquery code;
$(document).ready(function(){
$("#loginform").ajaxForm({
target: '#responselogin'
}).submit();
});
php code;
<?php
$username=$_POST['username'];
$password=$_POST['password'];
if($username=="tarhe" && $password=="oweh") {
header("location:panel.php");
} else {
echo"login failed";
}
?>
Please I need help, thanks in advance
your using ajax, so your 301 location header will have no effect to the overall browser window. you will have to return a structured data to your javascript and have javascript redirect instead.
$(document).ready(function(){
$("#loginform").ajaxForm({
success: function (data) {
if (data == "login failed") {
$("#responselogin").html("Login Failed");
} else {
window.location.href = "panel.php";
}
}
).submit();
});
its actually better if you use json response for this. Since it's formatted better for browser consumption.
for handling this using json you can do the following. first change your php code to return a json response
$success = 0;
if($username=="tarhe" && $password=="oweh") {
$success = 1;
}
echo json_encode(array('success' => $success));
Then in your javascript code
$(document).ready(function(){
$("#loginform").ajaxForm({
type: 'json',
success: function (data) {
if (data.success == 0) {
$("#responselogin").html("Login Failed");
} else {
window.location.href = "panel.php";
}
}
).submit();
});
I don't think you can use the location flag inside the http header with ajax. Think about it: You submit a form with ajax, so you're getting the response back in Javascript, and not into the browser.
Bind a success handler to the .submit() form, and set window.location.href=http://your-url.com
You are using ajax so make a response data and on success redirect the user.
window.location.href = "somewhere.html";
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.
I'm using the jQuery validation plugin and the form uses ajax to submit the form. I have a floating button bar which generates the buttons for pages depending on what the page is used for. These buttons sit outside of the form tag. My form's id is account-settings. In my document.ready I have this:
$("#account-settings").validate({
rules: {
email: {email: true}
},
messages: {
email: {email: "Enter a valid email address."}
},
})
There's a button called savesettings which saves the settings for the form. Here's the click event:
$('#savesettings').click(function() {
if($('#account-settings').valid()){
alert("Valid form");
}
else{
alert("Not valid");
}
}
Nothing happens when I click the button... so, basically, I'm obviously not using the plugin right, somebody enlighten me? Keep reading over the documentation but I don't see anything else...
You will need to serialize the form upon the user clicking the button something like..
$('#savesettings').click(function() {
var $as = $('#account-settings');
if($as.valid()){
$.post(
/* your server page */
, $as.serialize()
, /* your callback function */
);
}
else{
alert("Not valid");
}
});
I should point out the obvious accessibility pitfall with submitting a form this way where users with no JavaScript will not be able to use it.
If you want to submit a form using any button outside of that form, you should use the trigger() function like so:
$('body').on('click', '#my-button', function(){
$('#account-settings').trigger('submit');
});
Your validation plugin should then act as normal.
Your JS function could use a closing paren. Try something like:
$('#savesettings').click(function() {
if($('#account-settings').valid()){
alert("Valid form");
} else {
alert("Not valid");
}
});
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 check the value enter in the form by user. i have applied validation and its working. The problem is that if user enter any form value incorrectly and then clicks submit, the whole page is refreshed and all input data is lost.
I want that validations is checked before passing it to server. One of my friends told me its possible with AJAX. Can anyone guide a beginner on how to do this?
You can use javascript instead and save the server from transferring some extra KBs and calculations by using Ajax (which technically is javascript but you send the request back to the server)
Jquery has a plugin called validation that will make your life easier though:
http://docs.jquery.com/Plugins/validation
There is a live demo in the link above
For example if you wanted to validate the username you could do this
<script>
$(document).ready(function(){
$("#commentForm").validate();
});
</script>
<form id="commentForm">
<input id="uname" name="name" class="required" />
</form>
yes you can use ajax or otherwise with your current approach you can use sessions to store user data and prevent it from being lost. with ajax you can show response from the server to show to the user.
$.ajax({
url: 'ajax_login.php',
type:'post'.
data:(/*data from form, like,*/ id: $('#username').val())
success: function( data ) {
if(data == 1) {
$('.feedback').html('data has been saved successfully');
//redirect to another page
}
else {
$('.feedback').html('data could not be saved');
$('.errors').html(data);
}
}
});
ajax_login.php would be something like
<?php
if(isset($_POST)) {
//do form validation if it is valid
if(form is valid) {
saveData();
echo 1;
}
else {
echo $errors;
}
}
?>
Do not need ajax.
Just set the onsubmit attribute of your form to "return checkfun();" and define checkfun some way like this:
function checkfun()
{
if ( all things were checked and no problem to submit)
return true;
else
{
alert('ERROR!');
return false;
}
}