jQuery validation , submit handler, and submit form - php

I am having some problems on executing the following code.
The code submits but it doesnt do anything, it comes back to the same screen, it seems that the values of the form have been not submited.
<script type="text/javascript">
$(document).ready(function(){
$("#signin_form").validate({
debug: false,
rules: {
///
},
messages: {
///
},
submitHandler: function(form) {
var result;
$.post('test.php', $('#signin_form').serialize(), function(data){
result = $.parseJSON(data);
if (result.flag == 'false'){
$('#results').show()
}
})
.success(function(data){
if (result.flag == 'true'){
form.submit();
}
}, 'json');
}
});
});
</script>
If I change the code to the following, it works and it takes me to the proper screen, but i need to validate, a captcha code, i am not sure if it is the right place to do it, i tried to use beforeSubmit but then the captcha is not validated.
<script type="text/javascript">
$(document).ready(function(){
$("#signin_form").validate({
debug: false,
rules: {
///
},
messages: {
///
},
submitHandler: function(form) {
form.submit();
}
});
});
</script>
There is something about the $.post that i dont underestand... and doesnt submit the information.
Does anyone know what it could be?
thanks!

You don't need to change how the form submits, in this case, for validating the captcha, use remote function from jquery.validate.
There are some problems around the remote usage with jquery.validate. Check if you did the following:
1) Make sure you are using jQuery version 1.6.1 and above only.
2) Use the "synchronous" option for remote execution (default being asynchronous) and to do this set async argument to false.
Example of usage:
Suppose this is my form...
HTML:
Add id and name attributes to all the form elements or just the captcha (this one must have both).
<form id="signin_form" action="save.php" method="POST">
Enter captcha: O1S2C3A4R
<br/>
<input type="text" id="captcha" name="captcha" value=""/>
<input type="submit" id="save" name="save" value="Save"/>
</form>
jQuery:
Add type, async and data arguments. This last argument passes the captcha value to check.php file and that's why that element needs the id attribute. Then you are able to use this selector $('#captcha').
(For me this is better but you can also call the element by name using other selector type)
Just to know, you need to also define an error message for the remote, in this case I used Invalid captcha.
$(document).ready(function(){
$("#signin_form").validate({
rules: {
captcha: {
required: true,
remote: {
url:"check.php",
type:"post",
async:false,
data: {
/* this is the name of the post parameter that PHP will use: $_POST['captcha'] */
captcha: function() {
return $.trim($("#captcha").val());
}
}
}
}
},
messages: {
captcha: {
required: "*",
remote: "Invalid captcha"
}
}
});
});
PHP: check.php
At this point it is important to use "true" or "false" as string to let know the jquery.validation plugin if the captcha is valid or not. In this case, if captcha is equals to O1S2C3A4R then is valid and, at client side, you will look that the submit will process the form to save.php file specified in the html form action attribute.
<?php
$captcha = $_POST['captcha'];
if($captcha == "O1S2C3A4R"){
echo "true";
} else {
echo "false";
}
?>
Doing this way, you can validate the whole form without problems and also check the captcha value remotely without altering plugin functionality.
Also you can test all this code together and look that it works :-)
Hope this helps.

Javascript:
<script type="text/javascript">
$(document).ready(function(){
$("#signin_form").validate({
rules: {
captcha: {
remote: {
url: "remote.php"
}
}
}
},
messages: {
captcha: {
remote: "Please enter the text in the captcha."
}
}
});
});
</script>
HTML form:
<form id="signin_form">
<input type="text" name="captcha">
<input type="submit">
</form>
PHP:
$response = $_GET['captcha'];
$answer = 'captcha_answer';
if($response==$answer){
echo 'true';
} else {
echo 'false';
}
Sorry for shoving this part into an answer -- I'm not allowed to comment:
Keep in mind that setting the 'async' parameter to false will lock up your page until you get a response, which might not be what you want. The validation library should block normal form submission if it's waiting on a response for remote validation, at least in newer versions (I'm using jQuery 1.7.2 and Validation 1.10.0).
IIRC the jQuery Validate library will treat anything other than the exact string "true" as being an error. This can be used to pass different custom messages depending on the reason for rejection. json_encode adds extra quotation marks that cause jQuery Validate to see it as a custom error message.

Related

check availability of the username using ajax and jquery in codeigniter

Here I am trying to check that username input is available for the user or not. I am doing it in codeigniter.
Here is my view page:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<style type="text/css">
.no{color:red;}
.yes{color:green;}
</style>
<script>
$(document).ready(function(){
// unique user name checking ------------- starts here----------------
$("#username").blur(function(){
var form_data= {
action : 'check_username',
username : $(this).val
};
$.ajax({
type: "POST",
url : "check_unique_username",
data : form_data,
success : function(result) {
$("#message").html(result.message);
alert(result);
}
});
});
// unique username checking -------------- ends here-----------------
});
</script>
</head>
<body>
<form class="RegistrationForm" id="RegistrationForm" method="POST" action="">
<label for="username">User Name</label>
<div>
<input id="username" name="username" size="25" class="required" />
</div>
<input type="button" id="button1" name="button1" value="check availability" />
<div id="message"></div>
</form>
</body>
here is my controller code :
<?php
class Registration extends MX_controller {
function index(){
$this->load->view('registrationPage'); // this will load the registration page.
}
function unique_username() {
$action = $_POST['action'];
if($action=='check_username'){
$u = $this->input->post('username');
$users=array("jhon","neo","margo","hacker","user123");
if(in_array($u,$user)) {
echo json_encode(array('message' => "It is not available!"));
}
else {
echo json_encode(array('message' => "It is available!"));
}
}
}
}
?>
But my code is not working, where I am getting wrong,please help me out..showing only it is available for every username
Edited : I have changed my controller code...
You have not used # while using the id of the div, so use:
$("#message").html(result);
instead of $("message").html(result);
EDIT: An updated answer to an updated question.
It's actually pretty stupid none of us could see it, but the problem is this string: username : $(this).val. The reason is that .val is not jQuery's method that get's the value of a text field, it should be username : $(this).val() (with brackets).
This covers the first JS part, the next problem is a typo, you have url : "check_unique_username",, but it should be url : "registration/unique_username", (didn't have controller name, and had unnecessary check_ prefix while in controller the method was without it).
Next typo is in PHP - if(in_array($u,$user)) {, but we have an array $users, so change this to if(in_array($u,$users)) {, so PHP would not throw a notice.
Next problem is the missing line dataType: 'json', in AJAX request. We must put it so that JS could know what data type we are receiving and parse it in a correct way.
After that it should work. But I have some suggestion for you. Change the PHP, so that it would return not strings, but a boolean value. For example - true, if it's available, false if it's not.
if(in_array($u,$users)) {
echo json_encode(array('message' => false));
} else {
echo json_encode(array('message' => true));
}
That way it would be easier to manipulate this data in your JS code. For example you could add this code to the success part of your AJAX request:
success : function(result) {
if(result.message) {
$("#message").html("It's available!");
$("#button1").removeAttr('disabled');
} else {
$("#message").html("It's not available!");
$("#button1").attr('disabled','disabled');
}
}
And you will have your submit button enabled/disabled. This will make sure a normal user would not be able to submit the form if he entered a username that is taken.
Also I would change the event blur to keyup, that way you will have faster updates, but it's a bit more heavy on the server. Problem with blur event is that your user could fill the username and click on the button anyway, because blur event fires only after the user leaves the element.
Hope this helps!

jquery validate with multiple submit buttons does not recognise second submit action

I am using the jquery validate plugin to validate and submit a form on my page which has multiple submit buttons to run different functions.
One submit button runs using the $post method while the other uses the standard action method.
(Please stick with me if my terminology is wrong)
The problem I am having is that if I submit the form using the first button, then try again using the second button, it trys to run the first action again on the second submit.
Here's my code which will hopefully make things clearer...
<form id="myForm" action="add.php">
<input type="submit" id="myfunction" />
<input type="submit"​ id="add" />
​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​<input type="text" name="myvalue" />
</form>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
and my validate code...
$("#myForm input[type=submit]").click(function(e) {
if (e.target.id == 'myfunction') {
$("#myForm").validate({
submitHandler: function(form) {
$.post('myfunctionpage.php', $("#myForm").serialize(), function(data) { });
}
});
} else if (e.target.id == 'add') {
$("#myForm").validate({
rules: {
name: {
required: true,
}
}
});
}
});​
Why don't you seaprate the code into two segments?
$("#myfunction").click(function(e) {
$("#myForm").validate({
submitHandler: function(form) {
$.post('myfunctionpage.php', $("#myForm").serialize(), function(data) { });
}
});
}
$("#add").click(function(e) {
$("#myForm").validate({
rules: {
name: {
required: true
}
}
});
}
You need to stop the form submission in the $.post case. Try returning false from the click event handler, that should stop the event from bubbling to the form and causing it to submit.
Personally I hook into the submit event on the form element instead of click events on the buttons. The reason is that many users submit forms by placing the cursor in a text box and then pressing enter. No click event ever occurs and your code is bypassed...
also, its been a while since i used the validate plugin, but i think you're using it wrong calling validate() after a form has been submitted. check the docs for proper use.
Just in case someone is looking for that.
Simple after the first submit use $("#myForm").validate().destroy(); in order to clear "form data".
https://jqueryvalidation.org/Validator.destroy/

Ajax form , PHP process and return errors if there's any , if not success

I found a tutorial here : http://tutorialzine.com/2009/08/creating-a-facebook-like-registration-form-with-jquery/ (please take a look)
It's a nice tutorial, I followed everything there and remove extra stuff I don't want , like the functions.php with generate_function option as I am not in need of birthday etc. stuff.
All I want is a NAME(usrname) , EMAIL(email) , Password(password) , when the user click on "REGISTER" button (which is the form submit button), the script I got from the tutorial will send the data over to "regprocess.php" which contains validation check codes like checking if the submitted form data is empty.
But when I click REGISTER , the data is not sent back (the error message) from the "regprocess.php" nor the success message.
When i check with my firebug , the JSON response is showing the full php code like the one below(scroll down).
Here's my code :
HTML-
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>
<script type="text/javascript" src="register.js"></script>
<form id="regForm" action="regprocess.php" method="post">
<label for="usrname">Name:</label>
<input id="usrname" name="usrname" type="text" value="" class="nor">
<label for="email">Email:</label>
<input id="email" name="email" type="text" value="" class="nor">
<label for="password">Password:</label>
<input id="password" name="password" type="password" value="" class="nor">
<table><tr><td style="width:290px;"><div id="error"> </div></td><td><input name="register" type="submit" value="Register" id="regbtn"><center><img id="loading" src="images/load.gif" alt="Registering..." /></center></td></tr></table>
</form>
Okay the Ajax script is in "register.js" above.
Ajax script(register.js)-
$(document).ready(function(){
$('#regForm').submit(function(e) {
register();
e.preventDefault();
});
});
function register()
{
hideshow('loading',1);
hideshow('regbtn',0);
error(0);
$.ajax({
type: "POST",
url: "regprocess.php",
data: $('#regForm').serialize(),
dataType: "json",
success: function(msg){
if(parseInt(msg.status)==1)
{
window.location=msg.txt;
}
else if(parseInt(msg.status)==0)
{
error(1,msg.txt);
}
hideshow('loading',0);
hideshow('regbtn',1);
}
});
}
function hideshow(el,act)
{
if(act) $('#'+el).css('visibility','visible');
else $('#'+el).css('visibility','hidden');
}
function error(act,txt)
{
hideshow('error',act);
if(txt) $('#error').html(txt);
}
CSS:
Regbtn is the submit button , it's visibility is set to visible
loading is set to hidden
error is set to hidden
When a user click on Regbtn , loading visibility will become visible while Regbtn hides(visibility:hidden).
It's done in the Ajax script(register.js).
Okay now the php:
PHP(regprocess.php)-
if(empty($_POST['usrname']) || empty($_POST['email']) || empty($_POST['password']))
{
die('{status:0,"txt":"Fill in All Fields"}');
}
if(!(preg_match("/^[\.A-z0-9_\-\+]+[#][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/", $_POST['email'])))
die('{status:0,"txt":"Please Provide a Valid Email"}');
echo '{status:1,txt:"registered.html"}';
This checks whether the username , email and password data is empty , if yes , returns a message which will be displayed in the Error(#error in html) , it also checks whether email provided is valid.
If everything else is right , user will be directed to registered.html
But i think the script can't get the error message back from the php.
I hope someone can help me. Thanks.
Have a nice day.
hmm not too much of an answer but what I do on my forms is a I submit via ajax and put the result from the php page in the parent of the form.
below is the plugin in code. it works when the form is a child of a div by default.
(function($){
$.fn.extend({
//pass the options variable to the function
ajaxForm: function(options)
{
//Set the default values, use comma to separate the settings, example:
var defaults =
{
target: 'div'
}
var options = $.extend(defaults, options);
return this.each(function()
{
var o=options
$(this).submit(function(event)
{
event.preventDefault();//stop from submiting
//set needed variables
var $form = $(this)
var $div = $form.parent(o.target)
$url = $form.attr("action");
//submit via post and put results in div
$.post( $url, $form.serialize() , function(data)
{ $div.html(data) })
})
});
}
});
})(jQuery);
note this will run for every form so change it as you would wish.
whatever you want to display just echo on the php page. also this is made for post and the php page will access anything just like any other form being with post.
also it wouldn't be hard to modify if you felt necessary to send as json instead.
You need to put php tags around the php code, like this:
<?php
if(empty($_POST['usrname']) || empty($_POST['email']) || empty($_POST['password']))
{
die('{status:0,"txt":"Fill in All Fields"}');
}
if(!(preg_match("/^[\.A-z0-9_\-\+]+[#][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/", $_POST['email'])))
die('{status:0,"txt":"Please Provide a Valid Email"}');
echo '{status:1,txt:"registered.html"}';
?>

is the browser or server ignoring the code?

i made this form:
<form id="form" name="msgform" method="" action="">
<input type="text" size="40" id="msg" name="message"/>
<input type="submit" id="button" name="clicker" value="click" />
</form>
and this jquery script:
$(document).ready(function(){
$("#button").click(function(){
$("#form).submit(function(){
var submision= $("#form).val();
$.post("txt/process.php", submision, function(data){
alert(data);
});
});
});
});
and this is the process.php file:
<?php
echo $_POST['message'] . "";
?>
now when i click the button the form is submited, but it sends it using the GET method because i can see it in the adress bar, but it never gets sent to the php file, and i checked to see if the names are correct and if i specify the POST method it still doesnt go to the php file.
is the server or browser ignoring the code? or am i doing the whole thing wrong?
thanks
Please find the following code, it works and please go through with the documentation, it will tell you that what the mistake was being done.
$(document).ready(function(){
$("#button").click(function(){
$("#form").submit(function(){
/* var submision= $("#form).val();
THIS DOESN'T WORK TO GET ALL OF THE ELEMENTS IN
FORMAT TO PASS TO $.post EVENT,
We can do this as I did in following example
*/
$.post("txt/process.php", { msg: $("#msg").val() }, function(data){
alert(data);
});
/* Also you didn't put return false statement just at the end
of submit event which stops propagating this event further.
so it doesn't get submitted as usually it can be without ajax,
So this stops sending the form elements in url. This was because
by default if you define nothing in method property for form
then it consider it as GET method.
*/
return false;
});
});
});
Let me know please you are facing any issue.
You don't need to register the submit event for the form inside the click handler of the button. As it is a submit button it will automatically try to submit the form for which you register the corresponding handler:
$(function() {
$('#form').submit(function() {
// Get all the values from the inputs
var formValues = $(this).serialize();
$.post('txt/process.php', formValues, function(data) {
alert(data);
});
// Cancel the default submit
return false;
});
});
$("#form).submit(function(){
see if this selector is missing a "
$("#form").submit(function(){

JQuery and PHP validation problem?

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.

Categories