How do I use the livevalidation javascript library custom.validation function? - php

(note: my original question was not linked to my openid - I am reposting here to be able to edit/update/respond accordingly - if anyone with access could remove the original question: /questions/1554916/how-to-use-the-livevalidation-javascript-library-custom-validate-function that woudl be great !!)
Heya Folks,
I am very new to all of this so please bear with me!
I have mangaged to create a form with livevalidation checking of fields, and also with an ajax/json check to see if a usename is valid. I seem to get along fine with standard live validation.
Here is a demo of what I have at the moment: link text
The method to give a responce to the ajax username check simply changes a with a message in to make it visable, so I want to use a livevalidation check to manage the ajax responce - so I can link them together (check for blank, then in use, then invalid, then pass as ok) and have my responses output the same way.
I currently have this form code:
<?php
$script = "
$('uname').addEvent('blur', function(e) {
e = new Event(e).stop();
// Show the spinning indicator when pressing the submit button...
$('indicator1').setStyle('display', 'block');
var username = $('uname').value;
if ( username != '' ) {
var url = 'index.php?option=com_chronocontact&chronoformname=custom_livevalidation_test&task=extra&format=raw';
var jSonRequest = new Json.Remote(url, {
onComplete: function(r) {
$('indicator1').setStyle('display','none');
if ( r.username_ok ) {
$('username_msg').setHTML(\"<span style='color:green;'>Username '\"+username+\"' is OK</span>\");
} else {
$('username_msg').setHTML(\"<span style='color:red;'>Sorry, username '\"+username+\"' is already taken</span>\");
}
}
}).send({'username': username});
}
});
";
global $mainframe;
if ($mainframe->isSite())
{
$doc =& JFactory::getDocument();
$script = "
window.addEvent('domready', function() {
$script
});
";
$doc->addScriptDeclaration($script);
};
$script = "
var uname = new LiveValidation('uname', {
validMessage: 'This is a valid username',
wait: 500
});
uname.add(Validate.Presence, {
failureMessage: 'Username must not be blank!'
});
uname.add(Validate.Format, {
pattern: /^[a-zA-Z\-_]{4,16}$/,
failureMessage: 'Username must be between 4 and 16 characters'
});
";
global $mainframe;
if ($mainframe->isSite())
{
$doc =& JFactory::getDocument();
$script = "
window.addEvent('domready', function() {
$script
});
";
$doc->addScriptDeclaration($script);
};
?>
<div>
<span class="cf_label">Username: </span>
<input style="" id="uname" name="uname" class="" title="" value="" type="text">
<span id="indicator1" style="display: none"><img src="/images/hourglass.gif" alt="checking..." /></span>
<div id='username_msg'></div>
</div>
<br />
<input type='submit' name='submit' value='submit' />
With this being the json part that runs in the background:
<?php
$json = stripslashes($_POST['json']);
$json = json_decode($json);
if ( $json->username ){
$db =& JFactory::getDBO();
$query = "
SELECT COUNT(*)
FROM `jos_users`
WHERE `username` = ".$db->quote($json->username).";";
$db->setQuery($query);
$response = (bool) !$database->loadResult();
$response = array('username_ok' => $response );
echo json_encode($response);
}
?>
So looking at the livevalidation documentation, you can use a custom validation in this fashion:
// Pass a function that checks if a number is divisible by one that you pass it in args object
// In this case, 5 is passed, so should return true and validation will pass
Validate.Custom( 55, { against: function(value,args){ return !(value % args.divisibleBy) }, args: {divisibleBy: 5} } );
I am finding this to be very cryptic - I would think I should be able to point to 'function(r)' thats all ready there - but I doubt I am doing it the right way,
Can anyone shed any light, I am (hoping!) to understand it as well as uncover a solution!!
* Updates *
I am now led to believe that this code for the validate.custom part should work:
var uname = new LiveValidation('uname', {
validMessage: 'This is a valid username',
wait: 500
});
uname.add(Validate.Presence, {
failureMessage: 'Username must not be blank!'
});
uname.add(Validate.Custom('uname', { against: function(r){
return !(r.username_ok) }, args: {} } ),
failureMessage: 'This username is already taken'
});
uname.add(Validate.Format, {
pattern: /^[a-zA-Z\-_]{4,16}$/,
failureMessage: 'Username must be between 4 and 16 characters'
});
";
However it seems that I have an architecture issue - live validation wants an instant answer, and ajax takes place in the background. I have had a suggestion to investigate the 'observer pattern' thats an entirely new concept to me - I am usually playing with the graphical design and structure side of a cms!
Any further help / clarification appreciated as I will have to come back to this and get it working!!

try the code sample in the following link. It worked for me. The key is to write the logic in a separate JavaScript function and call it with the Validate.Custom function.
http://www.experts-exchange.com/codeSnippetPopup.jsp?csid=259114
Edit: Added code from the link:
//input Form
<form action="#" method="post">
<label for="ip">IP:</label>
<input type="text" name="ip" id="ip"/>
<br/>
<label for="ip">Case:</label>
<input type="text" name="ticket" id="ticket"/>
<br/>
<input type="submit" value="Submit" name="submit" onclick="checkInput()"/>
</form>
/// JS function
function checkInput() {
var ip = new LiveValidation('ip', {onlyOnSubmit: true } );
ip.add( Validate.Presence );
ip.add( Validate.Custom, { against: function(value){ return isValidIPAddress(value) }, failureMessage: "IP is not valid" } );
var ticket = new LiveValidation('ticket', {onlyOnSubmit: true } );
ticket.add( Validate.Presence );
ticket.add( Validate.Custom, { against: function(value){ return Case(value) }, failureMessage: "Case is not valid" } );
var ipSubmit = ip.form.onsubmit;
var ticketSubmit = ticket.form.onsubmit;
ip.form.onsubmit = function(){
var validIP = ipSubmit();
var validCase = ticketSubmit();
if((validIP)& (validCase))
getActionBack('0');
return false;
}
}

Here's another example that works.
f1.add(
Validate.Custom,
{
against: function (value, args) { return isValidCreditCard(value, args.cardType) },
args: { cardType: "Visa" },
failureMessage: "Credit Card number is not valid"
}
);
The weird part is...
against: function (value, args) { return isValidCreditCard(value, args.cardType) }
...which has my isValidCreditCard function nested inside the 'against' function. The against function just returns what my isValidCreditCard function returned.
You can put the actual function there instead just like the cryptic example, but anything more than a line would probably be quite confusing. (Why use % [modulus] in the example? No one knows that operator!)

Related

Server side scripting onkeyup PHP

i am trying to make an search box which search the name from elastic search database, but when i run the it always give me an error that ----
Notice: Undefined index: value in the line --> $query = $_GET['search_keyword'];
but from my script i believe it should get the "search_keyword".
Search box --
<form method="GET" action="/latest/helloTestData">
<input type="text" name="sample_search" id="sample_search" onkeyup="search_func(this.value);">
</form>
Script --
<script>
$(function () {
var minlength = 3;
$("#sample_search").keyup(function () {
var that = this,
value = $(this).val();
if (value.length >= minlength ) {
$.ajax({
type: "GET",
url: "/latest/helloTestData", // address to the php function
data: {
'search_keyword' : value
},
dataType: "text",
success: function(msg){
//we need to check if the value is the same
if (value==$(that).val()) {
//Receiving the result of search here
}
}
});
}
});
});
</script>
PHP ---
public function helloTestDataAction() {
$paramss = array('hosts' => array('localhost:9200'));
$client = new Elasticsearch\Client($paramss);
$query = $_GET['search_keyword'];
if ($query != "") {
$params = array();
$params['size'] = 1000000000;
$params['index'] = 'myindex';
$params['type'] = 'mytype';
$params['body']['query']['bool']['must'] = array(
array('match' => array('name' => $query)), // search data by input data
);
$esresult = $client->search($params);
if ($esresult < 1) {
echo "Your search did not match any documents. Please try different keywords.";
} else {
echo $esresult; //results found here and display them
}
}
return new Response('ok');
}
Can anyone knows how to fix this problem. Thanks a lot in advanced.
Modifiy $_GET['value'] into $_GET['search_keyword']
So
public function helloTestDataAction() {
[...]
$_GET['search_keyword'];
[...]
}
You're searching for a key that will not be into $_GET array, as, into your ajax request, you're passing a key named search_keyword and so this is the error
Simply replace
$_GET['value'] to $_GET['search_keyword']
Quick and simple! The front-end pass the typed text via GET by url.
In this test I put the 2 files in the same folder. Change as you need.
Front-end:
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div id="my_header" style="background-color:lightblue">
</div>
<input type="text" id="foo" value="bar" onkeyup="loadlink(this)" />
<script>
function loadlink(e){
$('#my_header').load('back.php?var='+e.value,function () {
$(this).unwrap();
});
}
</script>
Back-end (back.php):
<?php
echo "received: " . $_GET["var"] . ' <br>at ' . gmdate('Y-m-d h:i:s \G\M\T', time());
?>

php - codeigniter ajax form validation

Hi I’m quite new to jquery -ajax and I’d like some help please to join it with CI.
I have followed this tutorial on Submitting a Form with AJAX and I’d like to add this functionality to my CodeIgniter site. What I’d like to do is when the user submits the form, if there are any validation errors to show the individually on each input field (as in native ci process), or if this is not possible via validation_errors() function. If no errors occured to display a success message above the form.
Here's my code so far:
my view
// If validation succeeds then show a message like this, else show errors individually or in validation_errors() in a list
<div class="alert alert-success">Success!</div>
<?php echo validation_errors(); //show all errors that ajax returns here if not individualy ?>
<?php echo form_open('admin/product/add, array('class' => 'ajax-form')); ?>
<p>
<label for="product_name">Product *</label>
<input type="text" name="product_name" value="<?php echo set_value('product_name', $prod->product_name); ?>" />
<?php echo form_error('product_name'); ?>
</p>
<p>
<label for="brand">Brand</label>
<input type="text" name="brand" value="<?php echo set_value('brand', $prod->brand); ?>" />
<?php echo form_error('brand'); ?>
</p>
...
my controller
public function add($id){
// set validation rules in CI native
$rules = $this->product_model->rules;
$this->form_validation->set_rules($rules);
if ($this->form_validation->run() === true) {
// get post data and store them in db
$data = $this->input_posts(array('product_name', 'brand', 'category_id', 'description'));
$this->product_model->save($data, $id);
// no errors - data stored - inform the user with display success-div
} else {
// validation failed - inform the user by showing the errors
}
//load the view
$this->load->view('admin/products/add', $data);
}
and here’s the js script
$(document).ready(function () {
$('form.ajax-form').on('submit', function() {
var obj = $(this), // (*) references the current object/form each time
url = obj.attr('action'),
method = obj.attr('method'),
data = {};
obj.find('[name]').each(function(index, value) {
// console.log(value);
var obj = $(this),
name = obj.attr('name'),
value = obj.val();
data[name] = value;
});
$.ajax({
// see the (*)
url: url,
type: method,
data: data,
success: function(response) {
console.log(response); // how to output success or the errors instead??
}
});
return false; //disable refresh
});
});
How should I pass my validation results (either success or the post errors) throught the ajax request and display them on my view??
From some little research I did I've found that you can use a single controller, that holds both the native proccess and the ajax request (instead of using 2 controllers), but my main difficulty is, I don't understand how the results of the validation will pass through the js script and display them on my view?? Please note that I don't want to display anything on an alert box, instead show the results on a div or the errors individualy(if possible).
EDIT I did some changes to my application, here's the code so far:
the controller
public function manage($id = NULL){
$this->load->library('form_validation');
$data['categ'] = $this->category_model->with_parents();
//fetch a single product or create(initialize inputs empty) a new one
if (isset($id) === true) {
$data['prod'] = $this->product_model->get($id);
$data['attr'] = $this->attribute_model->get_by('product_id', $id, null, true);
} else {
$data['prod'] = $this->product_model->make_new();
$data['attr'] = $this->attribute_model_model->make_new();
}
if (isset($_POST['general_settings'])) {
if ($this->form_validation->run('product_rules') === true) {
// get post inputs and store them in database
$data = $this->product_model->input_posts(array('product_name', 'brand', 'category_id', 'general_description'));
$this->product_model->save($data, $id);
$status = true;
} else {
// validation failed
$status = validation_errors();
}
if ( $this->input->is_ajax_request() ) {
echo json_encode($status);
exit;
}
redirect('admin/product');
}
//if (isset($_POST['attributes_settings'])) { the same thing here }
// load the view
$this->load->view('admin/products/manage', $data);
}
and the js
success: function(response) {
//console.log(response);
if (data.status === true) {
$('#ajaxResults').addClass('alert alert-success').html(response);
} else {
$('#ajaxResults').addClass('alert alert-error').html(response);
};
}
But I'm having some issues
Although I get the error messages from validation_errors() as an alert-error when there are no errors I get the true in an alert-error too, insted of alert-success.
2.how should I return the success message too? eg. a message saying "Saves were done!".
Althought in a non-ajax-request the data are stored in the database, in case fo ajax the don't store. Any ideas What may be wrong???
HTML:
<div id="ajaxResults"></div>
Javascript ajax:
success: function(response) {
$('#ajaxResults').text(response);
}
this script you've wrote is only if the validation succeeds, right?
Wrong. The code in "success" gets executed any time you get a response back from the server (assuming the HTTP header is 200). Does your javascript knows if the server has any error for you? No.
You need your JavaScript to recognize if the validation failed or succeeded. You have many ways to do that. One of these could be sending the message to display followed by a 0 or 1.
So your PHP will looks like:
return "0 " . $errorMessage;
and
return "1 " . $successMessage;
and your javascript should then recognize, with if statement and substring, if the message starts with 0 or with 1.
Use this way i hope this will work for you
<script type='text/javascript'>
var base_url = '<?=base_url()?>';
function ajax_call()
{
var ids = $("#all_users").val();
$.ajax({
type:"POST",
url: base_url+"expense/home/get_expense",
data: "userid=" + ids,
success: function(result){
$("#your_div_id").html(result);
}
});
}
</script>

PHP - How to Post Form Data to a URL, Wait for a Response & Then Do Something

I'm going to give a basic example of what I need to be able to do, in the hopes that somebody can point me in the right direction, although I'm sure what I'm asking somebody is going to facepalm themselves when they read it. Anyway, here goes.
I have a form on a page on Site Y (let's call it form.php), that form looks like this (asks for just a username & password):
<form action="http://SiteX.com/validate.php" method="post">
Email Address: <input type="text" name="email">
Password: <input type="password" name="password">
<input type="submit">
</form>
As you can see, the form is hosted on Site Y, and is submitting the information to a page on Site X.
validate.php on Site X checks the submitted login details from Site Y and returns whether or not the login details are valid, sort of like this (obviously something more complex than this):
$SubmittedEmail = $_POST['email'];
$SubmittedPassword = $_POST['password'];
$CrossReferenceEmail = 'someemail#dontcare.com';
$CrossReferencePassword = 'apassword';
if ( ($SubmittedEmail == $CrossReferenceEmail) && ($SubmittedPassword == $CrossReferencePassword) ) {
echo 'Valid';
} else {
echo 'Not Valid'; }
What I need to do, that I don't know how to do, is how do I make "form.php" wait for a reply (whether the login details are valid or not) and then do something based on that reply?
<form id="Form" action="http://SiteX.com/validate.php" method="post">
Email Address: <input type="text" name="email">
Password: <input type="password" name="password">
<input type="submit">
</form>
$("#Form").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
e = $form.find( 'input[name="email"]' ).val(),
p = $form.find( 'input[name="password"]' ).val(),
url = $form.attr( 'action' );
/* Send the data using post */
var posting = $.post( url, { email: e,password:p } );
/* Put the results in a div */
posting.done(function( data ) {
if(data=='valid')
alert('login successful');
elseif(data=='Not Valid')
alert('login not successful');
});
});
very basic and simple way is using httpRequest by java script and get returned value from site X and if match submit data to any php file in site Y. if you like to know I can send an example to help you.
this way is more user friendly but need client side process.
other way is use get content function.
other way:
you can use get.php file on site Y and submit data to get.php .
in get.php file use the file_get_content function and submit username data by get method ( add to the end of url like example )
then check the returned value ( true or false )
example :
$SubmittedEmail = $_POST['email'];
$SubmittedPassword = $_POST['password'];
$homepage = file_get_contents("http://www.example.com/x.php?email=SubmittedEmail &password=$SubmittedPassword&...[other parameters]");
on www.x.com/x.php
you can get email and password by get method
and echo the result.
returnet value in $hompage is the result of x.php file on site x (true or false or any thing you echo on site x file x.php)
on site x.com/x.php do like this to get data and return result to y site:
$SubmittedEmail = $_GET['email'];
$SubmittedPassword = $_GET['password'];
if ( ($SubmittedEmail == $CrossReferenceEmail) && ($SubmittedPassword == $CrossReferencePassword) ) {
echo 'true';
} else {
echo 'false'; }
more help on:
http://php.net/manual/en/function.file-get-contents.php
this way... you CAN'T as soon as the form is transmitted, the url will be set to "validate.php" so the original form.php and it's code is not available anymore.
What you could do is change the formtransmission to a ajax-javascript, that'll wait for the response from validate.php without closing form.php... you could then do whatever you need to do with it.
(what's that got to do with curl?)
[edit]
Add this javascript to the form.php html output
function validate()
{
var e = $('email').value;
var p = $('password').value; //jQuery is easier to type
// the same as
// var p = document.getElementById('password').value;
var req = new Request({
url: '/validate.php?',
method: 'post',
data: {'email' : e, 'password' : p},
onComplete: function(response)
{
if (response == "Valid" )
{
//do what you want on success
}
else
{
// do what you want on unsuccessful login
}
}
}).send();
}
now edit the form (just the first line)
<form onsubmit="validate();" method="post">
that should do

strange behavior while including a class in php

I'm experiencing a strange behavior with PHP. Basically I want to require a class within a PHP script. I know it is straight forward and I did it before but when I do so, it change the behavior of my jquery (1.8.3) ajax response. I'm running a wamp setup and my PHP version is 5.4.6.
Here is a sample as for my index.html
head (omitting the jquery js include)
<script>
$(document).ready(function(){
$('#submit').click(function(){
var action = $('#form').attr('action');
var form_data = {
fname: $('#fname').val(),
lname: $('#lname').val(),
phone: $('#phone').val(),
email: $('#email').val(),
is_ajax: 1
};
$.ajax({
type: $('#form').attr('method'),
url: action,
data: form_data,
success: function(response){
switch(response){
case 'ok':
var msg = 'data saved';
break;
case 'ko':
var msg = 'Oops something wrong happen';
break;
default:
var msg = 'misc:<br/>'+response;
break;
}
$('#message').html(msg);
}
});
return false;
});
});
</script>
body
<div id="message"></div>
<form id="form" action="handler.php" method="post">
<p>
<input type="text" name="fname" id="fname" placeholder="fname">
<input type="text" name="lname" id="lname" placeholder="lname">
</p>
<p>
<input type="text" name="phone" id="phone" placeholder="phone">
<input type="text" name="email" id="email" placeholder="email">
</p>
<input type="submit" name="submit" value="submit" id="submit">
</form>
And as for the handler.php file:
<?php
require('class/Container.php');
$filename = 'xml/memory.xml';
$is_ajax = $_REQUEST['is_ajax'];
if(isset($is_ajax) && $is_ajax){
$fname = $_REQUEST['fname'];
$lname = $_REQUEST['lname'];
$phone = $_REQUEST['phone'];
$email = $_REQUEST['email'];
$obj = new Container;
$obj->insertData('fname',$fname);
$obj->insertData('lname',$lname);
$obj->insertData('phone',$phone);
$obj->insertData('email',$email);
$tmp = $obj->give();
$result = $tmp['_obj'];
/*
Push data inside array
*/
$array = array();
foreach($result as $key => $value){
array_push($array,$key,$value);
}
$xml = simplexml_load_file($filename);
// check if there is any data in
if(count($xml->elements->data) == 0){
// if not, create the structure
$xml->elements->addChild('data','');
}
// proceed now that we do have the structure
if(count($xml->elements->data) == 1){
foreach($result as $key => $value){
$xml->elements->data->addChild($key,$value);
}
$xml->saveXML($filename);
echo 'ok';
}else{
echo 'ko';
}
}
?>
The Container class:
<?php
class Container{
private $_obj;
public function __construct(){
$this->_obj = array();
}
public function addData($data = array()){
if(!empty($data)){
$oldData = $this->_obj;
$data = array_merge($oldData,$data);
$this->_obj = $data;
}
}
public function removeData($key){
if(!empty($key)){
$oldData = $this->_obj;
unset($oldData[$key]);
$this->_obj = $oldData;
}
}
public function outputData(){
return $this->_obj;
}
public function give(){
return get_object_vars($this);
}
public function insertData($key,$value){
$this->_obj[$key] = $value;
}
}
?>
The strange thing is that my result always fall under the default switch statement and the ajax response fit both present statement. I noticed then if I just paste the Container class on the top of the handler.php file, everything works properly but it kind of defeat what I try to achieve.
I tried different way to include the Container class but it seem to be than the issue is specific to this current scenario.
I'm still learning PHP and my guess is that I'm missing something really basic. I also search on stackoverflow regarding the issue I'm experiencing as well as PHP.net, without success.
Regards,
My guess is that you have white space at the end of your class file, which is causing the output to be ' ok' instead of 'ok'. This can be the result of using certain applications to edit your files, or accidentally adding a space after the closing ?>. Try removing the closing ?> in your php class all together. This is not only allowed (php will automatically end processing at the end of the file anyways), but often encouraged in many style guides to prevent exactly the kind of thing that you are describing.
Another thing I usually do for this type of situation, is instead of returning a plain string, I return a json string, which jQuery will automatically turn into a javascript object for you. This would also prevent, or at least let you know right away that you are having the above type of problem.
so php would echo like this:
exit( json_encode( array( 'status' => 'ok' ) ) );
and jQuery would receive like this:
$.ajax({
type: $('#form').attr('method'),
url: action,
data: form_data,
dataType: 'json',
success: function(response){
switch(response.status){
case 'ok':
var msg = 'data saved';
break;
case 'ko':
var msg = 'Oops something wrong happen';
break;
default:
var msg = 'misc:<br/>'+response;
break;
}
$('#message').html(msg);
}
});
Note the added dataType parameter in the ajax call, as well as using response.status to check the status property that we created in PHP.
This also allows you to return more than one value in your response. You can build the object or array however you like on the PHP side, and you would basically receive the same as a javascript object on the javascript side.

Jquery and ajax, my function for username checking?

I have written this ajax request for username checking...
function check_username() {
var username = $("#username").val();
$('.loading').fadeIn().delay(100);
$.post("ajax.php", {
username: $('#username').val(),
}, function (response) {
$('.error, .success').hide();
setTimeout(function () {
$('.loading').hide();
finishAjax('username', response);
}, 1000);
});
return false;
}
function finishAjax(id, response) {
$('#' + id).after(response).fadeIn(1000);
}
It all works fine just a couple of questions,
Can this code be improved in any way, this is the first ever one I have wrote so I wouldn't know.
Is there a way to make this a function for all my ajax requests rather than just username checking, so it can be used for email checking and such too. I am not sure on how to make a function like that would I have to pass variables on my onblur event which is attached to my form, at the minute it looks like this.
Is there a way to stop the ajax from running if the same error is there as previous, ie, string length should be over 3, so someone inputs AJ, and the error message 'must be over 3 characters' comes up, it the user then triggers the onblur event again, with the value of AJ, or CG, then the same error comes up, triggering a script that is useless and using memory.
Is there a way to make the ajax request with every character the user enters?
My ajax php is as follows...
<?php
require('dbc.php');
if (isset($_REQUEST['username'])) {
$q = $dbc -> prepare("SELECT username FROM accounts WHERE username = ?");
$q -> execute(array($_REQUEST['username']));
if (strlen($_REQUEST['username']) < 3) {
echo '<div class="error">Has to be at least 3 characters</div>';
}
elseif ($q -> rowCount() > 0) {
echo '<div class="error">Username already taken</div>';
}
else {
echo '<div class="success">Username available</div>';
}
}
?>
To answer 1 & 2. I would turn it into a plugin and do something along these lines.
$.fn.checkValid = function(options)
{
var response = function(response) {
var setClass = '';
var $span = $(this).data('checkValidTip');
if ($span)
{
$span.remove();
}
if (response === undefined) return;
setClass = (response.valid ? 'valid' : 'invalid');
var $span = $('<span>' + response.msg + '</span>');
$(this)
.data('checkValidTip', $span)
.after($span);
$span.hide()
.fadeIn(1000)[0]
.className = setClass;
};
var ajaxOptions = {
type: 'GET',
url: 'ajax.php',
success: response,
dataType: 'json'
};
this.each(function() {
var that = this;
var ajaxRequest = ajaxOptions;
ajaxRequest.data = {};
ajaxRequest.data[options.key] = this.value;
ajaxRequest.context = that
$.ajax(ajaxRequest);
});
};
Usage
$('#username, #email').blur(function() {
$(this).checkValid({ key: this.id });
});
PHP changes
You should make your PHP function return a JSON, instead of HTML i.e.
<?php
// Do your sql statements here, decide if input is valid or not
$arr = array('valid' => $is_valid,
'msg' => $error_or_good_msg
);
echo json_encode($arr);
/* For example will output:
{
"valid": "false",
"msg": "<b>Error: Must be at least 2 characters</b>"
}
Which can be read directly as response.valid
or response.msg from within response() function
*/
To answer question 3: short answer is no. For this to work, you should have basic validation in JS. The best option would be to use a plugin that uses objects for validation parameters, that way you can output your validation requirements dynamically from your database, from within PHP using json_encode i.e. your output format would be:
var validations = {
username: {
min_chars: 4,
max_chars: 10,
valid_chars: 'qwertyuiopasdfghjklzxcvbnm_-'
},
email: {
regex: /./ //your magic regex here
}
};
jsFiddle
http://jsfiddle.net/sqZfp/2/
To answer 4, just change the event as above from .blur to .keyup should do the trick.

Categories