Ajax data retrieve from controller - ajax

Hi i have called the database value in codeigniter controller and computed the values of database and stored in one new variable. So how can i get both the database values and the new variable that I have created in the controller as I want to display all database value and the new computed value in view. Please suggest me.
My controller: welcome
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public $total;
public function __construct() {
parent::__construct();
$this->load->library('table');
$this->load->model('product_database');
}
public function index() {
$data['show_table'] = $this->view_table();
$this->load->view('welcome_message', $data);
}
public function view_table(){
$result = $this->product_database->show_all_data();
if ($result != false) {
return $result;
} else {
return 'Database is empty !';
}
}
public function AddtoCart(){
$id = $this->input->post('product_id');
$qty = $this->input->post('qty');
$this->db->where('id', $id); // Select where id matches the posted id
$query = $this->db->get('productlist', 1); // Select the products where a match is found and limit the query by 1
foreach ($query->result() as $row)
{
$data = array(
'id' => $id,
'qty' => $qty,
'price' => $row->price,
'name' => $row->name
);
$total=$qty*$row->price;
echo $total;
}
}
}
?>
my view: welcome_message
<!DOCTYPE HTML>
<html>
<head>
<title>Product list</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"> </script>
<script type="text/javascript">
$(document).ready(function() {
$("#add").click(function(event) {
event.preventDefault();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/Welcome/AddtoCart",
dataType: 'json',
data: {name: },
success: function(res) {
if (res)
{ alert();
// Show Entered Value
jQuery("#total").html(res.total);
}
}
});
});
});
</script>
</head>
<body>
<div class="container">
<div class="message">
<?php
if (isset($read_set_value)) {
echo $read_set_value;
}
if (isset($message_display)) {
echo $message_display;
}
?>
</div>
<div> <?php
if (isset($show_table)) {
echo "<div class='productlist'>";
if ($show_table == 'Database is empty !') {
echo $show_table;
} else {
echo '<h2>Product List</h2><br/><br/>';
?>
<div class="row">
<div class="col-sm-8">
<div class="well">
<div class="table-responsive">
<?php
echo "<table width='98%', >";
echo '<tr><th class="e_id">Id</th><th>ProductName</th> <th>Price</th> <tr/>';
$i=1;
foreach ($show_table as $value) {
?>
<tr class="well" >
<?php
echo "<td width='30%' height='27px'>" . $value->id . "</td>" . "<td width='70%' height='27px'>" . $value->name . "</td>" . "<td height='27px'>" . $value->price . "</td>";
?>
<?php echo form_open('/Welcome/AddtoCart'); ?>
<td><input type="number" name="qty" value="1" style="width:40px;" min="1" max="99"></td>
<input type="hidden" name="product_id" value="<?php echo $value->id ?>" />
<td><input type="submit" value="Add" id="add" width="100%"></td>
<td><input type="submit" value="Rmv" id="rmv" width="100%"></td></br>
<?php echo form_close(); ?>
</tr>
<?php
$i=$i+1;}
echo '</table>';
?>
</div>
</div>
</div>
<div class="col-sm-4">
<div class="well">
<h4>Cart</h4>
Total Rs:<input type="text" value="" id="total"></br><br>
<input type="submit" value="Checkout" id="chk_out">
</div>
</div>
</div>
<?php
}
echo "</div>";
}
?>
</div>
</div>
</body>
</html>
And my model
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Product_database extends CI_Model {
public function show_all_data() {
$this->db->select('*');
$this->db->from('productlist');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result();
} else {
return false;
}
}
}
?>

In place of echo $total you can put this code :
$total= array('total'=> $total);
$youarray=array_merge($data, $total);
echo json_econde($youarray,true);

Related

Insert data in codeigniter

I am trying to make an insert function in codeigniter using php and bootstrap. But when i press add button, nothing happens, my new data are not added in my db table. Please Help me.
My code:
department.php
<?php
/*
* File Name: employee.php
*/
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class department extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->helper('form');
$this->load->helper('url');
$this->load->database();
$this->load->library('form_validation');
//load the employee model
$this->load->model('department_model');
}
//index function
function index()
{
//fetch data from department and designation tables
// $data['department'] = $this->department_model->get_department();
//set validation rules
$this->form_validation->set_rules('id', 'Employee ID', 'trim|required|numeric');
$this->form_validation->set_rules('department_emer', 'Department Name', 'trim|required|callback_alpha_only_space');
$this->form_validation->set_rules('pershkrimi', 'Description', 'trim|required');
//$this->form_validation->set_rules('id_departament', 'Department', 'callback_combo_check');
if ($this->form_validation->run() == FALSE)
{
//fail validation
$this->load->view('department_view');
}
else
{
//pass validation
$data = array(
//'id' => $this->input->post('id'),
'department_emer' => $this->input->post('department_emer'),
'pershkrimi' => $this->input->post('pershkrimi'),
);
//insert the form data into database
$this->db->insert('department', $data);
//display success message
$this->session->set_flashdata('msg', '<div class="alert alert-success text-center">Department details added to Database!!!</div>');
redirect('department/index');
}
}
//custom validation function to accept only alpha and space input
function alpha_only_space($str)
{
if (!preg_match("/^([-a-z ])+$/i", $str))
{
$this->form_validation->set_message('alpha_only_space', 'The %s field must contain only alphabets or spaces');
return FALSE;
}
else
{
return TRUE;
}
}
}
?>
department_model.php
<?php
/*
* File Name: employee_model.php
*/
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class department_model extends CI_Model
{
function __construct()
{
// Call the Model constructor
parent::__construct();
}
//get department table to populate the department name dropdown
}
?>
department_view.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CodeIgniter | Insert Employee Details into MySQL Database</title>
<!--link the bootstrap css file-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- link jquery ui css-->
<link href="<?php echo base_url('assets/jquery-ui-1.11.2/jquery-ui.min.css'); ?>" rel="stylesheet" type="text/css" />
<!--include jquery library-->
<script src="<?php echo base_url('assets/js/jquery-1.10.2.js'); ?>"></script>
<!--load jquery ui js file-->
<script src="<?php echo base_url('assets/jquery-ui-1.11.2/jquery-ui.min.js'); ?>"></script>
<style type="text/css">
.colbox {
margin-left: 0px;
margin-right: 0px;
}
</style>
<script type="text/javascript">
//load datepicker control onfocus
$(function() {
$("#hireddate").datepicker();
});
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-sm-offset-3 col-lg-6 col-sm-6 well">
<legend>Add Department Details</legend>
<?php
$attributes = array("class" => "form-horizontal", "id" => "departmentform", "name" => "departmentform");
echo form_open("department/index", $attributes);?>
<fieldset>
<div class="form-group">
<div class="row colbox">
<div class="col-lg-4 col-sm-4">
<label for="department_emer" class="control-label">Name</label>
</div>
<div class="col-lg-8 col-sm-8">
<input id="department_emer" name="department_emer" placeholder="department_emer" type="text" class="form-control" value="<?php echo set_value('department_emer'); ?>" />
<span class="text-danger"><?php echo form_error('department_emer'); ?></span>
</div>
</div>
</div>
<div class="form-group">
<div class="row colbox">
<div class="col-lg-4 col-sm-4">
<label for="mbiemer" class="control-label">Description</label>
</div>
<div class="col-lg-8 col-sm-8">
<textarea class="form-control" rows="5" id="pershkrimi" name="pershkrimi" placeholder="pershkrimi" value="<?php echo set_value('pershkrimi'); ?>" ></textarea>
<span class="text-danger"><?php echo form_error('pershkrimi'); ?></span>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-md-8 text-left">
<input id="btn_update" name="btn_update" type="submit" class="btn btn-primary" value="Add" />
<input id="btn_cancel" name="btn_cancel" type="reset" class="btn btn-danger" value="Cancel" />
</div>
</div>
</fieldset>
<?php echo form_close(); ?>
<?php echo $this->session->flashdata('msg'); ?>
</div>
</div>
</div>
</body>
</html>
In department.php replace
$this->db->insert('department', $data);
with
$this->load->model('department_model.php');
$this->department_model.php->insert($data);
And in department_model.php create a function insert
public function insert($data) {
if($this->db->insert('table_name', $data)) {
//Success message or anything which you want
}
}
This will solve your problem.
Let me know if you require any further help!!!
Please load the CI database library before inserting the data, or you can load it in your constructor method.
$this->load->library('database');
Hopefully it can help you.

delete condition if multiple checkbox unchecked in codeigniter

please help me i would like to delete some check box if checkbox unchecked.
My checkbox is automatic show from database my sql. and i would like to delete some checkbox when checkbox in not checked.
PLease Help
its my controller
public function edit_overview($id_product)
{
if ($this->input->post('submit')) {
foreach ($id_overview = $this->input->post('id_overview') as $rm) {
$check_idoverview = $this->Biostar->check_idoverview($id_product, $rm);
if ($check_idoverview==unchecked){
$data['file'] = $check_idoverview;
$this->Biostar->delete_overview($check_idoverview,$id_product);
}else{
if ($check_idoverview > 0) {
} else {
$datafield = array(
'id_product' => $id_product,
'id_overview' => $rm
);
$this->Biostar->saveoverviewproduct($datafield);
$message_success = "Data Has Been Update";
}
}
}
}
$data['message_success'] = #$message_success;
$field = $this->Biostar->get_overview($id_product);
$fieldid_product = $this->Biostar->get_id_product($id_product);
$data['field'] = $field;
$data['id_product'] = $fieldid_product;
$data['content'] = "biostar/edit_overview_product";
$this->load->view('dashboard/index', $data);
}
My Model
function delete_overview($check_overview,$id_product)
{
$sql = "delete from overview_briostar where id_overview='$check_overview' AND id_product='$id_product'";
return $sql;
}
My View
<form method="post" action="<?php echo base_url(); ?>biostar/add_overview_product/<?php echo $id_product->id_product; ?>">
<div class="box-body">
<?php foreach ($speed as $row){ ?>
<div class="checkbox">
<label>
<input type="checkbox" name="id_overview[]" onClick="EnableSubmit3(this)" value="<?php echo $row['id_overview']; ?>"<?php foreach ($field as $wor){ ?> <?php if($row['id_overview']==$wor['id_overview']) echo "checked";?> <?php } ?> ><?php echo $row['title']; ?>
</label>
</div>
<?php } ?>
<!-- /input-group -->
</div>
<div class="box-footer">
<input value="Submit" type="submit" id="submit3" name="submit" class="btn btn-primary">
</div>
</form>
Unchecked checkbox value will not get posted, so you have to use jquery and ajax
Your checkbox
<input class="id_overview" type="checkbox" name="id_overview[]" value="<?php echo $row['id_overview']; ?>"<?php foreach ($field as $wor){ ?> <?php if($row['id_overview']==$wor['id_overview']) echo "checked";?> <?php } ?> ><?php echo $row['title']; ?>
your jquery
<script type="text/javascript">
$(document).ready(function() {
$("form#frm").submit(function(e) { // give a id to your form
e.preventDefault();
var ids = new Array();
$('.id_overview').each(function() {
if ($(this).is(':checked')) {
} else {
ids.push($(this).val());
}
});
$.ajax({
// send ids through your ajax code
});
});
});
</script>
create a new function and call it by ajax to delete the ids.
You can try like this
<form method="post" action="<?php echo base_url(); ?>biostar/add_overview_product/<?php echo $id_product->id_product; ?>">
<div class="box-body">
<?php foreach ($speed as $row){ ?>
<div class="checkbox">
<label>
<input type="hidden" name="all_id[]" value="<?php echo $row['id_overview']; ?>" />
<input type="checkbox" name="id_overview<?php echo $row['id_overview']; ?>" onClick="EnableSubmit3(this)" value="<?php echo $row['id_overview']; ?>"<?php foreach ($field as $wor){ ?> <?php if($row['id_overview']==$wor['id_overview']) echo "checked";?> <?php } ?> ><?php echo $row['title']; ?>
</label>
</div>
<?php } ?>
<!-- /input-group -->
</div>
<div class="box-footer">
<input value="Submit" type="submit" id="submit3" name="submit" class="btn btn-primary">
</div>
</form>
and in you controller
if ($this->input->post('submit')) {
foreach($all_id as $row_id)
{
if($this->input->post('id_overview'.$row_id))
{
//do action where id is present
}
else
{
//do action if unchecked by getting id $row_id
}
}
}

shopping cart in codeigniter using ajax

Hi I am new with ajax and having problem. I am trying to make a shopping cart using ajax.I don't know what is wrong with my code please help me out.
When I click the add button an alert comes 'No success' and nothing happen , I am not able add items to cart.
Thanks for helping me.
This is my view
<html>
<head>
<title>Codeigniter cart class</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link href='http://fonts.googleapis.com/css?family=Raleway:500,600,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/style.css">
<script type="text/javascript">
$(document).ready(function() {
$("#myform").submit(function(event) {
event.preventDefault();
var insert_data= $(this).serializeArray();
$.ajax({
url: "<?php echo base_url(); ?>" + "index.php/shopping2/add",
dataType: 'json',
//type: "POST",
data: insert_data,
success:function(response) {
//if (response){
//var res = JSON.parse(response);
var res = response;
if(res.status == 200){
window.location.href="http://127.0.0.1/codeigniter_cart2/index.php/shopping2";
}else{
alert(res.msg);
}
//}
//else{
// alert('sorry');
//}
}
});
});
});
</script>
</head>
<body>
<div id='content'>
<div class="row">
<div class="col-sm-5">
<h2 align="center">Items</h2>
<?php
?>
<table id="table" border="0" cellpadding="5px" cellspacing="1px">
<?php
foreach ($products as $product) {
$id = $product['serial'];
$name = $product['name'];
$price = $product['price'];
?>
<tr class="well">
<td style="padding-left:15px;"><?php echo $name; ?></td>
<td>
Rs. <?php echo $price; ?></td>
<?php
?>
<?php
echo form_open('',array('id' => 'myform'));
echo form_hidden('id', $id);
echo form_hidden('name', $name);
echo form_hidden('price', $price);
?> <!--</div>-->
<?php
$btn = array(
'class' => 'fg-button teal',
'value' => 'Add',
'name' => 'action',
'id' => 'add_button'
);
?>
<td>
<?php
// Submit Button.
echo form_submit($btn);
echo form_close();
?>
</td>
</tr>
<?php } ?>
</table>
</div>
<div class="col-sm-7">
<!-- <div id="cart" >-->
<h2 align="center">Items on Cart</h2>
<div>
<?php $cart_check = $this->cart->contents();
if(empty($cart_check)) {
echo 'To add products to your shopping cart click on "Add" Button';
} ?> </div>
<table id="table" border="0" cellpadding="5px" cellspacing="1px">
<?php
// All values of cart store in "$cart".
if ($cart = $this->cart->contents()): ?>
<div id="addcart">
<tr id= "main_heading" class="well">
<td style="padding-left:15px;"><?>Name</td>
<td>Price(Rs)</td>
<td>Qty</td>
<td>Amount</td>
<td>Remove</td>
</tr>
<?php
// Create form and send all values in "shopping/update_cart" function.
echo form_open('shopping2/update_cart');
$grand_total = 0;
$i = 1;
foreach ($cart as $item):
echo form_hidden('cart[' . $item['id'] . '][id]', $item['id']);
echo form_hidden('cart[' . $item['id'] . '][rowid]', $item['rowid']);
echo form_hidden('cart[' . $item['id'] . '][name]', $item['name']);
echo form_hidden('cart[' . $item['id'] . '][price]', $item['price']);
echo form_hidden('cart[' . $item['id'] . '][qty]', $item['qty']);
?>
<tr class="well" id="addcart">
<td style="padding-left:15px;">
<?php echo $item['name']; ?>
</td>
<td>
<?php echo number_format($item['price'], 2); ?>
</td>
<td>
<?php echo form_input('cart[' . $item['id'] . '][qty]', $item['qty'], ' type="number" max="99" min="1" value="1" style="width:50px;"'); ?>
</td>
<?php $grand_total = $grand_total + $item['subtotal']; ?>
<td>
Rs <?php echo number_format($item['subtotal'], 2) ?>
</td>
<td>
<?php
// cancle image.
$path = "<img src='http://127.0.0.1/codeigniter_cart2/images/cart_cross.jpg' width='25px' height='20px'>";
echo anchor('shopping/remove/' . $item['rowid'], $path); ?>
</td>
<?php endforeach; ?>
</tr>
<tr>
<td style="padding-left:30px;"><b>Order Total: Rs <?php
//Grand Total.
echo number_format($grand_total, 2); ?></b></td>
<td colspan="5" align="right"><input type="button" class ='fg-button teal' value="Clear cart" onclick="window.location = 'shopping2/remove'">
<?php //submit button. ?>
<input type="submit" class ='fg-button teal' value="Update Cart">
<?php echo form_close(); ?>
</td>
</tr></div>
<?php endif; ?>
</table>
</div>
<!-- <div id="products_e" align="center">-->
<!--</div>-->
<!-- </div>-->
</div>
</div>
</body>
</html>
This is my controller
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Shopping2 extends CI_Controller {
public function __construct()
{
parent::__construct();
//load model
$this->load->model('billing_model');
$this->load->library('cart');
}
public function index()
{
$data['products'] = $this->billing_model->get_all();
$this->load->view('shopping_view2', $data);
}
function add()
{
$insert_data = array(
'id' => $this->input->post('id'),
'name' => $this->input->post('name'),
'price' => $this->input->post('price'),
'qty' => 1
);
$this->cart->insert($insert_data);
//$success = $this->cart->insert($insert_data);
$cart_check = $this->cart->contents();
if(!empty($cart_check)){
//$this->cart->contents(insert_data);
$res = array('status' => 200, 'msg' => 'success');
}else{
$res = array('status' => 500, 'msg' => 'No success');
}
echo json_encode($res);
//echo $data[0]['value'];
//redirect('shopping2');
}
function remove($rowid) {
// Check rowid value.
if ($rowid==="all"){
$this->cart->destroy();
}else{
$data = array(
'rowid' => $rowid,
'qty' => 0
);
$this->cart->update($data);
}
redirect('shopping2');
}
function update_cart(){
// Recieve post values,calcute them and update
$cart_info = $_POST['cart'] ;
foreach( $cart_info as $id => $cart)
{
$rowid = $cart['rowid'];
$price = $cart['price'];
$amount = $price * $cart['qty'];
$qty = $cart['qty'];
$data = array(
'rowid' => $rowid,
'price' => $price,
'amount' => $amount,
'qty' => $qty
);
$this->cart->update($data);
}
redirect('shopping2');
}
}
Please help me how to add items in the cart using ajax.
Since u managed to get a response, the problem should lie in your Model or data insertion.
Few suggestions:
It's also recommended that you use $.post() instead of $.ajax().
"<?php echo base_url(); ?>" + "index.php/shopping2/add" can be changed to "<?php echo site_url('shopping2/add"'); ?>"
Use the built in Codeignter output class to output your JSON. See here: https://www.codeigniter.com/userguide3/libraries/output.html

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);
}
}
}

Magento - Controller to Ajax Estimate Shipping: Load Block and display phtml

I copied estimatePostAction and made estimateAjaxPostAction (overriding core - I did not hack the core). The controller action works as well (class Mage_Checkout_CartController).
Now I want to get/create a block for replacing shipping block after estimate shipping with ajax. I tried this:
public function estimateAjaxPostAction()
{
$country = (string) $this->getRequest()->getParam('country_id');
$postcode = (string) $this->getRequest()->getParam('estimate_postcode');
$city = (string) $this->getRequest()->getParam('estimate_city');
$regionId = (string) $this->getRequest()->getParam('region_id');
$region = (string) $this->getRequest()->getParam('region');
$this->_getQuote()->getShippingAddress()
->setCountryId($country)
->setCity($city)
->setPostcode($postcode)
->setRegionId($regionId)
->setRegion($region)
->setCollectShippingRates(true);
$this->_getQuote()->save();
//$this->_goBack();
$this->loadLayout();
$block = $this->getLayout()->createBlock('Mage_Checkout_Block_Cart_Shipping','checkout.cart.shipping.ajax',array('template' => 'checkout/cart/shipping.phtml'));
if($block) {
$response = array();
$response['shipping'] = $block->toHtml();
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
}
}
The block checkout.cart.shipping.ajax was created. But toHtml() returns nothing.
My JSON returns:
{"shipping":""}
Why toHtml method doesn't work?
Edit: My block code (checkout/cart/shipping.phtml)
<?php /** #var $this Mage_Checkout_Block_Cart_Shipping */ ?>
<div class="row contem-shipping">
<div class="col-xs-10 shipping">
<div class="text-ship">
<h2><?php echo $this->__('Calcular o frete:') ?></h2>
<p><?php echo $this->__('Insira o CEP do endereço<br />no campo ao lado.') ?></p>
</div>
<div class="shipping-form">
<form action="<?php echo $this->getUrl('checkout/cart/estimatePost') ?>" method="post" id="shipping-zip-form">
<ul class="form-list">
<li class="no-display">
<div class="input-box">
<?php echo Mage::getBlockSingleton('directory/data')->getCountryHtmlSelect($this->getEstimateCountryId()) ?>
</div>
</li>
<?php if($this->getStateActive()): ?>
<li>
<label for="region_id"<?php if ($this->isStateProvinceRequired()) echo ' class="required"' ?>><?php if ($this->isStateProvinceRequired()) echo '<em>*</em>' ?><?php echo $this->__('State/Province') ?></label>
<div class="input-box">
<select id="region_id" name="region_id" title="<?php echo $this->__('State/Province') ?>" style="display:none;"<?php echo ($this->isStateProvinceRequired() ? ' class="validate-select"' : '') ?>>
<option value=""><?php echo $this->__('Please select region, state or province') ?></option>
</select>
<script type="text/javascript">
//<![CDATA[
$('region_id').setAttribute('defaultValue', "<?php echo $this->getEstimateRegionId() ?>");
//]]>
</script>
<input type="text" id="region" name="region" value="<?php echo $this->escapeHtml($this->getEstimateRegion()) ?>" title="<?php echo $this->__('State/Province') ?>" class="input-text" style="display:none;" />
</div>
</li>
<?php endif; ?>
<?php if($this->getCityActive()): ?>
<li>
<label for="city"<?php if ($this->isCityRequired()) echo ' class="required"' ?>><?php if ($this->isCityRequired()) echo '<em>*</em>' ?><?php echo $this->__('City') ?></label>
<div class="input-box">
<input class="input-text<?php if ($this->isCityRequired()):?> required-entry<?php endif;?>" id="city" type="text" name="estimate_city" value="<?php echo $this->escapeHtml($this->getEstimateCity()) ?>" />
</div>
</li>
<?php endif; ?>
<li>
<div class="input-box">
<input class="input-text validate-postcode<?php if ($this->isZipCodeRequired()):?> required-entry<?php endif;?>" type="text" id="postcode" name="estimate_postcode" value="<?php echo $this->escapeHtml($this->getEstimatePostcode()) ?>" />
</div>
</li>
</ul>
<div class="buttons-set">
<button id="button-cep" style="width: 100px;" type="button" title="<?php echo $this->__('Get a Quote') ?>" onclick="calculaFreteAjax(jQuery('#postcode').val()); return false;" class="btn btn-2 btn-2a"><?php echo $this->__('Get a Quote') ?></button>
</div>
</form>
<script type="text/javascript">
//<![CDATA[
new RegionUpdater('country', 'region', 'region_id', <?php echo $this->helper('directory')->getRegionJson() ?>);
//]]>
</script>
<?php $_shippingRateGroups = $this->getEstimateRates(); ?>
<?php if ($_shippingRateGroups): ?>
<form id="co-shipping-method-form" action="<?php echo $this->getUrl('checkout/cart/estimateUpdatePost') ?>">
<dl class="sp-methods">
<?php foreach ($_shippingRateGroups as $code => $_rates): ?>
<dt><?php echo $this->escapeHtml($this->getCarrierName($code)) ?></dt>
<dd>
<ul>
<?php foreach ($_rates as $_rate): ?>
<li<?php if ($_rate->getErrorMessage()) echo ' class="error-msg"';?>>
<?php if ($_rate->getErrorMessage()): ?>
<?php echo $this->escapeHtml($_rate->getErrorMessage()) ?>
<?php else: ?>
<input name="estimate_method" type="radio" value="<?php echo $this->escapeHtml($_rate->getCode()) ?>" id="s_method_<?php echo $_rate->getCode() ?>"<?php if($_rate->getCode()===$this->getAddressShippingMethod()) echo ' checked="checked"' ?> class="radio" />
<label for="s_method_<?php echo $_rate->getCode() ?>"><?php echo $this->escapeHtml($_rate->getMethodTitle()) ?>
<?php $_excl = $this->getShippingPrice($_rate->getPrice(), $this->helper('tax')->displayShippingPriceIncludingTax()); ?>
<?php $_incl = $this->getShippingPrice($_rate->getPrice(), true); ?>
<?php echo $_excl; ?>
<?php if ($this->helper('tax')->displayShippingBothPrices() && $_incl != $_excl): ?>
(<?php echo $this->__('Incl. Tax'); ?> <?php echo $_incl; ?>)
<?php endif; ?>
</label>
<?php endif ?>
</li>
<?php endforeach; ?>
</ul>
</dd>
<?php endforeach; ?>
</dl>
</form>
<?php endif; ?>
<script type="text/javascript">
//<![CDATA[
var coShippingMethodForm = new VarienForm('shipping-zip-form');
var countriesWithOptionalZip = <?php echo $this->helper('directory')->getCountriesWithOptionalZip(true) ?>;
coShippingMethodForm.submit = function () {
var country = $F('country');
var optionalZip = false;
for (i=0; i < countriesWithOptionalZip.length; i++) {
if (countriesWithOptionalZip[i] == country) {
optionalZip = true;
}
}
if (optionalZip) {
$('postcode').removeClassName('required-entry');
}
else {
$('postcode').addClassName('required-entry');
}
return VarienForm.prototype.submit.bind(coShippingMethodForm)();
}
//]]>
</script>
</div>
</div>
<div class="col-xs-6">
<?php
$totalItemsInCart = Mage::helper('checkout/cart')->getItemsCount(); //total items in cart
$totals = Mage::getSingleton('checkout/session')->getQuote()->getTotals(); //Total object
$subtotal = $totals["subtotal"]->getValue(); //Subtotal value
$grandtotal = $totals["grand_total"]->getValue(); //Grandtotal value
if(isset($totals['discount']) && $totals['discount']->getValue()) {
$discount = $totals['discount']->getValue(); //Discount value if applied
} else {
$discount = '';
}
$shipping = Mage::helper('checkout')->getQuote()->getShippingAddress()->getData();
$tax = $shipping["shipping_amount"];
/*if( $totals["tax"]->getValue()) {
$tax = $totals["tax"]->getValue(); //Tax value if present
} else {
$tax = '';
}*/
?>
<table class="totals-cart">
<tr>
<td class="total-tile">
Subtotal do pedido:
</td>
<td class="total-price">
<?php echo Mage::helper('core')->currency($subtotal, true, false); ?>
</td>
</tr>
<tr>
<td class="total-tile">
Frete:
</td>
<td class="total-price">
<?php echo Mage::helper('core')->currency($tax, true, false); ?>
</td>
</tr>
<?php if ($discount):?>
<tr>
<td class="total-tile">
Desconto:
</td>
<td class="total-price">
<?php echo Mage::helper('core')->currency($discount, true, false); ?>
</td>
</tr>
<?php endif;?>
</table>
</div>
</div>
<div class="row">
<div class="col-xs-16">
<div class="grand-total">
<p class="text">Total:</p>
<p class="price"><?php echo Mage::helper('core')->currency($grandtotal, true, false);?></p>
</div>
</div>
</div>
<script type="text/javascript">
function calculaFreteAjax(cep) {
jQuery('.contem-shipping .shipping').html('<span class="remove-frete" style="display: block; margin: 0 auto; width: 20px;" id="login-please-wait"><img src="http://sites.xpd.com.br/cpaps/skin/frontend/xpd/default/images/opc-ajax-loader.gif" class="v-middle" alt=""/></span>');
var param = {'country_id': 'BR','estimate_postcode': cep};
console.log(param);
jQuery.ajax({
type: "GET",
url: '<?php echo Mage::getBaseUrl().'checkout/cart/estimateAjaxPost/'; ?>', //My Custom Controller
data: param,
success: function(response) {
response = jQuery.parseJSON(response);
if(response.shipping) {
jQuery('.contem-shipping').parent().html(response.shipping);
}
else {
alert('Falha ao calcular o frete. Tente novamente.');
}
}
});
jQuery('#co-shipping-method-form dd input.radio').click(function(){
//I will submit the shipping method selected
});
}
</script>
Denis... I have modify code please check
public function estimateAjaxPostAction()
{
$country = (string) $this->getRequest()->getParam('country_id');
$postcode = (string) $this->getRequest()->getParam('estimate_postcode');
$city = (string) $this->getRequest()->getParam('estimate_city');
$regionId = (string) $this->getRequest()->getParam('region_id');
$region = (string) $this->getRequest()->getParam('region');
$this->_getQuote()->getShippingAddress()
->setCountryId($country)
->setCity($city)
->setPostcode($postcode)
->setRegionId($regionId)
->setRegion($region)
->setCollectShippingRates(true);
$this->_getQuote()->save();
$response = array();
$response['shipping']=$this->eastmatesajax();
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
}
protected function eastmatesajax()
{
$layout=$this->getLayout();
$layout->getMessagesBlock()->setMessages(Mage::getSingleton('checkout/session')->getMessages(true),Mage::getSingleton('catalog/session')->getMessages(true));
$block = $this->getLayout()->createBlock('checkout/cart_shipping')->setTemplate( 'checkout/cart/shipping.phtml');
return $block->toHtml();
}
Updated block issue solved using $this->_getQuote()->collectTotals(); before $this->_getQuote()->save();

Resources