Unable to upload image with codeigniter - image

I have trying to post some values to table with an image but when i try to upload file name saved in table but image doesn't move to directory. i have checked directory permission.
but still no luck.
function:
function add_multiple_choice_question($quiz_id) {
if (sizeof($this->input->post('options')) != $this->input->post('number_of_options')) {
return false;
}
foreach ($this->input->post('options') as $option) {
if ($option == "") {
return false;
}
}
if (sizeof($this->input->post('correct_answers')) == 0) {
$correct_answers = [""];
} else {
$correct_answers = $this->input->post('correct_answers');
}
$data['quiz_id'] = $quiz_id;
$data['title'] = html_escape($this->input->post('title'));
$data['number_of_options'] = html_escape($this->input->post('number_of_options'));
$data['type'] = 'multiple_choice';
$data['options'] = json_encode($this->input->post('options'));
$data['correct_answers'] = json_encode($correct_answers);
if (!file_exists('uploads/quiz_image')) {
mkdir('uploads/quiz_image', 0777, true);
}
if ($_FILES['quiz_image']['name'] == "") {
$data['quiz_image'] = 'category-thumbnail.png';
} else {
$data['quiz_image'] = md5(rand(10000000, 20000000)) . '.jpg';
move_uploaded_file($_FILES['quiz_image']['tmp_name'], 'uploads/quiz_image/' . $data['quiz_image']);
}
$this->db->insert('question', $data);
return true; }
Unable to move file to directory
Form
<form action="<?php echo site_url('admin/quiz_questions/'.$param2.'/add'); ?>" enctype="multipart/form-data" method="post" id = 'mcq_form'>
<input type="hidden" name="question_type" value="mcq">
<div class="form-group">
<label for="title"><?php echo get_phrase('question_title'); ?></label>
<input class="form-control" type="text" name="title" id="title" required>
</div>
<div class="form-group">
<label for="title"><?php echo get_phrase('quiz_image'); ?></label>
<div class="input-group">
<div class="custom-file">
<input type="file" class="custom-file-input" name="quiz_image" onchange="changeTitleOfImageUploader(this)" accept="image/*">
<label class="custom-file-label ellipsis" for=""><?php echo get_phrase('choose_file'); ?></label>
</div>
</div>
</div>
<div class="form-group" id='multiple_choice_question'>
<label for="number_of_options"><?php echo get_phrase('number_of_options'); ?></label>
<div class="input-group">
<input type="number" class="form-control" name="number_of_options" id="number_of_options" data-validate="required" data-message-required="Value Required" min="0">
<div class="input-group-append" style="padding: 0px"><button type="button" class="btn btn-secondary btn-sm pull-right" name="button" onclick="showOptions(jQuery('#number_of_options').val())" style="border-radius: 0px;"><i class="fa fa-check"></i></button></div>
</div>
</div>
<div class="text-center">
<button class = "btn btn-success" id = "submitButton" type="button" name="button" data-dismiss="modal"><?php echo get_phrase('submit'); ?></button>
</div>
application is using script but i am not experienced with it.
<script type="text/javascript">
function showOptions(number_of_options){
$.ajax({
type: "POST",
url: "<?php echo site_url('admin/manage_multiple_choices_options'); ?>",
data: {number_of_options : number_of_options},
success: function(response){
jQuery('.options').remove();
jQuery('#multiple_choice_question').after(response);
}
});
}
$('#submitButton').click( function(event) {
$.ajax({
url: '<?php echo site_url('admin/quiz_questions/'.$param2.'/add'); ?>',
type: 'post',
data: $('form#mcq_form').serialize(),
success: function(response) {
if (response == 1) {
success_notify('<?php echo get_phrase('question_has_been_added'); ?>');
}else {
error_notify('<?php echo get_phrase('no_options_can_be_blank_and_there_has_to_be_atleast_one_answer'); ?>');
}
}
});
showLargeModal('<?php echo site_url('modal/popup/quiz_questions/'.$param2); ?>', '<?php echo get_phrase('manage_quiz_questions'); ?>');
});
</script>
Controller
public function quiz_questions($quiz_id = "", $action = "", $question_id = "") {
if ($this->session->userdata('admin_login') != true) {
redirect(site_url('login'), 'refresh');
}
$quiz_details = $this->crud_model->get_lessons('lesson', $quiz_id)->row_array();
if ($action == 'add') {
$response = $this->crud_model->add_quiz_questions($quiz_id);
echo $response;
}
elseif ($action == 'edit') {
$response = $this->crud_model->update_quiz_questions($question_id);
echo $response;
}
elseif ($action == 'delete') {
$response = $this->crud_model->delete_quiz_question($question_id);
$this->session->set_flashdata('flash_message', get_phrase('question_has_been_deleted'));
redirect(site_url('admin/course_form/course_edit/'.$quiz_details['course_id']));
}
}
i searched too much n tried all trick but no luck.

Related

Ajax datatable is not inserting

I am studying about ajax datatabl. My AJAX datatable insert is not working. It has no error on console or whatsoever. It's just whenever I am inserting, the datatable is just refreshing. Is there anything that I missed? I have provided my codes below. Any help will be appreciated. Thank you very much.
This is the result whenever i'm adding. But it's not adding on database or whatsoever.
Views:
<div class="table-responsive">
<br/>
<button type="button" id="add_button" data-toggle="modal" data-target="#userModal" class="btn btn-info btn-lg">Add</button>
<br /><br />
<table id="user_datas" class="table table-bordered table-striped">
<thead>
<tr>
<th width="35%">Name</th>
<th width="35%">Email</th>
<th width="10%">Edit</th>
<th width="10%">Delete</th>
</tr>
</thead>
</table>
</div>
</div>
</body>
</html>
<div id="userModal" class="modal fade">
<div class="modal-dialog">
<form method="post" id="user_form" enctype="multipart/form-data" >
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add User</h4>
</div>
<div class="modal-body">
<input type="text" name="first_name" id="first_name" class="form-control" />
<br />
<input type="text" name="last_name" id="last_name" class="form-control" />
<br />
<!-- <input type="file" name="user_image" id="user_image" /> -->
<!-- <span id="user_uploaded_image"></span> -->
</div>
<div class="modal-footer">
<input type="hidden" name="user_id" id="user_id" />
<input type="submit" name="action" id="action" class="btn btn-success" value="Add" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
Ajax:
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
$('#add_button').click(function(){
$('#user_form')[0].reset();
$('.modal-title').text("Add User");
$('#action').val("Add");
})
var dataTable = $('#user_datas').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"<?php echo base_url() . 'profile/fetch_user'; ?>",
type:"POST"
},
"columnDefs":[
{
"targets":[0, 3, 3],
"orderable":false,
},
],
});
$(document).on('submit', '#user_form', function(event){
event.preventDefault();
var name = $('#name').val();
var email = $('#email').val();
if(name != '' && email != '')
{
$.ajax({
url:"<?php echo base_url() . 'profile/user_action'?>",
method:'POST',
data:new FormData(this),
contentType:false,
processData:false,
success:function(data)
{
console.log(name);
console.log(email);
alert(data);
$('#user_form')[0].reset();
$('#userModal').modal('hide');
dataTable.ajax.reload();
}
});
}
else
{
alert("Fields are Required");
}
});
});
</script>
Controller:
function fetch_user(){
$this->load->model("profiles");
$fetch_data = $this->profiles->make_datatables();
$data = array();
foreach($fetch_data as $row)
{
$sub_array = array();
$sub_array[] = $row->name;
$sub_array[] = $row->email;
$sub_array[] = '<button type="button" name="update" id="'.$row->id.'" class="btn btn-warning btn-xs update">Update</button>';
$sub_array[] = '<button type="button" name="delete" id="'.$row->id.'" class="btn btn-danger btn-xs delete">Delete</button>';
$data[] = $sub_array;
}
$output = array(
"draw" => intval(isset($_POST["action"] )),
"recordsTotal" => $this->profiles->get_all_data(),
"recordsFiltered" => $this->profiles->get_filtered_data(),
"data" => $data
);
echo json_encode($output);
}
function user_action(){
if(isset($_POST["action"])){
if($_POST["action"] == "Add")
{
$insert_data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post("email.")
);
$this->load->model('profiles');
$this->profiles->insert_crud($insert_data);
echo 'Data Inserted';
}
}
function fetch_single_user()
{
$output = array();
$this->load->model("profiles");
$data = $this->profiles->fetch_single_user($_POST["user_id"]);
foreach($data as $row)
{
$output['name'] = $row->name;
$output['email'] = $row->email;
}
echo json_encode($output);
}
}
Model:
var $table = "userss";
var $select_column = array("id", "name", "email");
var $order_column = array(null, "name", "email", null, null);
function make_query()
{
$this->db->select($this->select_column);
$this->db->from($this->table);
if(isset($_POST["search"]["value"]))
{
$this->db->like("name", $_POST["search"]["value"]);
$this->db->or_like("email", $_POST["search"]["value"]);
}
if(isset($_POST["order"]))
{
$this->db->order_by($this->order_column[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
}
else
{
$this->db->order_by('id', 'DESC');
}
}
function make_datatables(){
$this->make_query();
if($_POST["length"] != -1)
{
$this->db->limit($_POST['length'], $_POST['start']);
}
$query = $this->db->get();
return $query->result();
}
function get_filtered_data(){
$this->make_query();
$query = $this->db->get();
return $query->num_rows();
}
function get_all_data()
{
$this->db->select("*");
$this->db->from($this->table);
return $this->db->count_all_results();
}
function insert_crud()
{
$this->db->insert('userss', $data);
}
What is your database structure? Is the table called userss or users?
$this->db->insert('userss', $data); <--Possible typo?
You likely will need to use the inspect feature of your browser and look at any responses under the network tab to see any errors.

How to get Output it showing no any error & output?

The contoller shows output error1 it does not shoe even row(),and does not give any error in developer tool. it get the file from ajax users_controller but does not work & issue is contant.
This is the form:
<form class="form-signin" >
<h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
<label for="name" class="sr-only">Username</label>
<input type="text" id="name" class="form-control" placeholder="Username" autofocus><br/>
<label for="Password" class="sr-only">Password</label>
<input type="text" id="password" class="form-control" placeholder="Password">
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
<span class="error"></span>
</form>
These are the scripts:
<script>
$(document).ready(function(){
$('form').on('submit',function(){
var username = $('#name').val();
var password = $('#password').val();
$.ajax({
type:'post',
url:'users_controller/login_check',
data: {
username:'username',
password:'password'
},
success:function(result)
{
if(result !== 'error')
{
window.location.href=result;
}
else
{
$('.error').html('');
$('.error').html('<p class="alert alert-danger">Invalid username or password</p>');
$('.error').show();
}
}
});
return false;
});
});
This is controller file:
public function login_check()
{
$username = $this->input->post('username',TRUE);
$password = $this->input->post('password',TRUE);
$this->load->model('users_model');
//$row = $this->load->users_model('getUsers');
$row = $this->users_model->getUsers($username,$password);
if($row)
{
if($this->username === $username && $this->password === $password)
{
$this->session->set_userdata('user_id',$row->user_id);
$this->session->set_userdata('user_name',$row->username);
echo base_url('users_controller');
}
else
{
echo "error";
}
}
else{
echo "error1";
print_r($row);
}
}
The contoller shows output error1 it does not shoe even row(),and does not give any error in developer tool.

Codeigniter Mysql Ajax Pagination sort and search

I have to do a codeigniter crud operation. But now i want to add pagination search and sort for that.I used lots of tutorials to do that. But i can't understand. To anyone who knows please help me to do that. Thank you.
controller
class User_controller extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('user_model');
$this->load->library('form_validation');
}
// load user_list view
public function index()
{
$this->load->view('admin_include/header');
$this->load->view('admin_pages/user_list');
}
// show all the users in view
public function fillgrid(){
$this->user_model->fillgrid();
}
function fetch_record(){
$this->user_model->fetch_record();
}
// validate and insert new user data
public function create(){
$this->form_validation->set_rules('firstname', 'First Name', 'required');
$this->form_validation->set_rules('lastname', 'Last Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('contact_no', 'Contact Number', 'required|numeric|max_length[10]|min_length[10]');
if ($this->form_validation->run() == FALSE){
echo'<div class="alert alert-danger">'.validation_errors().'</div>';
exit;
}
else{
$this->user_model->create();
}
}
// edit user
public function edit(){
$id = $this->uri->segment(3);
$this->db->where('id',$id);
$data['query'] = $this->db->get('user');
$data['id'] = $id;
$this->load->view('admin_pages/user_edit', $data);
}
// update validation
public function update(){
$res['error']="";
$res['success']="";
$this->form_validation->set_rules('firstname', 'First Name', 'required');
$this->form_validation->set_rules('lastname', 'Last Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('contact_no', 'Contact Number', 'required|numeric|max_length[10]|min_length[10]');
if ($this->form_validation->run() == FALSE){
$res['error']='<div class="alert alert-danger">'.validation_errors().'</div>';
}
else{
$data = array('firstname'=> $this->input->post('firstname'),
'lastname'=> $this->input->post('lastname'),
'email'=>$this->input->post('email'),
'contact_no'=>$this->input->post('contact_no'),
'address'=>$this->input->post('address'));
$this->db->where('id', $this->input->post('hidden'));
$this->db->update('user', $data);
$res['success'] = '<div class="alert alert-success">One record updated Successfully</div>';
}
header('Content-Type: application/json');
echo json_encode($res);
exit;
}
//delete user
public function delete(){
$id = $this->input->POST('id');
$this->db->where('id', $id);
$this->db->delete('user');
echo'<div class="alert alert-success">One record deleted Successfully</div>';
exit;
}
model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User_model extends CI_Model {
public function fillgrid(){
$this->db->order_by("id", "desc");
$data = $this->db->get('user');
foreach ($data->result() as $row){
$edit = base_url().'index.php/user_controller/edit/';
$delete = base_url().'index.php/user_controller/delete/';
echo "<tr>
<td>$row->firstname</td>
<td>$row->lastname</td>
<td>$row->email</td>
<td>$row->contact_no</td>
<td>$row->address</td>
<td>$row->created</td>
<td><a href='$edit' data-id='$row->id' class='btnedit' title='edit'><i class='glyphicon glyphicon-pencil' title='edit'></i></a> <a href='$delete' data-id='$row->id' class='btndelete' title='delete'><i class='glyphicon glyphicon-remove'></i></a></td>
</tr>";
}
exit;
}
public function create(){
$data = array('firstname'=> $this->input->post('firstname'),
'lastname'=> $this->input->post('lastname'),
'email'=>$this->input->post('email'),
'contact_no'=>$this->input->post('contact_no'),
'address'=>$this->input->post('address'),
'created'=>date('d/m/y'));
$this->db->insert('user', $data);
echo'<div class="alert alert-success">One record inserted Successfully</div>';
exit;
}
private function edit(){}
private function delete(){}
//2015.7.26
//set table name to be used by all functions
var $table = 'user';
function fetch_record($limit, $start)
{
$this->db->limit($limit, $start);
$query = $this->db->get($this->user);
return ($query->num_rows() > 0) ? $query->result() : FALSE;
}
function record_count()
{
return $this->db->count_all_results('user');
}
//2015.7.26
}
//2015.7.26
public function pagination(){
$page_number = $this->input->post('page_number');
$item_par_page = 2;
$position = ($page_number*$item_par_page);
$result_set = $this->db->query("SELECT * FROM user LIMIT ".$position.",".$item_par_page);
$total_set = $result_set->num_rows();
$page = $this->db->get('user') ;
$total = $page->num_rows();
//break total recoed into pages
$total = ceil($total/$item_par_page);
if($total_set>0){
$entries = null;
// get data and store in a json array
foreach($result_set->result() as $row){
$entries[] = $row;
}
$data = array(
'TotalRows' => $total,
'Rows' => $entries
);
$this->output->set_content_type('application/json');
echo json_encode(array($data));
}
exit;
}
view
<div class="well">
<form class="form-inline" role="form" id="frmadd" action="<?php echo base_url() ?>index.php/user_controller/create" method="POST">
<!--First Name-->
<div class="form-group">
<label class="sr-only" for="firstname">First Name</label>
<input type="text" name="firstname" class="form-control" id="firstname" placeholder="First name">
</div>
<!--/First Name-->
<!--Last Name-->
<div class="form-group">
<label class="sr-only" for="lastname">Last Name</label>
<input type="text" name="lastname" class="form-control" id="lastname" placeholder="Last Name">
</div>
<!--/Last Name-->
<!-- email-->
<div class="form-group">
<div class="input-group">
<div class="input-group-addon">#</div>
<input class="form-control" name="email" type="email" placeholder="Enter email">
</div>
</div>
<!-- email-->
<!--Contact-->
<div class="form-group">
<label class="sr-only" for="contact_no">Contact</label>
<input type="text" class="form-control" name="contact_no" id="contact_no" placeholder="contact number">
</div>
<!--/Contact-->
<!--Address-->
<div class="form-group">
<label class="sr-only" for="address">Address</label>
<input type="text" name="address" class="form-control" id="exampleInputPassword2" placeholder="Address">
</div>
<!--/Address-->
<!--submit-->
<input type="submit" class="btn btn-success" id="exampleInputPassword2" value="submit">
<!--/submit-->
</div>
</form>
</div>
<table class="table">
<thead><tr><th>First Name</th><th>Last Name</th><th>Email</th><th>Contact</th><th>Address</th><th>created</th><th>Action</th></tr></thead>
<tbody id="fillgrid">
</tbody>
<tfoot></tfoot>
</table>
<!-- //2015.7.26-->
<div class="row clear-fix">
<div class="col-md-4 pull-right">
<button id="previous" class="btn btn-sm btn-primary">Previous</button>
<lable>Page <lable id="page_number" name="page_number" ></lable> of <lable id="total_page" name="total_page"></lable></lable>
<button id="next" class="btn btn-sm btn-primary">Next</button>
</div>
</div>
<div style="text-align: center">
<!--//2015.7.26-->
</div>
</div>
</div>
<script>
$(document).ready(function (){
//fill data
var btnedit='';
var btndelete = '';
fillgrid();
// add data
$("#frmadd").submit(function (e){
e.preventDefault();
$("#loader").show();
var url = $(this).attr('action');
var data = $(this).serialize();
$.ajax({
url:url,
type:'POST',
data:data
}).done(function (data){
$("#response").html(data);
$("#loader").hide();
fillgrid();
});
});
function fillgrid(){
$("#loader").show();
$.ajax({
url:'<?php echo base_url() ?>index.php/user_controller/fillgrid',
type:'GET'
}).done(function (data){
$("#fillgrid").html(data);
$("#loader").hide();
btnedit = $("#fillgrid .btnedit");
btndelete = $("#fillgrid .btndelete");
var deleteurl = btndelete.attr('href');
var editurl = btnedit.attr('href');
//delete record
btndelete.on('click', function (e){
e.preventDefault();
var deleteid = $(this).data('id');
if(confirm("are you sure")){
$("#loader").show();
$.ajax({
url:deleteurl,
type:'POST' ,
data:'id='+deleteid
}).done(function (data){
$("#response").html(data);
$("#loader").hide();
fillgrid();
});
}
});
//edit record
btnedit.on('click', function (e){
e.preventDefault();
var editid = $(this).data('id');
$.colorbox({
href:"<?php echo base_url()?>index.php/user_controller/edit/"+editid,
top:50,
width:500,
onClosed:function() {fillgrid();}
});
});
});
}
});
</script>
i think you have to check your db field name it will work definitely you are missing some db field name...

Form Validation Showing 2 Callback Messages

I am trying to set my own callback message for codeigniter. But when I try to make my own it will show both messages codeigniter one and my custom one. Here is a link to my errors are showing up the top error is one that I would like to use http://postimg.org/image/v9ilejmnt/
How am I able to make it only show my custom error message?
I also use hmvc so I have had to add run($this) in the form validation to make callback work.
Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends Controller {
private $error = array();
public function __construct() {
parent::__construct();
$this->load->library('user');
$this->load->library('form_validation');
$this->lang->load('common/login', 'english');
if($this->session->userdata('user_id')) {
redirect('dashboard');
} else {
return false;
redirect('login');
}
}
public function index() {
$this->form_validation->set_rules('username', 'Username', 'required|min_length[4]|max_length[12]|xss_clean|callback_validate');
$this->form_validation->set_rules('password', 'Password', 'required|xss_clean');
if($this->form_validation->run($this) == false) {
if (array_key_exists('warning', $this->error)) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
$data['action'] = site_url('login');
$this->load->view('common/login', $data);
} else {
redirect('dashboard');
}
}
function validate() {
$username = $this->input->post('username');
$password = $this->input->post('password');
if ($this->user->login($username, $password)) {
return true;
} else {
$this->error['warning'] = $this->lang->line('error_login');
return !$this->error;
}
}
}
View
<?php echo modules::run('common/header/index');?>
<div class="container">
<div class="row">
<div class="col-lg-6 col-lg-offset-3 col-md-4 col-md-offset-4 col-sm-offset-4 col-sm-4">
<div class="panel panel-default">
<div class="panel-heading"><h2 class="panel-title">Administration Login</h2></div>
<div class="panel-body">
<?php if ($error_warning) { ?>
<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> <?php echo $error_warning; ?>
<button type="button" class="close" data-dismiss="alert">×</button>
</div>
<?php } ?>
<form action="<?php echo $action;?>" method="post" enctype="multipart/form-data">
<div class="form-group">
<div class="input-group"><span class="input-group-addon"><i class="fa fa-user"></i> </span>
<input type="text" name="username" value="" placeholder="Username" class="form-control" size="50" />
</div>
<?php echo form_error('username', '<div class="text-danger">', '</div>'); ?>
</div>
<div class="form-group">
<div class="input-group"><span class="input-group-addon"><i class="fa fa-lock"></i></span>
<input type="password" name="password" value="" placeholder="Password" class="form-control"/>
</div>
<?php echo form_error('password', '<div class="text-danger">', '</div>'); ?>
</div>
<div class="form-group">
<div class="text-right">
<button type="submit" class="btn btn-primary"><i class="fa fa-key"></i> Login</button>
</div>
</div>
</form>
</div><!--/. Panel Body -->
</div><!--/. Panel Panel Default -->
</div>
</div>
</div>
<?php echo modules::run('common/footer/index');?>
you forgot to set error message for your your callback.
$this->form_validation->set_message('validate', 'invalid username or password');
return FALSE;
or you can do
$this->form_validation->set_message('validate', $this->lang->line('error_login'));
return FALSE;
in your view file you are showing errors for each fields (CI form validation messages) as well as your own <?php echo $error_warning; ?>
you should use following code
function validate() {
$username = $this->input->post('username');
$password = $this->input->post('password');
if ($this->user->login($username, $password)) {
return true;
} else {
$this->form_validation->set_message('validate', $this->lang->line('error_login'));
return FALSE;
}
and remove this block from view
<?php if ($error_warning) { ?>
<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> <?php echo $error_warning; ?>
<button type="button" class="close" data-dismiss="alert">×</button>
</div>
<?php } ?>
}
and remove this too
if (array_key_exists('warning', $this->error)) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
I worked it out today. When want to use both validation methods custom and form validation can not use callbacks.
public function index() {
$this->form_validation->set_rules('username', 'Username', 'required|min_length[4]|max_length[12]');
$this->form_validation->set_rules('password', 'Password', 'required|xss_clean');
if($this->form_validation->run($this) == false) {
$data['title'] = $this->lang->line('heading_title');
$data['text_heading'] = $this->lang->line('text_heading');
if (array_key_exists('warning', $this->error)) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
$data['action'] = site_url('login');
$this->load->view('common/login', $data);
} else {
if($this->validate()) {
redirect('dashboard');
} else {
$data['title'] = $this->lang->line('heading_title');
$data['text_heading'] = $this->lang->line('text_heading');
if (array_key_exists('warning', $this->error)) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
$data['action'] = site_url('login');
$this->load->view('common/login', $data);
}
}
}

Add products on shopping cart

Friends, I am developing an e-commerce website (using Codeigniter).
After the customer fill out the amount of products and click "Buy", only products with the field "quantity" are to be filled in cart. Can you help me?
HTML:
<form>
<ul class="products-list">
<li class="product">
<input type="hidden" class="product_id" value="1">
<span class="product-name">Product 1</span>
<span class="product-value">$ 100</span>
<span>Qnt. <input type="text" class="quantity"></span>
</li>
<li class="product">
<input type="hidden" class="product_id" value="2">
<span class="product-name">Product 2</span>
<span class="product-value">$ 100</span>
<span>Qnt. <input type="text" class="quantity"></span>
</li>
</ul>
<button>Buy</button>
</form>
jQuery:
$.ajax({
url: '/cart/add/'+product_id+'/'+quantity,
type: 'GET',
success: function( data ){
if ( data != false ) {
window.location.reload();
}
}
});
My PHP Code:
public function addItem( $product_id, $quantity){
$product = $this->Produto_model->getById($product_id);
$this->carrinho->setItem($product, $quantity);
echo json_encode($this->carrinho);
}
Try like this
HTML:
<form id="form-cart">
<ul class="products-list">
<li class="product">
<input type="hidden" class="product_id" value="1">
<span class="product-name">Product 1</span>
<span class="product-value">$ 100</span>
<span>Qnt. <input type="text" class="quantity" value="1"></span>
</li>
<li class="product">
<input type="hidden" class="product_id" value="2">
<span class="product-name">Product 2</span>
<span class="product-value">$ 100</span>
<span>Qnt. <input type="text" class="quantity" value="1"></span>
</li>
</ul>
<button id="form-cart-btn">Buy</button>
</form>
<script type="text/javascript">
$("#form-cart #form-cart-btn").click(function(){
form = $("#form-cart");
items = [];
form.find('li').each(function(i, e){
_e = $(e);
qty = parseInt(_e.find('.quantity').val());
if(isNaN(parseFloat(qty)) || ! isFinite(qty) || qty == 0)
return;
id = _e.find('.product_id').val();
items.push('item[' + id + ']=' + qty);
});
items = items.join('&');
$.ajax({
url: '/cart/add/?' + items,
dataType: 'json',
success: function(response)
{
if(response.status != 'success')
return false;
window.location.reload();
}
});
return false;
});
</script>
Cart Controller:
class Cart extends CI_Controller
{
public function add()
{
$items = isset($_GET['items']) ? $_GET['items'] : array();
foreach($items as $product_id => $qty)
{
$product = $this->Produto_model->getById($product_id);
if( ! $product)
{
++$i;
continue;
}
$this->carrinho->setItem($product, $qty);
++$i;
}
header("Content-type: application/json");
echo json_encode(array('status'=>'success'));
exit();
}
}

Resources