I want to create a registration form where I want to use jquery and also the CI validation library.
How can I do this? Upon submitting the form, I want the control to go to the validation library using jquery and return the response. Then, if all is well, I want the "form is submitted" message to be displayed on that page itself.
Edit:
here are my codes.
VIEW
<?php $this->load->view('template/header'); ?>
<div id="add_form">
<h2>Add New Category</h2>
<?php echo form_open('abc/abc_category_controller/add_new_category'); ?>
<?php
$category_data = array(
'name' => 'category_name',
'id' => 'category_name',
'value' => set_value('category_name'),
'maxlength' => '15'
);
$unit_data = array(
'name' => 'unit',
'id' => 'unit',
'value' => set_value('unit'),
'maxlength' => '10'
);
?>
<p><label for="name">Name: </label><?php echo form_input($category_data); ?></p>
<p><label for="unit">Unit: </label><?php echo form_input($unit_data); ?></p>
<p><?php echo form_submit('submit', 'Submit','id="submit"'); ?></p>
<?php echo form_close(); ?>
<?php echo validation_errors('<p class="error">'); ?>
</div><!--end add new category-form-->
<div id="success_msg">
</div>
<?php $this->load->view('template/footer') ?>
Controller- add_new_category
<?php
class Stocks_category_controller extends CI_Controller{
function add_new_category()
{
//$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Add a new category';
$this->form_validation->set_rules('category_name', 'Category Name', 'required');
$this->form_validation->set_rules('unit', 'Unit', 'required');
if ($this->form_validation->run() === FALSE)
{
$this->load->view('abc/add_new_category');
}
else
{
$category_name = $this->input->post('category_name');
$unit = $this->input->post('unit');
$this->load->model('abc/abc_category_model');
$insert_id=$this->abc_category_model->add_new_category($category_name
,$unit);
if($insert_id!=NULL)
{
$this->load->view('template/success',$data);
}
else{
$data['error_msg']='Error Occurred';
$this->load->view('template/template',$data);
}
}
}
function success(){
$data['success_msg']='New Category Successfully Created';
$this->load->view('template/success',$data);
}
}
And finally the model.
function add_new_category($category_name,$unit){
$data = array(
'abc_category_name' => $category_name ,
'unit' => $unit
);
$this->db->insert('abc_category', $data);
$insert_id=$this->db->insert_id();
return $insert_id;
}
}
What I want is that when I submit the form, jquery validation should take place. And if, all is well then the SUccessful message be displayed using ajax only and page should not reload.
Also, please tell me is it possible to use jquery validation and CI validation library both and maintaining ajax at the same time?
To implement both client side and server side validations you need to use the jquery validation plugin.
So, you need to include:
jQuery javascript library
jQuery validation plugin
Load the javascript with
<script type="text/javascript" src="<?php echo base_url();?>js/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>js/jquery.validate.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>js/jquery.validate-rules.js"></script>
then setup your form:
$attr = array('id' => 'demo_form');
echo form_open('demo/validation_example', $attributes);
and validate your form like:
$(document).ready(function() {
$("#demo_form").validate({
rules: {
name: {
required: true
},
...
},
messages: {
name: {
required: "Name required",
},
},
errorElement: "span",
errorPlacement: function(error, element) {
error.appendTo(element.parent());
}
});
});
And use the server side validation too, because it is not a good practice to use only client side validation.
For more help, you can find a good tutorial about
how to implement the jquery validation with codeigniter
and working demo
Where you can check jquery validation, and by disabling the javascript of your browser, you can check codeigniter server side validations done with php.
I think you have to use jquery ajax for this.
First you need to post your data. Set your submit button to fire jquery ajax like this.
$.ajax({
type: "GET",
url: "/controller/validate", //your controller action handler
dataType: "json",
data: {name:value, name: value}, //set your post data here
cache:false,
success: function(data){
//handle the callback response
if(data.success)
alert("Success");
else
alert(data.errors);
}
});
Next in your controller action, validate your post data using codeigniter validator.
If it fails the validation, you need to send the errors back to your js callback function using json_encode in your view. Set the data error like this,
In your view (the view you will set for /controller/validate), do something like this
$data['errors'] = validation_errors();
echo json_encode($data);
You will have the errors back to you without refreshing the page.
When the validation is success, just set a $data['success'] and use echo json_encode using if statement so that only success data will be retrieved. I have set the ajax script callback.
Related
I have a problem, i need to use, ajax in a form, in my page i have to change the color of a label after i search if a data is in a data base, if the data exist i must change the color of the label to red, if not i have to changed to green, i know how to use this in pure php, but i donĀ“t know how to do that in cakephp, if i am not wrong in pure php this is the forme to do it:
View
<form action="prueba.php" method="post">
<input type="text" id="txt_prueba" class="validador" />
<submit value="enviar"/>
</form>
View in Cake
<?php
echo $this->Form->create('Prueba', array('url' => 'prueba.php', 'type' => 'post'));
echo $this->Form->input('textoPrueba', array('label' => false,
'class' => 'validador'));
echo $this->Form->end(); ?>
Script
$(".validador").on('keyup keypress blur change', function (tecla) {
$.ajax({
method: "POST",
url: "algun.php",
data: {
name: $("#txt_prueba").val();
}
})
.done(function( msg ) {
if (msg=="Yes"){
$("#txt_prueba").css('background-color', 'red');
} else{
$("#txt_prueba").css('background-color', 'green');
}
});
});
Controller
require('conexion.php');
$consulta = $_POST['name'];
if (isset($consulta)) {
$consulta = mysqli_query($conexion, "SELECT * FROM tabla1
WHERE nombre LIKE '$consulta'");
$filas = mysqli_num_rows($consulta);
if ($filas === 0) {
echo 'Not';
}else {
echo 'Yes';
}
};
Have you read something about CakePHP? You should read some basic tutorial
Download and install CakePHP (https://book.cakephp.org/3.0/en/installation.html)
Build Your first controller with action and view (https://book.cakephp.org/3.0/en/tutorials-and-examples/cms/articles-controller.html)
Add Your JavaScript AJAX code in default.ctp layout file
Build Your first form (https://book.cakephp.org/3.0/en/tutorials-and-examples/cms/articles-controller.html#create-add-template)
Run, if You have some problems, try find solution on stackoverflow.com...
Hey I'm new to CI and have scoured the internet for a tutorial that will work but for some reason it won't work. Can someone help me with the code please:
What's the right edit to the code to submit an entry to the database via ajax without reloading the page?
Controller:
public function index(){
$this->load->helper('url');
$this->load->view('template');
}
function create()
{
$this->load->library('form_validation');
$this->load->helper('form');
$this->load->model('dbmodel');
$response = array();
$this->load->model('dbmodel');
$result = $this->dbmodel->addnew_row();
}
Model:
public function addnew_row() {
$data = array(
'title' => $this->input->post('title'),
'description' => $this->input->post('description'),
);
$result = $this->db->insert('books', $data);
return $result;
}
View Form:
<h2>Create</h2>
<?php echo form_open('welcome/create', array('id'=>'form'));?>
<p>Title: <?php echo form_input('title') ?></p>
<p>Description: <?php echo form_input('description') ?></p>
<?php echo form_submit('btn_submit','Save'); ?>
<?php echo form_close();?>
View AJAX:
// $.POST Example Request
$('#form').submit(function(eve){
eve.preventDefault();
var title = $('#title').val();
var description = $('#description').val();
url = '<?php echo site_url('welcome/create');?>'
$.ajax({
url: url,
type: 'POST',
data:{title:title, description:description
}
$(#dynamic_container).html(response.output);
});
});
Ok,At first you need to briefly go through the syntax of jQuery.ajax() before using it.
Now going though the AJAX code you mentioned in the question , this block of code is not suppose to be there
$(#dynamic_container).html(response.output);
AJAX provides Callback Function Queues to manipulate response before/after an AJAX call has been successfully completed , and in your case using success will resolve the issue :
$.ajax({
url: url,
type: 'POST',
data:{title:title, description:description
},
success : function(response){
$(#dynamic_container).html(response.output);
}
});
And you might be interested in using jQuery.post().
I am new to CakePHP and I am trying to figure you how to make an asynchronous call from a CakePHP view to a function in the controller. I would like the controller function to return a string and have the view display this string. I would also like to to do this without using helpers. I have been trying to find examples on the web but have been unable to do so. Does anyone have a simple example? I am also using jQuery.
Thanks
CakePHP has a built-in JS Helper to help write aJax functions. The only catch is to include jquery in your head or cake will throw jQuery errors. Heres more information http://book.cakephp.org/2.0/en/core-libraries/helpers/js.html
Your Form:
<?php
echo $this->Form->create('User', array('default'=>false, 'id'=>'YourForm'));
echo $this->Form->input('username');
echo $this->Form->submit('Check Username');
echo $this->Form->end();
?>
The Ajax Function: ('update'=>'#na') is the id of the element you want to update in your view.
<?php
$data = $this->Js->get('#YourForm')->serializeForm(array('isForm' => true, 'inline' => true));
$this->Js->get('#YourForm')->event(
'submit',
$this->Js->request(
array('action' => 'checkUsername', 'controller' => 'user'),
array(
'update' => '#na',
'data' => $data,
'async' => true,
'dataExpression'=>true,
'method' => 'POST'
)
)
);
echo $this->Js->writeBuffer();
?>
The Function in User Controller
function checkUsername(){
$this->autoRender = false;
$username = $this->User->find('first', array('conditions'=>array('User.username'=>$this->request->data['User']['username'])));
if ( $username == true )
echo 'Username is taken';
else
echo 'Username is not taken';
}
EDIT**
*If you want to use jQuery to do this and not the CakePHP Helper you can use aJax to call an action, then update your element like below*
$('#element').on('click', function() {
$.ajax({
url : '/controller/action',
type: 'POST',
success : function(response){
$('#elementToUpdate').html(response);
}
});
}
});
In your Controller Action you can return the "string" you would like to show in the view
function action(){
$string = 'Show this in the view';
return $string;
}
The above example would be executed when you "Click" an element with an id of "element" then upon "Success" would change element with id of "elementToUpdate" to the String "Show this in the view" Since it was returned from the controller action.
From further developments, I have a AJAX and CI email form that works perfectly with javascript disabled (using Codeigniter code) and when on using AJAX there are a few bugs.
When there are missing boxes and press submit it pops up with the error mmessage-great, but when filled in correctly and on submit it still posts the error even though its right and the email i still receive in my inbox.This is really bugging me as its something in my AJAX code and i think i am missing something in my controller.
Another question:On the AJAX form it is posting personal error/success messages- is there a way of echoing CI $success and echo validation_errors(); in this so they are the same?
The code is what i have so far:
TO see my controller follow this link: Codeigniter AJAX email validation
VIEW
<h1>Contact</h1>
<div id="contact">
<?php
//This is loaded in the view as it wont be used in the other pages
$this->load->helper('form');
echo form_open('contact/send_email');
//success message if passed validation checks
echo '<div id="success">';
echo $success;
echo '</div>';
// empty div for error messages (ajax)
echo '<div id="errors">';
// empty div for error messages (php)
if(validation_errors() != ""){
echo '<h3>Please correct the following errors:</h3>';
echo validation_errors();
}
echo '</div>';
echo form_label('Name: ', 'name');
$data = array (
'name' => 'name',
'id' => 'name',
'value' => set_value('name')
);
echo form_input($data);
echo form_label('Email: ', 'email');
$data = array (
'name' => 'email',
'id' => 'email',
'value' =>set_value('email')
);
echo form_input($data);
echo form_label('Message: ', 'message');
$data = array (
'name' => 'message',
'id' => 'message',
'value' =>set_value('message')
);
echo form_textarea($data);
?>
<br />
<?php
echo form_submit('submit', 'Send');
echo form_close();
?>
AJAX
<script type="text/javascript">
$(function() {
$('form').submit(function() {
// get the form values
var form_data = {
name: $('#name').val(),
email: $('#email').val(),
message: $('#message').val()
};
// send the form data to the controller
$.ajax({
url: "<?php echo site_url('contact/send_email'); ?>",
type: "POST",
data: $(form_data).serialize(),
success: function(msg) {
if(msg.validate)
{
$('form').prepend('<div id ="success">Success</div>');
$('#success').fadeOut(5000);
}else
$('form').prepend('<div id ="errors">Error</div>');
$('#errors').fadeOut(5000);
}
});
// prevents from refreshing the page
return false;
});
});
</script>
Looks to me like this line (in your javascript)
if(msg.validate)
is looking for an object, where your script isn't actually parsing any JSON or returning any JSON.
What I can only assume would be a good idea here (after looking at your controller too) would be to check if the <div id="errors"> has anything inside it in the response
Then in you javascript you would need to make a few changes
success: function(msg) {
if(msg.validate)
{
$('form').prepend('<div id ="success">Success</div>');
$('#success').fadeOut(5000);
}
else
{
$('form').prepend('<div id ="errors">Error</div>');
$('#errors').fadeOut(5000);
}
});
will become
success: function(msg) {
$msg = $(msg);
// check to see if the div with id="errors" contains a h3 tag
if($msg.filter('#errors').find('h3').length < 1)
{
$('form').prepend('<div id ="success">Success</div>');
$('#success').fadeOut(5000);
}
else
{
$('form').prepend('<div id ="errors">Error</div>');
$('#errors').fadeOut(5000);
}
});
Note: I've written this off the cuff so I haven't actually tested it but it should point you in the right direction.
Edited to use id selectors and not class selectors (habit of mine)
I am trying to create a twitter like application in which the user enters some data into a form and through using ajax (jquery library) the users see theirs submission in realtime go to the top of the all the other data.
The way it works is the user submits the form and the data gets submitted to the database, I also want to add teh data to the list of data using ajax.
My problem is I can only access the data the PHP method creates from the ajax request if I echo $var; in my php method, this doesn't look correct to me can some tell me what I am doing wrong please?
public function feed() {
$this->load->library('form_validation');
$this->load->helper('dates');
$data['feed'] = $this->f->get_feed_by_employer($this->session->userdata('employer_id'));
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->form_validation->set_rules('content', 'content', 'required|trim|max_length[140]');
$this->form_validation->set_rules('retrain', 'retrain position', 'trim|max_length[1]');
if ($this->form_validation->run() == FALSE)
{
echo validation_errors('<div class="error">', '</div>');
$this->template->build('employer/feed', $data);
}
else
{
$insert = array(
'content' => $this->input->post('content'),
'retrain' => $this->input->post('retrain'),
'created_at' => time(),
'employers_id' => $this->session->userdata('employer_id')
);
if($this->f->insert($insert)) {
echo $insert['content'];
}
}
}
and the jquery
$('#employer_feed').submit(function(){
$.ajax({
url: '/employer/feed',
data: $('#employer_feed').serialize(),
type: 'POST',
success:function(html) {
$('#feed').append('<div class="feed_item">'+html+'</div>');
}
});
return false;
});
There's no problem of using echo when dealing with ajax request, actually it's the way to go. Also you may use echo json_encode($output); depending on your ajax request type.
Check this article, using is_ajax to know when to echo and when to load your views is a clean way!
so create a file is-ajax_helper.php in application/helpers/ folder:
<?php
function is_ajax(){
return (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
}
And in your config/autoload.php:
$autoload['helper'] = array('is-ajax');
And just check if it's an ajax call or not!
EDIT:
Since Codeigniter 2.0 is officially out and plugins are now replaced with helpers, I have updated my Answer.
Nowadays, you can just use $this->input->is_ajax_request(), available in the input class, to achieve the same results as with the hand-made helper by #ifaour.