form validation using ajax in codeigniter - php

In this when i submit my form it shows errors first then reload the page and go to index page.. but i want is show only error message not reload page after.. here my controller is
class User extends CI_Controller {
public function index()
{
$this->load->view('index');
}
public function error()
{
/* Load form helper */
$this->load->helper(array('form'));
/* Load form validation library */
$this->load->library('form_validation');
/* Set validation rule for name field in the form */
$form_data = array('brand_name' => $this->input->post('brand_name'), 'your_name ' => $this->input->post('your_name'), 'mobile_no' => $this->input->post('Mobile No.'));
if($this->form_validation->run($form_data) == FALSE )
{
echo validation_errors();
}
else
{
$this->load->view('submit');
}
}
}
and my view file named index.php is
<script type="text/javascript">
$(document).ready(function(){
$('#get').click(function(){
$.post("<? base_url() . 'user/error' ?>",
$("form").serialize(),
function(result) {
$("#error_message").html(result).appendTo("form");
},"html");
});
});
</script>
<form role="form" action="" class="form-inline" name="form" method="POST" id >
<div id="error_message" style="color:red"></div>
<?php echo form_open('form'); ?>
<div class="col-md-3">
</div>
<div class="col-md-2">
<div class="form-group">
<input type="text" class="form-control" placeholder="Brand Name" name="brand_name" onfocus="this.placeholder = ''" onblur="this.placeholder='Brand Name'">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<input type="text" class="form-control" placeholder="Your Name" name="your_name" onfocus="this.placeholder = ''" onblur="this.placeholder='Your Name'">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<input type="text" class="form-control" placeholder="Mobile No" name="mobile_no" onfocus="this.placeholder = ''" onblur="this.placeholder='Mobile No'">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<input type="submit" id="get" class="btn btn-success" name="submit" value="Proceed" ></input>
</div>
</div>
<div class="col-md-3">
</div>
</form>
i just want it shows error message only not reload page after please help... thanks in advance

You are trying to post form in AJAX so you will need to set the form data manually
Tested with CI 2
$form_data = array('brand_name' => $this->input->post('brand_name'), 'your_name ' => $this->input->post('your_name')); // other fields as required for validations
And validation for the same would be
if($this->form_validation->run($form_data) == TRUE ){
//validation passed
}else{
//validation fail
}
For CodeIgniter 3, as the Online documentation mentions try https://www.codeigniter.com/userguide3/libraries/form_validation.html#validating-an-array-other-than-post
Validating an Array (other than $_POST)
Sometimes you may want to validate an array that does not originate from $_POST data.
In this case, you can specify the array to be validated:
$data = array(
'username' => 'johndoe',
'password' => 'mypassword',
'passconf' => 'mypassword'
);
$this->form_validation->set_data($data);

Related

how to show warning of empty field on form validation?

these are my code for form validation :
<form action="<?php echo base_url().'data_laporan/tambah_aksi';?>"method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Jenis Laporan</label>
<select class="form-control" name="jenis_laporan">
<option>Penemuan hewan</option>
<option>Kehilangan Hewan</option>
</select>
</div>
<div class="form-group">
<label>Jenis Hewan</label>
<input type="text" name="jenis_hewan" class="form-control">
</div>
<div class="form-group">
<label>Lokasi</label>
<input type="text" name="lokasi" class="form-control">
</div>
<div class="form-group">
<label>Deskripsi</label>
<input type="text" name="deskripsi" class="form-control">
</div>
<div class="form-group">
<label>Nama Pelapor</label>
<input type="text" name="nama_pelapor" class="form-control">
</div>
<div class="form-group">
<label>No Hp</label>
<input type="text" name="no_hp" class="form-control">
</div>
<div class="form-group">
<label>Gambar Hewan</label>
<input type="file" name="gambar" class="form-control">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
</form>
i want to show a simple warning when i click "Save Changes" as a submit button like this :
image for example warning
and these are my code for tambah_aksi() function :
public function tambah_aksi()
{
$jenis_laporan = $this->input->post('jenis_laporan');
$jenis_hewan = $this->input->post('jenis_hewan');
$deskripsi = $this->input->post('deskripsi');
$lokasi = $this->input->post('lokasi');
$nama_pelapor = $this->input->post('nama_pelapor');
$no_hp = $this->input->post('no_hp');
$gambar = $_FILES['gambar']['name'];
if ($gambar = '') {} else{
$config ['upload_path'] = './upload';
$config ['allowed_types'] = 'jpg|jpeg|png|gif';
$this->load->library('upload', $config);
if(!$this->upload->do_upload('gambar')){
echo "Gambar gagal di Upload";
}else{
$gambar=$this->upload->data('file_name');
}
}
$data = array (
'jenis_laporan' => $jenis_laporan,
'jenis_hewan' => $jenis_hewan,
'deskripsi' => $deskripsi,
'lokasi' => $lokasi,
'nama_pelapor' => $nama_pelapor,
'no_hp' => $no_hp,
'gambar' => $gambar,
);
$this->model_laporan->tambah_aksi($data, 'tb_laporan');
redirect('data_laporan/index');
}
i tried using if-else form validation run checking but it does not goes well, could you please help me to fix this with another way or the efficient way of if-else checking?
You can do this many ways
Via codeigniter 3.x
then first load form validation library in controller function and set rules and place holder for showing errors in view file. See for reference
https://codeigniter.com/userguide3/libraries/form_validation.html#the-controller
https://codeigniter.com/userguide3/libraries/form_validation.html#showing-errors-individually
Via HTML
You can simply do this by adding required attribute to all html elements which are required, browser will show warning automatically after clicking on submit button for required fields. see example for input html element
<input type="text" name="nama_pelapor" required class="form-control">
See for dropdown
<select class="form-control" required name="jenis_laporan">
<option>Penemuan hewan</option>
<option>Kehilangan Hewan</option>
</select>
Via Jquery
If you want to customize error messages then you do this via your own code in jquery or jquery validator library. See this documentation for jquery validation
https://jqueryvalidation.org/validate/
Comparison operator should be double == not single =. Edit your line of code to this.
if ($gambar =='') {} else{

$this->validate causes "Failed to load response data"

I have the following external form:
<form method="POST" action="http://infused.local/leads/post">
<div class="form-group">
<label>first_name</label>
<input type="text" name="first_name" class="form-control">
</div>
<div class="form-group">
<label>last_name</label>
<input type="text" name="last_name" class="form-control">
</div>
<div class="form-group">
<label>email</label>
<input type="text" name="email" class="form-control">
</div>
<div class="form-group">
<label>postal_code</label>
<input type="text" name="postal_code" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
Which points to the following controller method:
public function post()
{
$this->validate(request(), [
'email' => 'required|email',
]);
echo 'hello';
}
Via this route:
Route::post('leads/post', 'LeadController#post');
I've disabled CSRF protection for the form route.
When I submit the form, I get "Failed to load response data" from
Chrome.
When I remove the $this->validate call, I get "hello".
Why is this not working?
You need to return JSON and you can use the helper function:
response()->json([
'message' => 'hello'
]);
Then in your JS:
console.log(response.message);
OK apparently the validate method just redirects you back to the previous page if there are errors, unless the response is expected to be JSON. Ended up using the Validator facade instead.
Edit: Thanks for the downvotes. This website is cancer.

How to get data from database table in codeigniter?

I need to get the data that has been stored in my database to print in my website.I want to input the user entered word and then store it in a table after that i want it to show on a page.I have already saved created a form that takes the user entered data and stores it in a table but have not been able to display the data.I want the data entered by the user be available in any file
Here is my View
<form class="form-horizontal"
action="<?php echo base_url() ?>index.php/submit/new_form_submit" method="post">
<fieldset>
<br>
<div class="form-group">
<label class="col-md-4 control-label" for="Title">Title</label>
<div class="col-md-4">
<input id="Title" name="Title" type="text" placeholder="" class="form-control input-md" required="">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="Price">Price</label>
<div class="col-md-4">
<input id="Price" name="Price" type="number" placeholder="" class="form-control input-md" required="">
</div>
</div>
<!-- Textarea -->
<div class="form-group">
<label class="col-md-4 control-label" for="textarea">Describe your product</label>
<div class="col-md-4">
<textarea class="form-control" id="textarea" name="textarea"></textarea>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="Link">Link to Live preview</label>
<div class="col-md-4">
<input id="Link" name="Link" type="url" placeholder="e.g http://www.example.com" class="form-control input-md" required="">
</div>
</div>
<!-- File Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="filebutton">Screenshot of your theme</label>
<div class="col-md-4">
<label for="file-input">
<!-- <div class="thumbnail">
<img src="<?/*= base_url() */?>Images/placeholder.jpg"/>
</div>-->
</label>
<input id="file-input" type="file"/>
</div>
</div>
<br>
<!-- Button (Double) -->
<div class="form-group">
<label class="col-md-4 control-label" for="button1id"></label>
<div class="col-md-8">
<button type="submit" class="btn btn-success">Save</button>
<a id="cancel" name="cancel" class="btn btn-danger" href="<?php echo base_url(); ?>index.php/home">
Cancel</a>
</div>
</fieldset>
Here is my Controller
<?php
session_start();
class Submit extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('security');
$this->load->helper('url');
$this->load->helper('form');
$this->load->model('Submit_Database');
$this->load->library('form_validation');
}
public function index()
{
$this->load->view('templates/header');
$this->load->view('submitf/submit');
$this->load->view('templates/footer');
}
public function new_form_submit()
{
$this->load->helper('url');
$this->form_validation->set_rules('Title', 'Title', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
$this->load->view('templates/header');
$this->load->view('pages/home');
$this->load->view('templates/footer');
} else {
$data = array(
'Title' => $this->input->post('Title'),
'Price' => $this->input->post('Price'),
'textarea' => $this->input->post('textarea'),
'Link' => $this->input->post('Link')
);
$result = $this->Submit_Database->submit_insert($data);
if ($result == TRUE) {
$this->load->view('templates/header');
$this->load->view('pages/about');
$this->load->view('templates/footer');
} else {
$this->load->view('templates/header');
$this->load->view('submitf/submit');
$this->load->view('templates/footer');
}
}
redirect('');
}
}
Here is my model
<?php
Class Submit_Database extends CI_Model
{
function __construct()
{
parent::__construct(); // construct the Model class
$this->load->database();
}
// Insert registration data in database
public function submit_insert($data)
{
// Query to insert data in database
$this->db->insert('submit', $data);
}
}
Any help would be much appreciated!
The logic is this:
You need a function in model to select from the database.
A function in controller to call the model function and load the view with the data.
And a view file to actually display the data.
You can use sessions in order to store the data in a session variable and access it in any file. You have to load the session library.

insert into form doesn't insert into table ? with codeigniter framework

database details:
dbtable : guests
dbcolumns : id (A_I), guestname, guestemail
when i submit a data it's only refresh the page and take no action i'm beginner please tell me where's the problem and why
i made insert form by basic php and i passed but with codeigniter maybe i'm not fully understood yet looks like my experience about 1% or 5% :D :D
Controller/Guests.php :
<?php
class Guests extends CI_Controller {
public function index($page = 'guests')
{
if ( ! file_exists(APPPATH.'/views/main/'.$page.'.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
$data['title'] = ucfirst($page);
$data['pagedesc'] = 'Guests List';
$this->load->view('include/header', $data);
$this->load->model('guests_model');
$data['records'] = $this->guests_model->getAll();
$this->load->view('main/guests', $data);
$this->load->view('include/footer', $data);
}
public function addnewguest($page = 'Add New Guest')
{
if ( ! file_exists(APPPATH.'/views/main/addnewguest.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
$data['title'] = ucfirst($page);
$data['pagedesc'] = 'Please Fill Informations Below';
$this->load->view('include/header', $data); // loaded the header
$this->load->model('guests_model'); // loaded the model
$this->load->view('main/addnewguest', $data); // loaded add new form
if($this->input->post('createnew')) { // if click add send information to addnewguestpost() function in the guest_model file
$this->guests_model->addnewguestfunc();
}
$this->load->view('include/footer', $data); // loaded the footer
}
}
views/main/addnewguest.php
<form class="form-horizontal" action="<?php echo site_url('guests/addnewguest'); ?>" method="post">
<div class="form-group">
<label for="guestname" class="col-sm-2 control-label">Guest Name</label>
<div class="col-sm-3">
<input type="text" name="guestname" class="form-control" id="guestname" placeholder="Guest Name ...">
</div>
</div>
<div class="form-group">
<label for="guestemail" class="col-sm-2 control-label">Guest Email</label>
<div class="col-sm-3">
<input type="text" name="guestemail" class="form-control" id="guestemail" placeholder="Guest Email ..">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default" name="createnew">Add</button>
</div>
</div>
</form>
models/guests_model.php
<?php
class Guests_model extends CI_Model {
public function getAll() {
$query = $this->db->get('guests');
if($query->num_rows() > 0){
return $query->result();
} else {
return FALSE;
}
}
public function addnewguestfunc() {
$data = array(
'guestname' => $this->input->post('guestname'),
'guestemail' => $this->input->post('guestemail')
);
$this->db->insert('guests', $data);
}
}
Solved !!
forgot change button to input because i copied it from bootstrap basic templates for practicing ..
views/main/addnewguest.php after change button to input :
<form class="form-horizontal" action="<?php echo site_url('guests/addnewguest'); ?>" method="post">
<div class="form-group">
<label for="guestname" class="col-sm-2 control-label">Guest Name</label>
<div class="col-sm-3">
<input type="text" name="guestname" class="form-control" id="guestname" placeholder="Guest Name ...">
</div>
</div>
<div class="form-group">
<label for="guestemail" class="col-sm-2 control-label">Guest Email</label>
<div class="col-sm-3">
<input type="text" name="guestemail" class="form-control" id="guestemail" placeholder="Guest Email ..">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" class="btn btn-default" name="createnew">Add</input>
</div>
</div>
</form>

Laravel 4 throwing MethodNotAllowedHttpException

I am making a simple registration form that then submits data to my database. However, the problem that I am running into is that the code that should submit the info to the database is not working.
Here's the form that I made using Twitter Bootstrap
<!DOCTYPE html>
<html>
<body>
<div class="modal-body">
<div class="well">
<div id="myTabContent" class="tab-content">
<div class="tab-pane active in" id="login">
<form method="POST" action='/adding_to_table' class="form-horizontal">
<fieldset>
<div id="legend">
<legend class="">Create Your Account</legend>
</div>
<div class="control-group">
<!-- Username -->
<label class="control-label" for="firstname">First Name</label>
<div class="controls">
<input type="text" id="first_name" name="firstname" placeholder="" class="input-xlarge">
</div>
</div>
<div class="control-group">
<!-- Username -->
<label class="control-label" for="lastname">Last Name</label>
<div class="controls">
<input type="text" id="last_name" name="lastname" placeholder="" class="input-xlarge">
</div>
</div>
<div class="control-group">
<!-- Username -->
<label class="control-label" for="email">E-mail</label>
<div class="controls">
<input type="text" id="e_mail" name="email" placeholder="" class="input-xlarge">
</div>
</div>
<div class="control-group">
<!-- Username -->
<label class="control-label" for="username">Username</label>
<div class="controls">
<input type="text" id="username" name="username" placeholder="" class="input-xlarge">
</div>
</div>
<div class="control-group">
<!-- Password-->
<label class="control-label" for="password">Password</label>
<div class="controls">
<input type="password" id="password" name="password" placeholder="" class="input-xlarge">
</div>
</div>
<div class="control-group">
<!-- Button -->
<div class="controls">
<button class="btn btn-primary">Submit</button>
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
<script class="cssdeck" src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script class="cssdeck" src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.1/js/bootstrap.min.js"></script>
</body>
<html>
This is the route that I am passing to the action field in my form:
Route::get('/adding_to_table', function()
{
return View::make('create');
});
And this is the create.php file that the route (above) is supposed to load which takes care of
the database submission
DB::table('user_info')->insert(
array("First_name" => Input::post('firstname'),
"Last_name" => Input::post("lastname"),
"E-mail" => Input::post("email"),
"Username" => Input::post("username"),
"Password" => Input::post("password"),
)
);
echo "Successfully entered user information into data table";
However, Laravel doesn't like this and is throwing this error at me:
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
Open: /Users/brendanbusey/Desktop/php_site/laravelSite/bootstrap/compiled.php
}))->bind($request);
} else {
$this->methodNotAllowed($others);
}
}
protected function methodNotAllowed(array $others)
{
throw new MethodNotAllowedHttpException($others);
}
protected function check(array $routes, $request, $includingMethod = true)
I have double and triple checked to make sure that I am using the names and not the id's from my html form when I'm sending the data via POST and all my names from the columns in my database match the ones in my code. Any help would be greatly appreciated!
You need to have two routes defined, one for GET and one for POST. If you want to use the same adding_to_table url, it should be something like
Route::get('/adding_to_table', function() {
// code to display your form initially
});
Route::post('/adding_to_table', function() {
// code to process the form submission
});
Maybe I'm not understanding you correctly, but it looks like you are using View::make() to try to run your db insert code. I believe View::make() is just intended to render blade templates, so I don't think this will work. Instead you could put that type of thing into a controller method, or even directly into the post route closure. To access the submitted values, you should use Input::get('firstname') etc. In the laravel docs here it explains that
You do not need to worry about the HTTP verb used for the request, as
input is accessed in the same way for all verbs.
You need to change the form opening line in your HTML to this:
<form method="POST" action='adding_to_table' class="form-horizontal">
In your routes.php file, you need to have this:
Route::get('adding_to_table', function()
{
return View::make('create');
});
Route::post('adding_to_table', function()
{
DB::table('user_info')->insert(
array("First_name" => Input::get('firstname'),
"Last_name" => Input::get("lastname"),
"E-mail" => Input::get("email"),
"Username" => Input::get("username"),
"Password" => Input::get("password"),
)
);
});
Change
Input::post() to Input::get()
to retrieve inputs.
Just add {{ csrf_field() }} below your form, like this:
<form method="POST" action='/adding_to_table' class="form-horizontal">
{{ csrf_field() }}
in Create.blade.php
{!! Form::open(array('route' => 'ControllerName.store','method' => 'POST','files' => true)) !!}
in Controller :-
public function store(Request $request)
{
$this->validate($request, [
'first_name' =>'required',
'last_name' => 'required',
'e_mail' =>'required',
'username' => 'required',
'password' =>'required',
]);
ModelName::create($request->all());
return route->(ControllerName.index);
NOTE : check model with all fields are fillable are not .

Categories