strange behavior while including a class in php - 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.

Related

PHP RESTful services; AJAX and DELETE method with username/password credentials

I asked another question related to RESTful services here, and have another question involving DELETE (PUT):
Same kind of situation where I want to send along user credentials (username/password) with my PUT. This is my DELETE service so far:
$http_req = $_SERVER["REQUEST_METHOD"];
switch ($http_req) {
case DELETE:
$user = $acct->read($_REQUEST["usernameDel"], $_REQUEST["passwordDel"]); // this method used to read db table with 1 record
if (!empty($_REQUEST["delTaskId"]) && isset($_REQUEST["usernameDel"]) && isset($_REQUEST["passwordDel"])) {
if ($user == true) {
$delete = fopen("php://input", "r");
$data = stream_get_contents($deleted);
$params;
parse_str($data, $params);
$dropped = $mgr->delete($params["id"]) // calls the method that deletes a particular row based on its id
echo $dropped;
}
}
}
This is the html page I am working with. I updated it to be in a :
<form action="TaskService.php" method="POST">
<label for="usernameDel">Username</label>
<input type="text" name="usernameDel" id="usernameDel" required/><br />
<label for="passwordDel">Password</label>
<input type="password" name="passwordDel" id="passwordDel" required/><br />
<label for="delTaskId">Task ID</label>
<input type="text" name="delTaskId" id="delTaskId" required/><br /><br />
<button type="button" id="btnDelete">Delete Task</button><br /><br />
</form>
This is my ajax code (edit-now using #Devs modifications):
$("#btnDelete").click(function() {
$.ajax({
method: "DELETE",
url: "TaskService.php",
data: { 'username':$("#usernameDel").val(), 'password': $("#passwordDel").val(), 'id': $("#delTaskId").val()},
success: function(theResponse) {
alert(theResponse);
}
});
});
Currently it returns a 200 response, but gives me the error messages I had put in for my Account class (comes back with "Could not find account".
My gut is telling me it has something to do with my $_REQUEST[] superglobals since it's not doing anything with a form action, but I am not all too familiar with passing information via ajax
Thoughts?
Just arranged the ajax format, also some syntax error in the php code.
Note: never tested
Ajax
$(document).ready(function(){
$("#btnDelete").click(function() {
$.ajax({
method: "DELETE",
url: "TaskService.php",
data: { 'username':$("#usernameDel").val(), 'password': $("#passwordDel").val(), 'id': $("#delTaskId").val()},
success: function(theResponse) {
// Output
alert(theResponse); // comment this
}
});
});
});
TaskService.php
<?php
$http_req = $_SERVER["REQUEST_METHOD"];
switch ($http_req) {
case DELETE:
$user = $acct->read($_REQUEST["username"], $_REQUEST["password"]); // this method used to read db table with 1 record
if ($user == true) {
$delete = fopen("php://input", "r");
$data = stream_get_contents($deleted);
$params;
parse_str($data, $params);
$dropped = $mgr->delete($params["id"]); // calls the method that deletes a particular row based on its id
echo $dropped;
}
break;
}
?>
Found out why my validation wasn't working! I feel so blind!
I was ignoring the fact that the delete action was taking username, password, and id as parameters....as such, validation wasn't going to work because the "php://input" file hadn't been opened to parse through all 3 parameters.
Here's my updated PHP that works:
// I needed to access the file FIRST before doing anything with the parameters passed from AJAX
$deleted = fopen("php://input", "r");
$data = stream_get_contents($deleted);
$params;
parse_str($data, $params);
$user_auth = $acctMgr->readAcct($params["username"], $params["password"]);
if ($user_auth == true) {
$rows = $mgr->delete($params["id"]);
echo $rows;
} else {
echo "User not authenticated";
}

How to use post() jquery method with codeigniter form_validation

I want to validate a form without refreshing the page using the .post() jQuery method.
I use codeigniter for validation. Could you please tell me how to make it right? I find it pretty confusing ...
Here is the jQuery code:
$(document).ready(function(){
$(".form_errors").hide();
$("#send").on("click",function(){ //the submit button has the id="send"
$(".form_errors").hide(); //these are <p> for each input to show the error
var user=$("input.box");
var data={};
var names=$("input.box").attr("name");
for(i=0;i<user.length;i++){
name=names[i];
value=user[i].val();
data.name=value;
}
$.post('ksite/account',
data,
function(result){
$("div.answer").html(result);
for(i=0;i<user.length;i++){
error_message=<?php echo form_error("?>names[i]<?php ");?>;
$("p#error_"+names[i]+".form_errors").html(error_message).show();
}
}
return false;});
});
form_error is a CodeIgniter function. (I suppose someone who used ci is familiar with).
The form:
<p id="error_user" class="form_errors"></p>
<input type="text" class="box" name="user">
<p id="error_password" class="form_errors"></p>
<input type="password" class="box" name="password">
<input type="submit" id="send">
Is the form tag neccessary ? And if yes,do i have to mention action and method ?
Do I have to specify the type of the response?
And in ksite/account I do:
/* ...... */
if (!this->form_validation->run(''account")) {
echo "The account couldn't be made";
} else {
echo "The account was successfully created ";
}
P.S.Although you may not be familiar with codeigniter, I would appreciate if someone could tell me if the code is correct and what improvements could be made.
Here is what I did.
You have to Ajax for getting data without refreshing the page.
HTML Page
$form = $(form);
var url = $form.attr('action');
dataString = $form.serialize();
$.ajax({
type: "POST",
url: url,
data: dataString,
dataType: "json",
success: function(data) {
$(data).each(function(j,details){
var status = details.status;
var message = details.message;
$('#message_ajax_register').show();
$('#message_ajax_register').html('<div class="alert alert-success">'+message+'</div>');
});
}
});//end of $.ajax**
I am first setting up the rules in my controller method and then validating it.
Controller
public function update_fest()
{
if($this->input->post())
{
$this->form_validation->set_rules('txtgpluswebsite', 'Google Plus Page URL', 'trim|xss_clean|prep_url');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
if($this->form_validation->run() == false){
$message = validation_errors();
$data = array('message' => $message,'status'=>0);
}
else{
$message = $this->add_fest_database();
$data = $message;
}
}
else{
$message = "Fest details are required";
$data = array('message' => $message,'status'=>0);
}
$this->output->set_content_type('application/json');
$json = $this->output->set_output(json_encode($data));
return $json;
}
If validation run is not false, then go to add_fest_database(other function). In that function,
function add_fest_database()
{
$youtubeWebsite = $this->input->post('txtyoutubewebsite');
$gplusWebsite = $this->input->post('txtgpluswebsite');
$this->load->model('model_fest');
$data = array("fest_youtube"=>$youtubeWebsite,"fest_gplus"=>$gplusWebsite);
return data;
}

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>

Using AJAX in a backoffice PrestaShop module

I'm creating a module for the shopping cart PrestaShop so I have to follow a set framework of rules when creating a module that will work in their system, and I want to submit forms via AJAX without reloading the page.
Here is a trimmed version of the module page which builds and determines what is displayed:
<?php
class mymodule extends Module
{
private $_html = '';
// Module information
function __construct()
{
// Get shop version
$versionMask = explode('.', _PS_VERSION_, 3);
$versionTest = $versionMask[0] > 0 && $versionMask[1] > 3;
// Module info
$this->name = 'MyModule';
$this->tab = $versionTest ? 'administration' : 'Administration';
if ($versionTest) { $this->author = 'JD'; }
$this->version = '0';
parent::__construct();
$this->displayName = $this->l('MyModule');
$this->description = $this->l('Description...');
}
// Display content
public function getContent()
{
$this->_displayForm();
return $this->_html;
}
// Build the display
private function _displayForm()
{
$this->_html .= '<script src="../modules/mymodule/scripts.js" type="text/javascript"></script>
<form name="formName" id="formName" method="get">
<input type="submit" name="submitModule" value="Continue" />
</form>';
}
}
?>
Normally there is a private _postProcess function which processes form data which then calls the function getContent on page reload where you can then check to see if it should show the form or the results etc.
But since I want to do this with AJAX, I've removed the _postProcess function as it's not needed, linked to my scripts.js which has the following:
$(document).ready(function() {
$('#formName').submit(function(e)
{
e.preventDefault();
$.ajax({
url: "ajax.php",
type: "GET",
dataType: "json",
success: function(data)
{
if (data.response == 1)
{
alert('true');
}
else
{
alert('false');
}
}
});
});
});
And the ajax.php file itself which I've really trimmed down so it's forced to show a result:
<?php
$json['response'] = 1;
echo json_encode($json);
exit();
?>
But I always get the error Uncaught TypeError: Cannot read property 'response' of null, which is obviously telling me the data.response isn't being sent through properly as it doesn't know what response is.
If I test the pages manually, everything works fine, so it leads me to believe either it has something to with the fact it could be in a class perhaps? And that I have to do something different to usual to get it to send the data through?
Or PrestaShop doesn't allow modules to run via AJAX, yet the only thing I can find on their site which relates to this is someone asking the same question in their forum and it has no replies/fixes.
I'd also like to note the AJAX is working to an extent, that if in the success function I put alert("hello"); the alert popup is shown.
Does anyone have any ideas where I might be going wrong?
Uncaught TypeError: Cannot read property 'response' of null scripts.js:132
$.ajax.success scripts.js:132
o jquery-1.7.2.min.js:2
p.fireWith jquery-1.7.2.min.js:2
w jquery-1.7.2.min.js:4
d
scripts.js:132 refers to the line: if (data.response == 1)
Also I've taken it out of the class and put it on a normal page/seperate directory and have the same code, just not inside the class/functions:
index.php
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="scripts.js" type="text/javascript"></script>
<form name="formName" id="formName" method="get">
<input type="submit" name="submitModule" value="Continue" />
</form>
scripts.js
$(document).ready(function() {
$('#formName').submit(function(e)
{
e.preventDefault();
$.ajax({
url: "ajax.php",
type: "GET",
dataType: "json",
success: function(data)
{
if (data.response == 1)
{
alert('true');
}
else
{
alert('false');
}
}
});
});
});
ajax.php
<?php
$json['response'] = 1;
echo json_encode($json);
exit();
?>
And when I submit the page I get the alert true and if I view ajax.php I get {"response":1}. So that code itself is ok, it's just integrating it with their class/functions.
It appears the path to the ajax.php file in the scripts.js file was causing the problem.
It's to do with the structure of the folders in prestashop, all modules are placed in /prestashop/modules/ directory but the modules are viewed from /prestashop/admin/. So changing them to the full paths fixed the problem.
Thanks to the guys that helped on here though, it's still appreciated!
I think your result is being sent ok, but not interpreted as JSON, a bit of the jquerys fault - I dare to say.
header('Content-Type: text/javascript; charset=utf8');
Putting this in the PHP script should do the trick and force the correct interpretation of the json the data.
If the previous suggestion didn't get you anywhere also try using $.parseJson(); as in jQuery docs:
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );

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

(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!)

Categories