How to call javascript function in callback function of codeigniter controller? - php

I want call the javascript function into callback function of codeigniter controller.
Controller: Callback function
public function email_exist($id) {
$this->db->where('email', $id);
$query = $this->db->get('login');
if (!$query->num_rows() > 0) {
$this->form_validation->set_message(__FUNCTION__, $this->email_validate());
return FALSE;
} else {
return TRUE;
}
Javascript: Alert function
function email_validate(){
alert('Invalid Email Id');
}
An uncaught Exception was encountered
Type: Error
Message: Call to undefined method Login::email_validate()
Filename: C:\wamp64\www\CodeIgniterProject1\application\controllers\login.php
Line Number: 46
login_form.php
<?php echo validation_errors(); ?>
<?php echo form_open_multipart(); ?>
<form name="form">
<div class="loginform">
<?php echo form_label('LOGIN', 'login'); ?>
</div>
<div class="email">
<?php echo form_input('email', 'E-MAIL', set_value('email')); ?>
</div>
<div class="password">
<?php echo form_password('password', 'PASSWORD', set_value('password')); ?>
</div>
<div class='checkbox'>
<?php
echo form_checkbox(array(
'name' => 'remember',
'id' => 'remember',
'value' => 'REMEMBER ME',
'checked' => FALSE,
'style' => 'margin:1px'
)) . form_label('REMEMBER ME', 'remember');
?>
</div>
<div class='btnlogin'>
<?php echo form_submit('login', 'LOGIN'); ?>
</div>
</form>

you cant do that in Codeigniter, use Codeigniter default form validation library
View here
if you want to add css for validation errors then try set_error_delimeters()
if you have bootstrap then use
alert alert-danger
class, else create one class
$this->form_validation->set_error_delimiters('<div class="alert alert-danger">', '</div>');
see
[other suggestions]
instead of putting all error in the top, you can also try
<?php
echo form_error('email');
form_input('email', 'E-MAIL', set_value('email'));
?>
other options is jquery validation or js validation, write js in view or external .js file
<?php
data = array(
'name' => 'username',
'id' => 'username', //use the id for jquery validation $('#username').on('blur', function() { });
'value' => 'johndoe',
'maxlength' => '100',
'size' => '50',
'style' => 'width:50%'
'onBlur' => 'email_validate();' //use this for javascript validation
);
echo form_input($data);
?>
im unable to comment, thats why posting as answer

Related

Codeigniter form validation does not show error and redirects to blank page

Given below is controller and view but its not validated and only redirects to about:blank page.
I Have made some changes but nothing happens.
controller:
<?php
class Home extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library(array('form_validation','session')); // load form lidation libaray & session library
$this->load->helper(array('url','html','form')); // load url,html,form helpers optional
}
public function index(){
// set validation rules
$this->form_validation->set_rules('name', 'Name', 'required|min_length[4]|max_length[10]');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('number', 'Phone Number', 'required|numeric|max_length[15]');
$this->form_validation->set_rules('subject', 'Subject', 'required|max_length[10]|alpha');
$this->form_validation->set_rules('message', 'Message', 'required|min_length[12]|max_length[100]');
// hold error messages in div
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
// check for validation
if ($this->form_validation->run() == FALSE) {
$this->load->view('viewform');
}else{
$this->session->set_flashdata('item', 'form submitted successfully');
redirect('Home');
}
}
}
?>
view:
<?php if(validation_errors()) { ?>
<div class="alert alert-warning">
<?php echo validation_errors(); ?>
</div>
<?php } ?>
<?php if($this->session->flashdata('item')) { ?>
<div class="alert alert-success">
<?php echo $this->session->flashdata('item'); ?>
</div>
<?php } ?>
<?php echo form_open(); ?>
<div class="form-group">
<?php echo form_label('Your Name','name'); ?>
<?php echo form_input(array("class"=>"form-control","name" => "name", "placeholder"=>"Enter Name","value" => set_value('name'))); ?>
</div>
<div class="form-group">
<?php echo form_label('Email address','EmailAddress'); ?>
<?php echo form_input(array("class"=>"form-control","name" => "email", "placeholder"=>"Enter email","value" => set_value('email'))); ?>
</div>
<div class="form-group">
<?php echo form_label('Phone Number','number'); ?>
<?php echo form_input(array("class"=>"form-control","name" => "number", "placeholder"=>"Enter Phone Number","value" => set_value('number'))); ?>
</div>
<div class="form-group">
<?php echo form_label('Subject','subject'); ?>
<?php echo form_input(array("class"=>"form-control","name" => "subject", "placeholder"=>"Enter Subject","value" => set_value('subject'))); ?>
</div>
<div class="form-group">
<?php echo form_label('Message','message'); ?>
<?php echo form_input(array("class"=>"form-control","name" => "message", "placeholder"=>"Enter Message","value" => set_value('message'))); ?>
</div>
<button type="submit" class="btn btn-default">Submit</button>
<?php echo form_close(); ?>
so when any error is there the page is redirected to about:blank even if all fields are proper or improper how to fix this?

Codeigniter form_validation not working

I have used codeigniter in the past but I am building a social network and I am working on the registration. I have autoloaded the form and form validation helpers. I have a form going to my user controller/register function and I have validation rules setup but its ignoring them and proceeding to the next page. I cant for the life of me figure out why. Any help is appreciated..the code and rules are not complete (obviously) but the validation should work at this point
VIEW
<?php echo validation_errors('<p class="error">'); ?>
<?php echo form_open('user/register/1'); ?>
<?php echo form_hidden('register_id', $randomcode); ?>
<?php echo form_label('First Name', 'first_name'); ?>
<?php echo form_input('first_name',set_value('first_name')); ?>
<br />
<?php echo form_label('Last Name', 'last_name'); ?>
<?php echo form_input('last_name',set_value('last_name')); ?>
<br />
<?php echo form_label('Gender', 'gender:'); ?>
<?php echo form_radio('gender', 'male'); ?> Male
<?php echo form_radio('gender', 'female'); ?> Female
<br />
<?php echo form_label('Date of Birth:', 'birthdate'); ?>
<?php echo form_date('birthdate'); ?>
<br />
<?php echo form_label('Zipcode:', 'zipcode'); ?>
<?php echo form_input('zipcode',set_value('zipcode')); ?>
<br />
<?php echo form_label('Email:', 'email'); ?>
<?php echo form_email('email',set_value('email')); ?>
<br />
<?php echo form_label('Password', 'password'); ?>
<?php echo form_password('password'); ?>
<br />
<?php echo form_label('Confirm', 'password2'); ?>
<?php echo form_password('password2'); ?>
<br />
<?php
$data = array(
'name' => 'submit',
'class' => 'big-blue-btn',
'value' => 'Sign Up'
);
?>
<?php echo form_submit($data); ?>
<?php echo form_close(); ?>
CONTROLLER
public function register($step){
if($step == 1){
$this->form_validation->set_rules('first_name', 'first_name', 'required');
$this->form_validation->set_rules('last_name', 'last_name', 'required');
if($this->form_validation->run() == FALSE){
//Views
$data['main_content'] = 'public/user/register1';
$this->load->view('public/template', $data);
} else {
//Post values to array
$data = array(
'register_id' => $this->input->post('register_id'),
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'gender' => $this->input->post('gender'),
'birthdate' => $this->input->post('birthdate'),
'zipcode' => $this->input->post('zipcode'),
'email' => $this->input->post('email'),
'password' => $this->input->post('password'),
'password2' => $this->input->post('password2')
);
//Send input to model
$this->User_model->register1($data);
$data['show_sidebar'] = FALSE;
}
} elseif($step == 2){
//Send input to model
$this->User_model->register2($data);
} elseif($step == 3){
//Send input to model
$this->User_model->register3($data);
}
}
Review your code, you're missing a closing bracket on your first if.

codeigniter form validation not functioning

i am working on a small form that summits data to a table on to a database nothing spectacular. i am trying to add some validation rules but they are not working i am still a beginner at php and codeigniter so cant figure out why can someone look at my code and help me out tnx in advance.
view
<html>
<head>
</head>
<body>
<?php echo validation_errors(); ?>
<?php echo form_open('http://localhost/Surva/index.php/info/credentials/'); ?>
<ul id="info">
<li><label for='name'>Name:</label><?php echo form_input('name')?>
</li>
<li><label for='second_name'>Second Name:<label> <?php echo form_input('second_name');?>
</li>
<li><label fro='phpne'>Phone:</label> <?php echo form_input('phone');?></li>
<li><label for='email'>Email: </label><?php echo form_input('email');?>
</li>
<li><?php echo form_submit('submit', 'Start survay!!' );?></li>
</ul>
<?php echo form_close();?>
</body>
</html>
controller
<?php
class Info extends CI_Controller{
function index(){
$this->load->view('info_view');
}
function credentials()
{
$data = array(
'name' => $this->input->post('name'),
'second_name' => $this->input->post('second_name'),
'phone' => $this->input->post('phone'),
'email' => $this->input->post('email'),
);
$this->info_model->add_record($data);
}
function validation(){
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name', 'required|alpha|xss_clean');
$this->from_validation->set_rules('second_name', 'required|alpha|xss_clean');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
if ($this->form_validation->run() == FALSE){
$this->load->view('info_view');
}else{
redirect('survaycontroller/index');
}
}
}
?>
i used the codeigniter user guide for validation in there explanation it looked very easy the whole structure is taken from the guide i daunt understand what the problem is .
You can do it Simple with one controller. I test it and it works!
Class name test.php
Controller name index
function index(){
$this->load->library('form_validation');
$data['name'] = $this->input->post('name');
$data['second_name'] = $this->input->post('second_name');
$data['phone'] = $this->input->post('phone');
$data['email'] = $this->input->post('email');
if($this->input->post('submit')) {
$this->form_validation->set_rules('name', 'Name', 'required|alpha|xss_clean');
$this->form_validation->set_rules('second_name', 'Second Name', 'required|alpha|xss_clean');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
if ($this->form_validation->run()){
$this->info_model->add_record($data);
}
}
$this->load->view('test');
}
View: test.php
<html>
<head>
</head>
<body>
<?php echo validation_errors(); ?>
<?php echo form_open('test/index'); ?>
<ul id="info">
<li><label for='name'>Name:</label><?php echo form_input('name')?>
</li>
<li><label for='second_name'>Second Name:<label> <?php echo form_input('second_name');?>
</li>
<li><label fro='phpne'>Phone:</label> <?php echo form_input('phone');?></li>
<li><label for='email'>Email: </label><?php echo form_input('email');?>
</li>
<li><?php echo form_submit('submit', 'Start survay!!' );?></li>
</ul>
<?php echo form_close();?>
</body>
</html>
You're not sending the form to the method validation
view
<html>
<head>
</head>
<body>
<?php echo validation_errors();
//you must redirect the form to the right method, in this case your method is "validation" on the controller is "info"
//another thing, you don't need to put all the url, just put the controller and the method, this way when you migrate your website to a server you don't have to worry changing the url
echo form_open('info/validation'); ?>
<ul id="info">
<li><label for='name'>Name:</label><?php echo form_input('name')?>
</li>
<li><label for='second_name'>Second Name:<label> <?php echo form_input('second_name');?>
</li>
<li><label fro='phpne'>Phone:</label> <?php echo form_input('phone');?></li>
<li><label for='email'>Email: </label><?php echo form_input('email');?>
</li>
<li><?php echo form_submit('submit', 'Start survay!!' );?></li>
</ul>
<?php echo form_close();?>
</body>
</html>
controller
<?php
class Info extends CI_Controller{
//I've added the public before function
public function index(){
$this->load->view('info_view');
}
//In this one I've added private, Why? Because you don't peopple to use this method if they go to http://(yourdomain). This way you can only use this function inside this controller
private function credentials()
{
$data = array(
'name' => $this->input->post('name'),
'second_name' => $this->input->post('second_name'),
'phone' => $this->input->post('phone'),
'email' => $this->input->post('email'),
);
$this->info_model->add_record($data);
}
//this one is also as public, and it's the one who we'll receive the post request from your form
public function validation(){
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name', 'required|alpha|xss_clean');
$this->from_validation->set_rules('second_name', 'required|alpha|xss_clean');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
if ($this->form_validation->run() == FALSE){
$this->load->view('info_view');
}else{
//if the form is valid then you call the private function credentials and save the data to your database
$this->credentials();
redirect('survaycontroller/index');
}
}
}
?>
Check the alterations I made to your code, if you need some more explain or help you're welcome
second param missing in second rule
$this->from_validation->set_rules('second_name', 'Second Name', 'required|alpha|xss_clean');
Look at the example below, You have to check $this->form_validation->run() inside your credentials() function.
public function add_category()
{
$this->load->library('form_validation');
$data = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
//Validation rules
$this->form_validation->set_rules('name', 'Name', 'trim|required');;
$this->form_validation->set_rules('description', 'Description', 'trim|required');
$this->form_validation->set_rules('position', 'Position', 'trim|numeric');
$artist_category = $this->input->post('artist_category', TRUE);
$data['artist_category'] = $artist_category;
if($this->form_validation->run() === FALSE)
{
$this->template->write('title', 'Category : Add Category');
$this->template->write_view('content', 'category/add_category',$data);
$this->template->render();
}
else
{
$name = trim($this->input->post('name',TRUE));
$description = trim($this->input->post('description',TRUE));
$position = trim($this->input->post('position',TRUE));
$colour = trim($this->input->post('colour',TRUE));
$language_id = trim($this->input->post('language_id',TRUE));
//Add record to categories table
$category_id = $this->Category_model->insert_category($name,$description,$position,$colour,$date_added);
$this->session->set_flashdata('success_msg', 'Category added successfully.');
//Redirect to manage categories
redirect('category');
}
}
else
{
$this->template->write('title', 'Category : Add Category');
$this->template->write_view('content', 'category/add_category');
$this->template->render();
}
}

Yii: Access CActiveForm.htmlOptions from controller when form is submitted to change css visibility

I have a CActiveForm which when submitted should make a second CActiveForm become visible. I know how to change the htmlOptions of the form when its created but not how to access it via the controller.
My View with two forms. The second form has visibility:hidden
<div class="form">
<?php
$numberForm = $this->beginWidget('CActiveForm', array(
'id' => 'addnumber-form',
'enableAjaxValidation' => true,
'clientOptions' => array(
'validateOnSubmit' => true,
),
));
?>
<p class="note"><?php echo UserModule::t('Fields with <span class="required">*</span> are required.'); ?></p>
<?php echo $numberForm->errorSummary($numberModel); ?>
<div class="row">
<?php echo $numberForm->labelEx($numberModel, 'number'); ?>
<?php echo $numberForm->textField($numberModel, 'number'); ?>
<?php echo $numberForm->error($numberModel, 'number'); ?>
<?php
echo CHtml::submitButton(UserModule::t("Verify"), array(
"class" => "btn btn-success"
));
?>
</div>
<?php $this->endWidget(); ?>
<?php
$verifyForm = $this->beginWidget('CActiveForm', array(
'id' => 'verify-form',
'enableAjaxValidation' => true,
'clientOptions' => array(
'validateOnSubmit' => true,
),
'htmlOptions' => array("style"=>"visibility: hidden"),
));
?>
<?php echo $verifyForm->errorSummary($verifyModel); ?>
<p>A authorisation code has been sent to your phone. Please enter it below. If you don't receive a text message make sure you entered your number correctly and try again</p>
<div class="row">
<?php echo $verifyForm->labelEx($verifyModel, 'authcodeUser'); ?>
<?php echo $verifyForm->textField($verifyModel, 'authcodeUser'); ?>
<?php echo $verifyForm->error($verifyModel, 'authcodeUser'); ?>
<?php
echo CHtml::submitButton(UserModule::t("Confirm"), array(
"class" => "btn btn-success"
));
?>
<?php
foreach(Yii::app()->user->getFlashes() as $key => $message) {
echo '<div class="flash-' . $key . '">' . $message . "</div>\n";
}
?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
My controller for these forms
public function actionAddnumber(){
$numberModel = new UserAddNumber;
$verifyModel = new UserVerifyNumber;
if (Yii::app()->user->id) {
// ajax validator
if(isset($_POST['ajax']) && $_POST['ajax']==='addnumber-form')
{
echo UActiveForm::validate($numberModel);
Yii::app()->end();
}
if(isset($_POST['UserAddNumber'])) {
$numberModel->attributes=$_POST['UserAddNumber'];
if($numberModel->validate()) {
$profile = Profile::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
$profile->mobileNo = $numberModel->number;
$profile->save();
//MAKE $verifyForm visibility to visible uring htmlOptions
Yii::app()->session['authcode'] = '4444';
}
}
if(isset($_POST['UserVerifyNumber'])) {
$verifyModel->attributes=$_POST['UserVerifyNumber'];
if($verifyModel->validate()) {
$profile = Profile::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
$profile->mobileNoVerified = True;
$profile->save();
Yii::app()->user->setFlash('profileMessage',UserModule::t("Your mobile number has been verified"));
$this->redirect(array("profile"));
}
}
}
$this->render('addnumber', array('numberModel'=>$numberModel, 'verifyModel' => $verifyModel));
}
It looks like you could just create a new variable for whether or not to show the second form and then pass it to the view. Here is your controller:
public function actionAddnumber(){
$numberModel = new UserAddNumber;
$verifyModel = new UserVerifyNumber;
$formVisibility = "hidden";
if (Yii::app()->user->id) {
// ajax validator
if(isset($_POST['ajax']) && $_POST['ajax']==='addnumber-form')
{
echo UActiveForm::validate($numberModel);
Yii::app()->end();
}
if(isset($_POST['UserAddNumber'])) {
$numberModel->attributes=$_POST['UserAddNumber'];
if($numberModel->validate()) {
$profile = Profile::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
$profile->mobileNo = $numberModel->number;
$profile->save();
//MAKE $verifyForm visibility to visible uring htmlOptions
$formVisibility = "visible";
Yii::app()->session['authcode'] = '4444';
}
}
if(isset($_POST['UserVerifyNumber'])) {
$verifyModel->attributes=$_POST['UserVerifyNumber'];
if($verifyModel->validate()) {
$profile = Profile::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
$profile->mobileNoVerified = True;
$profile->save();
Yii::app()->user->setFlash('profileMessage',UserModule::t("Your mobile number has been verified"));
$this->redirect(array("profile"));
}
}
}
$this->render('addnumber', array('numberModel'=>$numberModel, 'verifyModel' => $verifyModel, 'formVisibility' => $formVisibility));
}
And here is the first part of your second form:
<?php
$verifyForm = $this->beginWidget('CActiveForm', array(
'id' => 'verify-form',
'enableAjaxValidation' => true,
'clientOptions' => array(
'validateOnSubmit' => true,
),
'htmlOptions' => array("style"=>"visibility: ".$formVisibility),
));
?>
[edit] To make sure I am answering your question, I should add that I've never seen any way of changing the htmlOptions from the controller directly. That's why I proposed this solution instead.

Missing validation message in cakephp application

I'm trying to add a layout for a cakephp application but now my validation message is no longer being displayed. When validating a comment on a blog entry, the validation message thats suppose to be at the top is not displayed.
If you changing the layout means that you missed to add
<?php
if ($this->Session->check('Message.flash')){
echo $this->Session->flash();
}
?>
before the
Other possible place is in the current controller.
Search if you have code like:
$this->Session->setFlash('...');
The first code is responsible for displaying the message, while the second one is responsible for setting the message.
But the code definitely will help more :)
Here is my add function in comments_controller.php
function add(){
debug($this->data);
//if the user submitted a comment post
if (!empty($this->data)){
//display the 'add view'
$this->Comment->create();
if ($this->MathCaptcha->validates($this->data['Comment']['security_code'])) {
if ($this->Comment->save($this->data)){
$this->Session->setFlash(__('The Comment has been added.', true));
$this->redirect('/posts/index/'.$this->data['Comment']['post_id']);
}
//failed validation
else{
debug($this->data);
$this->Session->setFlash(__('Comment could not be saved. Please try again.', true));
}
}
else {
$this->Session->setFlash(__('Please enter the correct answer to the math question.', true));
$this->redirect('/posts/index/'.$this->data['Comment']['post_id']);
}
Here is my entry.ctp where my posts and comments reside:
<div id="article">
<h2><?php echo $entry[0]['Post']['title']; ?></h2>
<p class="date"><em>Modified:</em> <?php $date = new DateTime($entry[0]['Post']['modified']);
echo $date->format('Y-m-d');?></p>
<p class="date"><em>Author:</em> <?php echo $entry[0]['User']['username']; ?></p>
<p class="intro"><?php echo $entry[0]['Post']['content']; ?></p>
<h2>Comments:</h2>
<div id="comments_success"></div>
<!-- show the comment -->
<?php
echo $form->create('Comment', array('action' => 'add'));
echo $form->input('name', array('class' => 'validate[required] text-input'));
echo $form->input('email', array('class' => 'validate[required,custom[email]] text-input'));
echo $form->input('text', array('id' => 'commenttext', 'type' => 'textarea', 'label' => 'Comment:', 'rows' => '10', 'class' => 'validate[required] text-input'));
//captcha
echo $form->input('security_code', array('label' => 'Please Enter the Sum of ' . $mathCaptcha));
echo $form->input( 'Comment.post_id', array( 'value' => $entry[0]['Post']['id'] , 'type' => 'hidden') );
echo $form->end('Submit');
?>
<!-- comments -->
<ol>
<?php
foreach ($entry[0]['Comment'] as $comment) :
?>
<li>
<h3><?php echo $comment['name']; ?></h3>
<p class="date"><em>Date:</em> <?php echo $comment['created']; ?></p>
<p class="text"> <?php echo $comment['text']; ?></p>
</li>
<?php
endforeach;
?>
</ol>
</div>
This is the index function in my posts_controller
function index($entry_id = null) {
if (isset($entry_id)){
$entry = $this->Post->findAllById($entry_id);
$comments = $this->Post->Comment->getCommentsFromPostID($entry_id);
$this->set('entry' , $entry);
$this->set('mathCaptcha', $this->MathCaptcha->generateEquation());
$this->render('entry');
}
else{
$posts = $this->Post->find('all');
$this->set(compact('posts'));
}
}
I know this is old, but ust make sure you have the following code somewhere visible in your app/views/layouts/default.ctp (or whatever is your layout for this application)
<?php echo $this->Session->flash(); ?>
It will echo nothing if there is no message to be displayed, but if there is a message, then it will be output accordingly.

Categories