Ajax form validation in codeigniter - codeigniter

hellp guys,
I've been working on ajax recently, and I have a problem in using it with codeigniter form validation library. I used the example that tool generate in the function http://formtorch.geekhut.org/.
Now, ajax works perfectly and return data correctly when I use json_encode() function with dummy data, but validation in the example uses validation library instead of form_validation library, which seems to be older version.
For that, validation didn't work with ajax in that example, specifically $this->form_validation->run() function makes ajax return no result even if I echo dummy data using json_encode() in the beginning of create_course().
so what's wrong with validation with ajax, and explain to me how data sent by ajax received by the controller.
so this is my code:
function create_course()
{
$this->form_validation->set_rules('course_code', 'course_code', 'trim|xss_clean|required');
$this->form_validation->set_rules('name', 'name', 'xss_clean|required');
// .. etc
if ($this->form_validation->run()) {
// validation ok
$data['course_code'] = $this->form_validation->set_value('course_code');
$data['name'] = $this->form_validation->set_value('name');
// ... etc
if ($this->models_facade->create_course($user_id,$data)) { // success
$data = array( 'profile_change' => $this->lang->line('profile_change'));
} else { // fail
$data = array( 'profile_change_error' => $this->lang->line('profile_change_error'));
}
}
else
{
$data = array(
'course_code' => $this->form_validation->course_code_error,
'name' => $this->form_validation->name_error
);
}
echo json_encode($data);
}
and this is the Jquery Ajax function
   $(function(){
$("#submit").click(function(){
var course_code = $("#course_code").val();
var name = $("#name").val();
// etc
$.post("<?php echo base_url() ?>home/create_course", course_code:course_code, name:name},
function(data){
function(data){
alert(data.data);
$("#course_code_error").html(data.course_code);
$("#name_error").html(data.name);
},'json');
});
return false;
});
   

Rather than printing out via "this->form_validation->xxxx_error" you can utilize Form Helper method "form_error()" to call the error messages.
So you can do something like..
$data = array(
'course_code' => form_error('course_code'),
'name' => form_error('name')
);

You might also consider setting the output content type header for JSON data.
$this->output->set_content_type('application/json');
echo json_encode($data);

What version of Codeigniter are you using? Did you remember to load the validation library in your construct?
$this->load->library('form_validation');

If you're making an ajax request you can use the validation_errors().
When the validation run it'll populate the array of error messages.
Here an exemple :
// Set your rules
$this->form_validation->set_rules('course_code', 'course_code', 'trim|xss_clean|required');
$this->form_validation->set_rules('name', 'name', 'xss_clean|required');
if ($this->form_validation->run()) {
//happy happy time
}
else {
//well now i'm sad...
//Important to turn that off if it's on
$this->output->enable_profiler(false);
$this->output->set_status_header('500');
$this->output->set_content_type('application/json');
echo json_encode(array(
'error_msg' => validation_errors(),
));
}
And then on your client-side you can use the response like that :
error:function(data) {
$("your-error-input-selector").html('').append(data.responseJSON.msg);
}
Hope i helped even if i'm 2 year late.
P.S Sorry for my broken english.

****//view-path [application/views/myviews/myview2.php]****
<script src="<?php echo base_url('/jquery-1.9.1.min.js');?>"></script>
<script>
$(document).ready(function() {
$("#frm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: $('#frm').attr('action'),
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
console.log(data);
data = JSON.parse(data);
if(data.st == 0)
{
$( ".error-message" ).remove();
var data1 = JSON.parse(data.msg);
$('form :input').each(function(){
var elementName = $(this).attr('name');
var message = data1[elementName];
if(message){
var element = $('<div>' + message + '</div>')
.attr({
'class' : 'error-message'
})
.css ({
display: 'none'
});
$(this).before(element);
$(element).fadeIn();
}
});
}
if(data.st == 1)
{
$('#validation-error').html(data.msg);
$( ".error-message" ).remove();
}
},
error: function(){}
});
}));
});
</script>
<style>
.error-message{color:red;}
</style>
<?php echo form_open_multipart('ajaxcontroller/index', array('id'=>'frm')); ?>
<div id="validation-error"></div>
<h5>Username</h5>
<input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" />
<h5>Password</h5>
<input type="text" name="password" value="<?php echo set_value('password'); ?>" size="50" />
<h5>Password Confirm</h5>
<input type="text" name="passconf" value="<?php echo set_value('passconf'); ?>" size="50" />
<h5>Email Address</h5>
<input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" />
<h5>Profile Pic</h5>
<input type="file" name="image[]" value="" multiple=""/>
<div><input type="submit" value="Submit" /></div>
</form>
**//controller--[application/controllers/ajaxcontroller.php]****
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Ajaxcontroller extends CI_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
if($_POST)
{
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]');
$this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
if (empty($_FILES['image']['name'][0])) {
$this->form_validation->set_rules('image[]', 'File', 'required');
}
if ($this->form_validation->run() == FALSE)
{
$errors = $this->form_validation->error_array(); //function in library : My_Form_validation
echo json_encode(array('st'=>0, 'msg' => json_encode($errors)));
}
else
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$email = $this->input->post('email');
if(is_array($_FILES)) {
foreach ($_FILES['image']['name'] as $name => $value){
if(is_uploaded_file($_FILES['image']['tmp_name'][$name])) {
$sourcePath = $_FILES['image']['tmp_name'][$name];
$targetPath = "images/".$_FILES['image']['name'][$name];
if(move_uploaded_file($sourcePath,$targetPath)) {
}
}
}
}
echo json_encode(array('st'=>1, 'msg' => 'Successfully Submiited'));
}
}
else
{
$this->load->view('myviews/myview2');
}
}
}
**//library file -- path will be [application/libraries/MY_Form_validation.php]**
<?php
/**
*
* Enter description here ...
* #return CI_Controller
*/
class MY_Form_validation extends CI_Form_validation
{
public function error_array()
{
return $this->_error_array;
}
}

Related

Do form validation with jquery ajax in codeigniter

How can i do form validation in codeigniter if i don't want to refresh the page?
Basically i do this:
$config = array(
array(
'field' => 'c_name',
'label' => 'Name',
'rules' => 'trim|required'
),
array(
'field' => 'c_job',
'label' => 'Job',
'rules' => 'trim|required',
)
);
$this->form_validation->set_rules($config);
if($this->form_validation->run() == true)
{
$this->load->model('model');
//.....
}
else{
$this->load->view('view');
}
But if i send data with ajax and the page doesn't refresh, How can i do form validation?
Edit:
Thanks # Amra Kojon. That's good and works but the new problem is this:
if ($this->form_validation->run() == FALSE) {
echo validation_errors();
}
else {
//echo 'hi';
$value = $this->input->post('value');
$values = array(
'c_name' => $value['c_name'],
'c_job'=> $value['c_job'],
'c_address'=> $value['c_address'],
'c_phone'=> $value['c_phone'],
'c_mail'=> $value['c_mail'],
'c_state'=> $value['c_state'],
'c_intrest'=> $value['c_intrest'],
'c_added_info'=> $value['c_added_info']
);
$add = $this->customers_model->add_customer($values);
echo $add;
}
If i just say echo "something" in the else part, It works and if the validation were OK, It echo hi but if i write theme in database (Which the value array has data and in not ajax way, it insert date), It doesn't work and the else part isn't working!!!
If you gave your JS- jquery Ajax code it would more efficient to understand your problem.. Don't worry! Try my following instruction...
Get get form value and pass to form as
$(document).ready(function(){
var dataString = $("#FormId").serialize();
var url="ControllerName/MethodName"
$.ajax({
type:"POST",
url:""+url,
data:dataString,
success:function (data) {
alert(data);
}
});
})
Controller :
Load library form_validation in construct as ...
$this->load->library('form_validation');
$this->load->helper('form');
Now write your controller as ...
function MethodName {
$this->form_validation->set_error_delimiters('', '');
$this->form_validation->set_rules('fname','First Name', 'required');
$this->form_validation->set_rules('lname','Last Name', 'required');
$this->form_validation->set_rules('email','Email Address','required|valid_email|is_unique[sec_users.email]');
if ($this->form_validation->run() == FALSE) {
echo validation_errors();
}
else {
// To who are you wanting with input value such to insert as
$data['frist_name']=$this->input->post('fname');
$data['last_name']=$this->input->post('lname');
$data['user_name']=$this->input->post('email');
// Then pass $data to Modal to insert bla bla!!
}
}
I know your question is a year old but you can use this for the latest bootstrap with codeigniter
<?php
class Yourcontroller extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
}
public function index() {
$this->load->view('template/register');
}
public function validate() {
$json = array();
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[5]');
$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'required|matches[password]');
$this->form_validation->set_rules('code', 'Login Code', 'required|numeric|min_length[4]||max_length[8]');
$this->form_validation->set_message('required', 'You missed the input {field}!');
if (!$this->form_validation->run()) {
$json = array(
'username' => form_error('username', '<p class="mt-3 text-danger">', '</p>'),
'email' => form_error('email', '<p class="mt-3 text-danger">', '</p>'),
'password' => form_error('password', '<p class="mt-3 text-danger">', '</p>'),
'confirm_password' => form_error('confirm_password', '<p class="mt-3 text-danger">', '</p>'),
'code' => form_error('code', '<p class="mt-3 text-danger">', '</p>')
);
}
$this->output
->set_content_type('application/json')
->set_output(json_encode($json));
}
}
Ajax Script
<script type="text/javascript">
$( document ).ready(function() {
$('#error').html(" ");
$('#form-submit-button').on('click', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url('yourcontroller/validate');?>",
data: $("#form").serialize(),
dataType: "json",
success: function(data){
$.each(data, function(key, value) {
$('#input-' + key).addClass('is-invalid');
$('#input-' + key).parents('.form-group').find('#error').html(value);
});
}
});
});
$('#form input').on('keyup', function () {
$(this).removeClass('is-invalid').addClass('is-valid');
$(this).parents('.form-group').find('#error').html(" ");
});
});
</script>
Full View Code
<div class="container">
<div class="row">
<div class="col-sm-6 ml-auto mr-auto m-auto">
<div class="card mt-5">
<h5 class="card-header"></h5>
<div class="card-body">
<?php echo form_open('agent/register', array('id' => 'form', 'role' => 'form'));?>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<?php echo form_input('username', '', array('class' => 'form-control', 'placeholder' => 'Enter Agent Username', 'id' => 'input-username'));?>
<div id="error"></div>
</div>
<hr/>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<?php echo form_input('email', '', array('class' => 'form-control', 'placeholder' => 'Enter Agent Email', 'id' => 'input-email'));?>
<div id="error"></div>
</div>
<hr/>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<?php echo form_password('password', '', array('class' => 'form-control', 'placeholder' => 'Enter Password', 'id' => 'input-password'));?>
<div id="error"></div>
</div>
<hr/>
</div>
<div class="col-sm-6">
<div class="form-group">
<?php echo form_password('confirm_password', '', array('class' => 'form-control', 'placeholder' => 'Enter Confirm Password', 'id' => 'input-confirm_password'));?>
<div id="error"></div>
</div>
<hr/>
</div>
</div>
<hr/>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<button type="button" class="btn btn-block btn-dark" id="form-submit-button">Register Agent</button>
</div>
</div>
</div>
<?php echo form_close();?>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$( document ).ready(function() {
$('#error').html(" ");
$('#form-submit-button').on('click', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url('yourcontroller/validate');?>",
data: $("#form").serialize(),
dataType: "json",
success: function(data){
$.each(data, function(key, value) {
$('#input-' + key).addClass('is-invalid');
$('#input-' + key).parents('.form-group').find('#error').html(value);
});
}
});
});
$('#agent-register-form input').on('keyup', function () {
$(this).removeClass('is-invalid').addClass('is-valid');
$(this).parents('.form-group').find('#error').html(" ");
});
});
</script>
If you are aware about passing data with ajax, then the work flow is as follows.
1) Send form data through ajax to your controller.
2) Do form validation as of now.
3) If success then "echo" value 1
4) If failure, echo value 0
So that using the value in echo, you can determine whether the validation fails or not. I can give you an example if you need
Sample ajax code
$('#form').on('submit', function(e){
e.preventDefault();
var data = $(this).serialize();
$.ajax({
url: 'your url',
type: 'POST',
data: data,
success: function(data){
if(data == 1){
$('#form')[0].reset();
alret('success');
}
else if(data == 0){
alret('failed');
}
},
error: function(){
alert('error');
}
});
});
Create MY_Form_validation in libraries folder
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation {
private $json = array();
private $opts = array();
function get_json($extra_array = array(),$error_array=array())
{
if(count($extra_array)) {
foreach($extra_array as $addition_key=>$addition_value) {
$this->json[$addition_key] = $addition_value;
}
}
$this->json['options'] = $this->opts;
if(!empty($error_array)){
foreach($error_array AS $key => $row)
$error[] = array('field' => $key, 'error' => $row);
}
foreach($this->_error_array AS $key => $row)
$error[] = array('field' => $key, 'error' => $row);
if(isset($error)) {
$this->json['status'] = 'error';
$this->json['errorfields'] = $error;
} else {
$this->json['status'] = 'success';
}
return json_encode($this->json);
}
}
Call this function in controller if validation failed:
echo $this->form_validation->get_json();
You get the response with form fieldname and errormessage
Example:
{"options":[],"status":"error","errorfields":[{"field":"email","error":"The Mobile Number\/Email\/Username field is required."},{"field":"password","error":"The Password field is required."}]}
Try this is my working (Codeigniter 3.0) basic example to achieve what you want do
include filename.js in your view
document.getElementById("yourForm").reset();
$(document).ready( function() {
var yourForm = $('#yourForm');
yourForm.submit( function(event) {
event.preventDefault();
$.ajax( {
type: 'POST',
url: yourForm.attr( 'action' ),
data: yourForm.serialize(),
success: function(data) {
if (data.code == '200') {
$('#message').html(data.message);
document.getElementById("yourForm").reset();
}
},
error: function(data) {
var response = data.responseText;
var obj = jQuery.parseJSON(response);
if (obj.code == '500') {
var i;
for (i = 0; i < obj.field.length; i++) {
name = obj.field[i];
$('.label-'+name).addClass('label-error');
errors = JSON.stringify(obj.validation);
validate = jQuery.parseJSON(errors);
$('.helper-'+name).html(validate[name]);
}
}
}
} );
} );
} );
view HTML form example
In this example in am using className you can use id as well change filename.js file accordingly
<form id="yourForm" action="base_url/controller/function_name" action="POST">
// Important text after className "label-" & "helper-" must be input name
<label class="label-firstName">Name</label>
<input type="text" name="firstName" />
<span class="helper-firstName"></span>
</form>
<div id="message"></div>
controller PHP code
public function function_name()
{
if(!empty($_POST)) {
$this->load->library('form_validation');
$this->form_validation->set_rules('firstName','First Name','required|max_length[16]');
if($this->form_validation->run())
{
$params = array(
'firstName' => $this->input->post('firstName'),
);
// Model returning $data['newRecord'] with $params and insertId
$data['newRecord'] = $this->Record_model->newRecord($params);
$reply = array();
$reply['code'] = 200;
$reply['record'] = array(
'insertId' => $data['newRecord']['insertId'],
'firstName' => $data['newRecord']['firstName']
);
$reply['message'] = 'Hello, ' .$data['newRecord']['firstName']. ' - We have received your message. ' .$data['newRecord']['insertId']. ' is your reference ID, for this communication.';
header('Content-Type: application/json; charset=UTF-8');
print json_encode($reply);
}
else {
$validation = $this->form_validation->error_array();
$field = array();
foreach($validation as $key => $value) {
array_push($field,$key);
}
$reply = array(
'code' => 500,
'field' => $field,
'validation' => $validation,
'message' => 'Submission failed due to validation error.'
);
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Problem', true, 500);
header('Content-Type: application/json; charset=UTF-8');
print json_encode($reply);
}
}
else {
$reply = array();
$reply['code'] = 403;
$reply['message'] = 'No Direct Access Allowed.';
header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden', true, 403);
header('Content-Type: application/json; charset=UTF-8');
print json_encode($reply);
}
}
If using ajax,...you can't use form_validation library
So you can validate on client side using jquery ...and on server side should use if statement to check submitted data

How to AJAX work

I am new in AJAX. but I am trying to learn How this is working.
I am using symfony2 with fos user bundle and I want implement AJAX to my login form.
so I was doing this :
login.html.twig
<script>
$('#_submit').click(function(e){
e.preventDefault();
$.ajax({
type : $('form').attr( 'method' ),
url : $('form').attr( 'action' ),
data : $('form').serialize(),
success : function(data, status, object) {
if (data.sucess == false) {
$('.tab-1').prepend('<div />').html(data.message);
} else {
window.location.href = data.targetUrl;
}
}
});
</script>
<div id="tab-1" class="login_form">
<form action="{{ path("fos_user_security_check") }}" role="form" method="post">
<label for="username"><strong>User Name / Email Address</strong>
<input type="text" id="username" name="_username" value="{{ last_username }}" required="required" />
</label>
<label for="password"><strong>Password</strong>
<input type="password" id="password" name="_password" required="required" />
</label>
<label for="password"><strong>Remember Me</strong>
<input type="checkbox" id="remember_me" name="_remember_me" value="on" />
</label>
<input type="submit" class="submitBut" id="_submit" name="_submit" value="{{ 'security.login.submit'|trans({}, 'FOSUserBundle') }}" />
</form>
</div>
And when submit then go this file :-
<?php
namespace XXXX\UserBundle\Handler;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Router;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Translation\MessageSelector;
class AuthenticationHandler implements AuthenticationSuccessHandlerInterface, AuthenticationFailureHandlerInterface
{
protected $router;
protected $security;
protected $userManager;
protected $service_container;
public function __construct(RouterInterface $router, SecurityContext $security, $userManager, $service_container)
{
$this->router = $router;
$this->security = $security;
$this->userManager = $userManager;
$this->service_container = $service_container;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token) {
if ($request->isXmlHttpRequest()) {
$result = array('success' => true);
$response = new Response(json_encode($result));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
else {
// Create a flash message with the authentication error message
$request->getSession()->getFlashBag()->set('error', $exception->getMessage());
$url = $this->router->generate('fos_user_security_login');
return new RedirectResponse($url);
}
return new RedirectResponse($this->router->generate('anag_new'));
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception) {
$translator = new Translator('fr_FR');
//$result = array(
// 'success' => false,
// 'function' => 'onAuthenticationFailure',
// 'error' => true,
// 'message' => $this->translator->trans($exception->getMessage(), array(), 'FOSUserBundle')
//);
$result = array('success' => false);
$response = new Response(json_encode($result));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
When submit the form then show me in login_check url:
{"success":false}
But I want when result false then return same form where I was trying to login(I mean same popup div)?
What's wrong my code ajax or action return ?
Or I am return correct ?
window.location will reload the entire page. That's not the desired result I suppose since you are using AJAX ( the hole point of AJAX is to not reload the page) instead you could display an error message if the login is not successful.
I suggest you add an error div in your html form
<div class='error' style="display:none" > ooups an erro occured </div>
and then in the ajax call just show it or add a significant message error :
if (data.sucess == false) {
$('.tab-1').prepend('<div />').html(data.message);
} else {
$('.error').show();
}

How do I get domPDF to display my codeigniter view correctly

I feel there is a small step that I am missing that apparently everyone on the other related questions understands.
I have created a simple CI 2 view, controller and model, shown below:
I have installed dompdf into the helpers folder like so:
applications/helpers/dompdf
applications/helpers/dompdf/dompdf_help.php
What I want to happen is when user clicks the submit button on the view page, send form data to the db, then get a pdf of that filled in form.
Between getting underdefined var errors or nothing at all, except for the data going to db, I can't see what I am missing.
Could some please guide me? What am I not getting here?
View
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>test pdf</title>
</head>
<body>
<?php // Change the css classes to suit your needs
$attributes = array('class' => '', 'id' => '');
echo form_open('quicksubmit', $attributes); ?>
<p>
<label for="title">Title <span class="required">*</span></label>
<?php echo form_error('title'); ?>
<?php // Change the values in this array to populate your dropdown as required ?>
<?php $options = array(
'' => 'Please Select',
'Mrs' => 'Mrs',
'Miss' => 'Miss',
'Ms' => 'Ms',
'Mr' => 'Mr',
); ?>
<br /><?php echo form_dropdown('title', $options, set_value('title'))?>
</p>
<p>
<label for="first_name">First Name</label>
<?php echo form_error('first_name'); ?>
<br /><input id="first_name" type="text" name="first_name" maxlength="100" value="<?php echo set_value('first_name'); ?>" />
</p>
<p>
<label for="last_name">Last Name <span class="required">*</span></label>
<?php echo form_error('last_name'); ?>
<br /><input id="last_name" type="text" name="last_name" maxlength="100" value="<?php echo set_value('last_name'); ?>" />
</p>
<p>
<label for="branch">Branch</label>
<?php echo form_error('branch'); ?>
<?php // Change the values in this array to populate your dropdown as required ?>
<?php $options = array(
'' => 'Please Select',
'Branch 1' => 'Branch One',
'Branch 2' => 'Branch Two',
); ?>
<br /><?php echo form_dropdown('branch', $options, set_value('branch'))?>
</p>
<p>
<label for="zip">Zip</label>
<?php echo form_error('zip'); ?>
<br /><input id="zip" type="text" name="zip" maxlength="7" value="<?php echo set_value('zip'); ?>" />
</p>
<p>
<?php echo form_submit( 'submit', 'Submit'); ?>
</p>
<?php echo form_close(); ?>
</body>
</html>
Controller
<?php
class Quicksubmit extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->library('form_validation');
$this->load->database();
$this->load->helper('form');
$this->load->helper('url');
$this->load->model('quicksubmit_model');
}
function index()
{
$this->form_validation->set_rules('title', 'Title', 'required|trim|xss_clean|max_length[50]');
$this->form_validation->set_rules('first_name', 'First Name', 'trim|xss_clean|max_length[100]');
$this->form_validation->set_rules('last_name', 'Last Name', 'required|trim|xss_clean|max_length[100]');
$this->form_validation->set_rules('branch', 'Branch', 'trim|xss_clean|max_length[100]');
$this->form_validation->set_rules('zip', 'Zip', 'trim|xss_clean|is_numeric|max_length[7]');
$this->form_validation->set_error_delimiters('<br /><span class="error">', '</span>');
if ($this->form_validation->run() == FALSE) // validation hasn't been passed
{
$this->load->view('quicksubmit_view');
}
else // passed validation proceed to post success logic
{
// build array for the model
$this->pdf($output);
$form_data = array(
'title' => set_value('title'),
'first_name' => set_value('first_name'),
'last_name' => set_value('last_name'),
'branch' => set_value('branch'),
'zip' => set_value('zip')
);
// run insert model to write data to db
if ($this->quicksubmit_model->SaveForm($form_data) == TRUE) // the information has therefore been successfully saved in the db
{
redirect('quicksubmit/success'); // or whatever logic needs to occur
}
else
{
echo 'An error occurred saving your information. Please try again later';
// Or whatever error handling is necessary
}
}
}
function success()
{
redirect(base_url(),'refresh');
/*echo 'this form has been successfully submitted with all validation being passed. All messages or logic here. Please note
sessions have not been used and would need to be added in to suit your app';*/
}
function pdf()
{
$this->load->helper(array('dompdf', 'file'));
// page info here, db calls, etc.
$html = $this->load->view('quicksubmit_view', $data, true);
pdf_create($html, 'filename');
/*or
$data = pdf_create($html, '', false);
write_file('name', $data);*/
//if you want to write it to disk and/or send it as an attachment
}
}
?>
Model
<?php
class Quicksubmit_model extends CI_Model {
function __construct()
{
parent::__construct();
}
// --------------------------------------------------------------------
/**
* function SaveForm()
*
* insert form data
* #param $form_data - array
* #return Bool - TRUE or FALSE
*/
function SaveForm($form_data)
{
$this->db->insert('quicksubmit', $form_data);
if ($this->db->affected_rows() == '1')
{
return TRUE;
}
return FALSE;
}
}
?>
dompdf_help.php file
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
function pdf_create($html, $filename='', $stream=TRUE)
{
require_once("dompdf/dompdf_config.inc.php");
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
if ($stream) {
$dompdf->stream($filename.".pdf");
} else {
return $dompdf->output();
}
}
?>
you were nearly there!
It is probably better to store dompdf in the third_party folder, and it is not a code igniter helper. - see the path i store it in in the constructor. Then it is always available.
Also, it is probably better to do the 'work' of the program in the model, so this includes making PDFs etc.
don't use a ?> at the end of your code.
i modded your code to work, and verified it did work. it simply saves a file named tmp/name.pdf. I am sure you can work out the rest. i did comment out the database loader because that wasn't needed for me to test the code.
see enc.
<?php
class Quicksubmit extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->library('form_validation');
//$this->load->database();
$this->load->helper('form');
$this->load->helper('url');
$this->load->helper('file');
$this->load->model('quicksubmit_model');
global $_dompdf_show_warnings;global $_dompdf_debug;global $_DOMPDF_DEBUG_TYPES;global $_dompdf_warnings;$_dompdf_show_warnings = FALSE;
require_once(realpath(APPPATH."third_party/dompdf")."/dompdf_config.inc.php"); // remember that the constant DOMPDF_TEMP_DIR may need to be changed.
spl_autoload_register('DOMPDF_autoload');
}
function index()
{
$this->form_validation->set_rules('title', 'Title', 'required|trim|xss_clean|max_length[50]');
$this->form_validation->set_rules('first_name', 'First Name', 'trim|xss_clean|max_length[100]');
$this->form_validation->set_rules('last_name', 'Last Name', 'required|trim|xss_clean|max_length[100]');
$this->form_validation->set_rules('branch', 'Branch', 'trim|xss_clean|max_length[100]');
$this->form_validation->set_rules('zip', 'Zip', 'trim|xss_clean|is_numeric|max_length[7]');
$this->form_validation->set_error_delimiters('<br /><span class="error">', '</span>');
if ($this->form_validation->run() == FALSE) // validation hasn't been passed
{
$this->load->view('quicksubmit_view');
}
else // passed validation proceed to post success logic
{
// build array for the model
$form_data = array(
'title' => set_value('title'),
'first_name' => set_value('first_name'),
'last_name' => set_value('last_name'),
'branch' => set_value('branch'),
'zip' => set_value('zip')
);
$this->pdf($form_data);
// run insert model to write data to db
if ($this->quicksubmit_model->SaveForm($form_data) == TRUE) // the information has therefore been successfully saved in the db
{
redirect('quicksubmit/success'); // or whatever logic needs to occur
}
else
{
echo 'An error occurred saving your information. Please try again later';
// Or whatever error handling is necessary
}
}
}
function success()
{
redirect(base_url(),'refresh');
/*echo 'this form has been successfully submitted with all validation being passed. All messages or logic here. Please note
sessions have not been used and would need to be added in to suit your app';*/
}
function pdf($data)
{
$dompdf = new DOMPDF();
$html = $this->load->view('quicksubmit_view', $data, true);
$dompdf->set_paper('a4','portrait');
$dompdf->load_html($html);
$dompdf->render();
$pdf = $dompdf->output();
write_file('tmp/name.pdf', $pdf);
}
}

Form submission using AJAX and handling response in Wordpress Website

I have a wordpress website. I have made a contact form and it is POSTed by AJAX.
Here's the code:
<script type="text/javascript">
jQuery(document).ready(function(){
$("#error_box").hide();
$('#contact_form').submit(function(e){
// prevent the form from submitting normally
e.preventDefault();
var na=$("#1").val();
var email2=$("#2").val();
var subject2 = $("#3").val();
var message2 = $("#4").val();
var mydata = "pn2="+na+"&email="+email2+"&subject="+subject2+"&msg="+message2;
alert(mydata);
$("#contact_form").css({"opacity":"0.1"});
$.ajax ({
type: 'POST',
url: $(this).attr.action, // Relative paths work fine
data: mydata,
success: function(){
$("#contact_form").css({"opacity":"1"});
$('#error_box').fadeIn('fast').css({"height": "auto"});
}
});
});
});
</script>
When the form is submitted, I want the error box (#error_box) to display a message according to the data submitted, for example if one of the fields is empty it should display an error, or display a success message if the processing is successful and the form has been mailed. Is there any way I can do this?
[UPDATE]
Here's my contact-form.php file(the action)
<?php if(isset($_POST['pn2']) && isset($_POST['email']) && isset($_POST['subject']) && isset($_POST['msg']))
{
if(empty($_POST['pn2']) || empty($_POST['email']) || empty($_POST['subject']) || empty($_POST['msg'])){
echo 'EMPTY ERROR';
}
else
{
$name = $_POST['pn2'];
$email = $_POST['email'];
$subj = $_POST['subject'];
$msg = $_POST['msg'];
$to = "ankushverma61#gmail.com";
$mail_cont = "FROM: $person_name. \n Email: $email. \n Msg: $msg";
echo "success";
mail($recipient, $subj, $mail_cont) or die("UNABLE TO SEND!!!");
}
}
?>
Form submission using Ajax call
Contact Form
<form action="#" id="contactForm" method="post">
<input class="require" type="text" placeholder="First Name" name="firstName">
<span class="fieldError"></span>
<input class="require" type="text" placeholder="Last Name" name="lastName">
<span class="fieldError"></span>
.
.
.
<input type="submit" value="Submit">
</form>
client side validation with ajax call
jQuery('#contactForm').submit(ajaxSubmit);
function ajaxSubmit(){
var newContactForm = jQuery(this).serialize();
var flag = 0;
jQuery('.require', '#contactForm').each(function(){
var inputVal = jQuery(this).val();
if(jQuery.trim(inputVal) === ""){
flag = 1;
jQuery(this).next().html("Can't be blank");
jQuery(this).next().show();
}
else{
jQuery(this).next().hide();
}
});
if(flag){
return false;
}
jQuery.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php?action=contactForm",
data: newContactForm,
success:function(data){
jQuery(':input','#contactForm')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
jQuery("#feedback").html(data);
jQuery("#feedback").fadeOut(10000);
},
error: function(errorThrown){
alert(errorThrown);
}
});
return false;
}
store form data in db and send mail
add the following code in functions.php
wp_enqueue_script('jquery');
add_action('wp_ajax_addContactForm', 'addContactForm');
add_action('wp_ajax_nopriv_addContactForm', 'addContactForm');
function addContactForm(){
global $wpdb;
$first_name = $_POST['firstName']; $last_name = $_POST['lastName'];
$email = $_POST['email'];
.
.
.
if($wpdb->insert('table_name',array(
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $email,
.
.
.
))===FALSE){
echo "Error";
}
else {
$headers = 'From: xyz <xyz#xyz.com>';
$subject = "Thank you";
$body = "<p>Thank you</p><p>.........</p>";
wp_mail( $email, $subject, $body, $headers);
echo "<div class='success'>Thank you for filling out your information, we will be in contact shortly.</div>";
}
exit;
}
You should use:
$.ajax ({
type: 'POST',
url: $(this).attr.action,
data: mydata,
success: function(response) { // here you receive response from you serverside
$("#contact_form").css({"opacity":"1"});
$('#error_box').html(response).fadeIn('fast').css({"height": "auto"});
}
});
Your server action url: $(this).attr.action, should return message which be inserted in #error_box
First create form like this
<p class="register-message"></p>
<form action="#" method="POST" name="testregister" class="register-form">
<fieldset>
<label><i class="fa fa-file-text-o"></i> Register Form</label>
<input type="text" name="firstname" placeholder="Username" id="firstname">
<p id="firstname-error" style="display:none">Firstname Must be Enter</p>
<input type="email" name="email" placeholder="Email address" id="email">
<p id="email-error" style="display:none">Email Must Be Enter</p>
<input type="submit" class="button" id="test" value="Register">
</fieldset>
</form>
then bind the click and send ajax call
<script type="text/javascript">
jQuery('#test').on('click', function(e) {
e.preventDefault();
var firstname = jQuery('#firstname').val();
var email = jQuery('#email').val();
if (firstname == "") {
jQuery('#firstname-error').show();
return false;
} else {
jQuery('#firstname-error').hide();
}
if (email == "") {
jQuery('#email-error').show();
return false;
} else {
jQuery('#email-error').hide();
}
jQuery.ajax({
type: "POST",
dataType: 'json',
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: {
action: "test", // redirect function in function.php
firstname: firstname,
email: email
},
success: function(results) {
//console.log(results);
if (results == "1") {
jQuery('.register-message').text("Email already exist");
} else {
jQuery('.register-message').text("Register successfu");
}
},
error: function(results) {}
});
});
</script>
In function.php add the below code to insert data in table
<?php
//
add_action('wp_ajax_test', 'test', 0);
add_action('wp_ajax_nopriv_test', 'test');
function test()
{
$firstname = stripcslashes($_POST['firstname']);
$email = stripcslashes($_POST['email']);
global $wpdb;
$q = $wpdb->prepare("SELECT * FROM wp_test WHERE email='" . $email . "' ");
$res = $wpdb->get_results($q);
if (count($res) > 0) {
echo "1";
} else {
$user_data = array(
'firstname' => $firstname,
'email' => $email
);
$tablename = $wpdb->prefix . 'test';
$user_id = $wpdb->insert($tablename, $user_data);
echo "0";
}
die;
}

CodeIgniter show errors individually next to form field with ajax callback

I'd made a form using CI and have a native form_validation() library to validate each fields input, I using jQuery post to callback the input to check whether each fields is valid, how if I want each error to populate into form_error() next to each field instead of validation_errors()?
Please refer to below:
view:
<script>
$("#btnregister").click(function() {
var parameters = $("#reg_form").serialize();
$.post(baseurl+'pages/registration', parameters, function(data) {
if(data == "ok") {
//show success message
}else{
$("#error").html(data);
}
}, "html");
});
</script>
<div id="error"></div>
<form id="reg_form" method="post">
<p>
<label for="reg_username">Username</label><br />
<input type="text" id="reg_username" name="reg_username" value="<?php echo set_value('reg_username'); ?>">
<?php echo form_error('reg_username'); ?>
</p>
<p>
<label for="reg_email">Email</label><br />
<input type="text" id="reg_email" name="reg_email" value="<?php echo set_value('reg_email'); ?>">
<?php echo form_error('reg_email'); ?>
</p>
<p><input type="button" id="btnregister" value="Register"></p>
</form>
</div>
Controller:
public function registration(){
$this->load->library('form_validation');
$this->form_validation->set_rules('reg_username', 'Username', 'trim|required|min_length[4]|max_length[15]|xss_clean|is_unique[users.username]');
$this->form_validation->set_rules('reg_email', 'Email', 'trim|required|valid_email|is_unique[users.email]');
if($this->form_validation->run() == FALSE){
echo validation_errors();
}else{
// insert to db
echo "ok";
}
}
Thanks for help.
You'll have to build your own error array. It would be nice if we could access the
Form_validation's $_error_array but unfortunately it's protected and there's no access method for it.
I'm going to change your controller to output a json response to make this easier:
public function registration()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('reg_username', 'Username', 'trim|required|min_length[4]|max_length[15]|xss_clean|is_unique[users.username]');
$this->form_validation->set_rules('reg_email', 'Email', 'trim|required|valid_email|is_unique[users.email]');
if ($this->form_validation->run())
{
$response['status'] = TRUE;
}
else
{
$errors = array();
// Loop through $_POST and get the keys
foreach ($this->input->post() as $key => $value)
{
// Add the error message for this field
$errors[$key] = form_error($key);
}
$response['errors'] = array_filter($errors); // Some might be empty
$response['status'] = FALSE;
}
// You can use the Output class here too
header('Content-type: application/json');
exit(json_encode($response));
}
Now your ajax success callback can read the status and errors keys of the response. You can loop through data.errors and add each one to the input field:
$("#reg_form").submit(function() {
var form = $(this);
$.post(baseurl+'pages/registration', form.serialize(), function(data) {
if (data.status == true) {
//show success message
}else{
$.each(data.errors, function(key, val) {
$('[name="'+ key +'"]', form).after(val);
});​
}
}, "json");
});
Another easy way is to post the form to itself, and have your ajax response reload the entire form - that way the messages and validation filters will be taken care of server-side.

Resources