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!
Related
I have a page finduser.php which is accessed by clicking a button on another page user.php. user.php is a simple form that takes a couple of parameters from an end user, submits to finduser.php which appends that user to a list.
user.php
<form action="finduser.php" method="post">
<input type="text" name="username" required="required"/>
<input type="submit" value="Find User"/>
</form>
finduser.php
<?php
//session start is on another page included on every page
$theUser = $_POST["username"];
if (!isset($_SESSION["users"])) {
$_SESSION["users"] = array();
} else {
$_SESSION["users"][] .= $theUser;
}
?>
The way the UX handles is that you begin on user.php, submit form and are navigated to finduser.php, but if you want to keep searching for users, you need to press back and resubmit the form. I'd like a way to not redirect on form submit, but still execute the code on finduser.php.
I notice some sites use a similar concept for adding items to a cart. Some sites redirect you to the cart on adding something, but some stay on the same page without disrupting UX. A little box might appear "x has been added to cart", which lets you add multiple things from the same page to cart but without seeing the cart between.
How can I accomplish this? To reiterate what I'm trying to do:
user types a name in user.php
user presses submit, the PHP in finduser.php is executed
perhaps a box appears "[name] has been added to the list"
there are no page redirects
I could do something like the below:
user.php
<?php
//session start is on another page included on every page
if ((sizeof($_POST) == 1) && isset($_POST["username"])) {
$theUser = $_POST["username"];
if (!isset($_SESSION["users"])) {
$_SESSION["users"] = array();
} else {
$_SESSION["users"][] .= $theUser;
}
}
<form action="user.php" method="post">
<input type="text" name="username" required="required"/>
<input type="submit" value="Find User"/>
</form>
?>
This way only one page is needed, but it still needs to redirect (to itself), and is prone to disruption when someone refreshes the page for example.
You need to use AJAX to process your PHP code and return the result. Here's an option using jQuery's AJAX handler:
# File: yourform.html
<form action="finduser.php" id="findUserForm" method="post">
<input type="text" name="username" required="required"/>
<input type="submit" value="Find User"/>
<div class="messages"></div>
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#findUserForm').submit(function(e) {
// Stop the regular post action
e.preventDefault();
var $form = $(this);
// Define the request that should happen instead
$.ajax({
url: $form.attr('action'),
method: $form.attr('method'),
dataType: 'json',
data: {
username: $('input[name="username"]').val()
}
}).done(function(result) {
// Append the results to the messages div
$('.messages').append('<p>' + result.message + '</p>');
});
});
});
</script>
Then your backend script to process the username:
# File: finduser.php
<?php
session_start();
if (isset($_POST['username'])) {
// do your processing...
if (empty($_SESSION['users'])) {
$_SESSION['users'] = [];
}
// Add it to the array
$_SESSION['users'][] = trim($_POST['username']);
// do more processing?
// Return a result
echo json_encode(
'success' => true,
'message' => $_POST['username'] . ' was successfully added!'
);
exit;
}
// Handle errors!
echo json_encode(
'success' => false,
'message' => 'No username was posted.'
);
I haven't tested this, but the idea is that you tell jQuery to override the default way it handles that form being submitted, and instead it should send the username via AJAX to finduser.php. That script will do things that you tell it to, add the user to the session array, then output a JSON result message. jQuery's .done() event then processes that result message and adds the message to the .messages div.
You can use the success => bool option to control how the messages might display, for example:
.done(function(result) {
var $elem = $('<p></p>');
// Add a CSS class for display
if (result.success) {
$elem.addClass('success');
} else {
$elem.addClass('error');
}
// Append the results to the messages div
$elem
.html(result.message)
.appendTo($('.messages'));
});
Then add some CSS like so:
.success {
color: green;
}
.error {
color: red;
}
In theory, your result messages should then be colour coded.
I cannot for the life of me figure out what is going on here. I'll open a different browser to check if what I changed works, and maybe my other browser cached something, and it will work! But then I do it again and it doesn't seem to. I'm going crazy.
On my website, syllableapp.com, I created a MySQL database I could connect to. I made a PHP script that connects to it, adds a simple entry to it, and is done. It's called register_email.php, and it's available to access here. Accessing it manually via that URL will add the entry. Its code is as follows:
<?php
$db = new mysqli("localhost", "username", "password", "table");
if ($db->connect_error) {
echo "Could not connect to database.";
exit;
}
else {
$db->query("INSERT INTO emails (email) VALUES ('weird')");
echo 1;
}
?>
If I check, it gets added.
However, I want it to be added from a form. I have an HTML file at http://syllableapp.com/test/index.html that looks like this:
<html>
<head>
<title>Syllable - iPhone Speed Reader</title>
<link rel="stylesheet" href="styles/style.css">
<script type="text/javascript" src="scripts/jquery-1.8.1.min.js"></script>
<script type="text/javascript" src="scripts/scripts.js"></script>
<script type="text/javascript" src="scripts/jquery-ui-1.8.23.min.js"></script>
</head>
<body>
<div class="content">
<img src="images/app-icon.png" alt="App icon">
<h1>Syllable</h1>
<p>Speed reading app for iPhone. Devour all your Instapaper and Pocket articles, and learn to read much faster in the process.</p>
<form method="post" action="">
<input type="email" class="email" placeholder="Email me when it's live">
<input type="submit" class="submit" value="Send">
</form>
</div>
</body>
</html>
So when the user submits the form, the JavaScript file I linked to at the top intercepts the submit button press, and calls an AJAX function to submit it to the PHP form. The jQuery for that looks like:
$(document).ready(function() {
$('input[type="submit"]').click(function() {
var email = $.trim($('.email').val());
var emailRegEx = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (email == "" || !emailRegEx.test(email)) {
event.preventDefault();
$(this).effect("shake", { times:2 }, 75);
}
else {
$.ajax({
type: "POST",
url: "http://syllableapp.com/test/register_email.php",
data: { "message": "hi" },
success: function(data) {
alert("success");
},
error: function(jqXHR, textStatus, errorThrown) {
alert("failure");
}
});
}
});
});
Which basically just checks if it's a valid email address, then if so, calls the PHP file.
However, every time I click submit, it says failure. Why on earth is this happening? Why can I access it directly, but it won't let me use AJAX?
Just a guess, but in your AJAX block change the URL line to this:
url: "register_email.php",
Also, as a test,
(1) change your alert command in the AJAX success function to:
alert(data);
and (2) insert this line immediately following the <?php directive in the file "register_email.php":
die('Made it to here');
A few things:
1) You're form needs an action or else it's not proper HTML. You can set it to a value like "#"
2) When you click the submit button, you want the form submitted using custom ajax, and not through the standard way. Your ajax handler for the click event should be something like:
$('input[type="submit"]').click(function(event) {
event.preventDefault();
//...
});
You have event.preventDefault in your code, but the event variable isn't being passed to the function. And I think you want event.preventDefault called every time, not just in the case of input validation failure.
3) Instead of using alerts, try using console.log and monitoring your javascript console to see if you get any errors. Add those errors to your question to help us with your issue.
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.
I'm just a PHP starter and now I want to learn JQUERY, on my learning process I practice on validating inputs usually I validate my inputs using a pure PHP code only and every time I validate the inputs the page reloads and now I want to improve in doing things I found some articles like http://api.jquery.com/jQuery.ajax/, http://api.jquery.com/jQuery.post/ (can't post other links) but I am more confused because they have different approach and I want to use the approach from the JQUERY tutorial but I haven't found any good tutorials and there is no tutorials on JQUERY's site that is using a database, usually I code like this:
<form method="post">
<label for="Username">Username:</label>
<input id="Username" type="text" name="username">
<?php
session_start();
if(isset($_SESSION['msg'])){
$msg=$_SESSION['msg'];
echo '<label for="Username">'.$msg.'</label>';
?>
<input type="submit" name="reg">
</form>
<?php
if(isset($_POST['reg'])){
$result=//check username from database here
if($result){
$_SESSION['msg']='username not available.';
}
else {
$_SESSION['msg']='username available.';
}
}
?>
Now I want to learn how can I validate inputs directly from the database without reloading the page? I don't know where should I start, what to add in my code. Any help, advice or suggestions will be really a big help for me :)
first, in your form add a onSubmit function
<form name='myform' type='POST' action='http://www.action.fr' onSubmit="return check_form()">
you can do this in ajax like that
function check_form()
{
var user = $('#Username').val(); // Username is the id of your input
var password = $('#password').val(); // password is the id of your input
$.ajax(
{
type:"POST", // or get as you want
url:"myfile.php", // it is the php file which can do the job
data: "user="+user+"&password="+password, // the param to send to your file,
success:function(msg)
{
;// msg is the result of your 'myfile.php', everything you write is in the msg var
}
});
}
in your php file you can get your data like this :
$user = $_POST['user'];
$password = $_POST['password'];
// if your type is get then use $_GET instead of $_POST
tell me if you have any problem with my code.
Write your validation script as though you're expecting a page refresh. Instead of outputting error messages, put them in a JSON array and print the JSON data. Then call the script from the AJAX function. It's really that simple.
<?php
// validate.php
$sampleInput_number = isset($_POST['sampleInput_number']) ? $_POST['sampleInput_number'] : "";
$errors = array();
if (trim($sampleInput_number) == "" || !is_numeric(trim($sampleInput_number)) {
$errors[] = "SampleInput_number must be a number!";
}
// sample input must also match a value from the database
if (!matchesDBValue($sampleInput_number)) {
$errors[] = "SampleInput_number must match a value from the database!";
}
function matchesDBValue($value) {
$retval = false;
// compare to db values here...
return $retval;
}
echo json_encode($errors);
Your form would look something like this:
<form action="" method="post" id="theForm">
<input type="text" name="sampleInput_number" id="sampleInput_number" />
<input type="button" id="formSubmit" value="Submit" />
</form>
And your javascript would look like this:
<script language="javascript" type="text/javascript">
$(#formSubmit).on("click", function() {
$.post("validate.php",
{
sampleInput_number: $("#sampleInput_number").val()
}, function(data) {
// check returned json data
// perform action based on results
if (no_errors) {
$("#theForm").submit();
}
}, "json"
);
});
</script>
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"}';
?>