codeigniter get returned data variable from model in controller and use it in conditional statement - codeigniter

what is wrong with my search implementation, here what i wish to achieve.
view page(form) -> controller(form data variable) -> model(query database and pass to controller) if there's a result return TRUE else return FALSE -> controller(get data from model) if true display data in table else if FALSE display a no results returned message.
here are my pages:
view:
<form action="<?php echo site_url('retrieve')?>" method="post">
<input type="text" name="id">
....
</form>
model:
public function retrieve($id)
{
$search = "SELECT * FROM table";
$result = $this->db->conn_id->prepare($search);
$result->execute();
if($result->rowCount()>0){
return $query_result = $result->fetchAll(PDO::FETCH_ASSOC);
}
}
controller:
public function retrieve_info()
{
$id = $this->input->post('id'),
$this->load->model('search_model');
$this->search_model->retrieve($id);
$data['query_result'] = $this->search_model->retrieve($id);
$this->load->view('display',$data);
}

First the form action is linking to the retrieve function in the controller. However, from your example there is no retrieve function in your controller, only in your model.
view:
<form action="<?php echo site_url('retrieve')?>" method="post">
<input type="text" name="id">
....
</form>
model:
public function retrieve($id)
{
$search = "SELECT * FROM table";
$result = $this->db->conn_id->prepare($search);
$result->execute();
if($result->rowCount()>0){
return $query_result = $result->fetchAll(PDO::FETCH_ASSOC);
}
}
controller:
public function retrieve()
{
if($_POST){
$id = $this->input->post('id'),
$this->load->model('search_model');
$data['query_result'] = $this->search_model->retrieve($id);
$this->load->view('display',$data);
}else {
//form failed to submit via post
}
}

Related

Creating default object from empty value using laravel 6 and ajax

i have in an annonces table a multiple images, i want to update multiple images, but it gives me error:
Creating default object from empty value knowing that i tried to transform multipleimage to a given json.in the console it gives me the name of the images to select.
AnnoncesController.php
public function filesUpdate(Request $request,$id)
{
$Annonce=Annonce::find($id);
$data = array();
if($request->hasFile('images'))
{
foreach($request->file('images') as $file)
{
$path = $request->images->store('annonces');
$Annonce->images = $path;
array_push($data,$path);
}
}
$Annonce->images = json_encode($data);
$Annonce->save();
return Redirect::to("annonces")
->withSuccess('Great! file has been successfully uploaded.');
}
web.php
Route::post('annonces/filesUpdate','AnnoncesController#filesUpdate');
details.blade.php
<form method="post" action="{{url('annonces/filesUpdate')}}" enctype="multipart/form-data"
class="dropzone" id="dropzone">
<input type="hidden" name="_method" value="PUT">
{{ csrf_field() }}
</form>
<script type="text/javascript">
Dropzone.options.dropzone =
{
maxFilesize: 12,
renameFile: function(file) {
var dt = new Date();
var time = dt.getTime();
var images = time+file.name
console.log(time+file.name);
return images;
},
acceptedFiles: ".jpeg,.jpg,.png,.gif",
addRemoveLinks: true,
timeout: 50000,
success: function(file, response)
{
console.log(response);
},
error: function(file, response)
{
return false;
}
};
</script>
You are not passing the id as route parameter in the form action so the $id value received in filesUptate method in controller will be null. You have to pass the $Annonce->id as route parameter via form action
//When you send this view as response from edit method you need to pass
//either $Annonce object or at least the $Annonce->id as $AnnonceId to the view
//If you pass the entire $Annonce object then append $Annonce->id as below
//to the form action or replace it with $AnnonceId if you are passing only
//$AnnonceId from the edit method of the controller
<form
method="post"
action="{{url('annonces/filesUpdate/' . $Annonce->id)}}"
enctype="multipart/form-data"
class="dropzone" id="dropzone"
>
<input type="hidden" name="_method" value="PUT">
{{ csrf_field() }}
</form>
The error probably arises as you are trying to call store method on array.
Try the below
public function filesUpdate(Request $request,$id)
{
$Annonce=Annonce::findOrFail($id);
$data = array();
if($request->hasFile('images'))
{
foreach($request->file('images') as $file)
{
//Trying to call store on an array here
//$request->images is not an instance of UploadedFile
//$path = $request->images->store('annonces');
//$file is an instance of UploadedFile
//so you can call store method on it
$data[] = $file->store('annonces');
}
}
$Annonce->images = json_encode($data);
$Annonce->save();
return Redirect::to("annonces")
->withSuccess('Great! file has been successfully uploaded.');
}
You can also use $casts property to let Laravel handle the casting of images attribute automatically
class Annonce extends Model
{
protected $casts = [ 'images' => 'array'];
}

laravel-5.8:The POST method is not supported for this route. Supported methods: GET, HEAD

hi m trying to add products in cart but it says: The POST method is not supported for this route. Supported methods: GET, HEAD.. (View: \resources\views\product\detail.blade.php), I wants that by clicking the addtocart it redirect me to that age with products,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,...…………………………………..,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
route:
Route::get('cart', 'Admin\ProductController#cart')->name('product.cart');
Route::get('/addToCart/{product}', 'Admin\ProductController#addToCart')->name('addToCart');
controller:
public function cart()
{
if (!Session::has('cart')) {
return view('products.cart');
}
$cart = Session::has('cart');
return view('product.cart', compact('cart'));
}
public function addToCart(Product $product, Request $request)
{
if(empty(Auth::user()->email)){
$data['email'] = '';
}else{
$data['email'] = Auth::user()->email;
}
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$qty = $request->qty ? $request->qty : 1;
$cart = new Cart($oldCart);
$cart->addProduct($product);
Session::put('cart', $cart);
return redirect()->back()->with('flash_message_success', 'Product $product->title has been successfully added to Cart');
}
view:
<form method="POST" action="{{ route('addToCart') }}" enctype="multipart/form-data">
<div class="btn-addcart-product-detail size9 trans-0-4 m-t-10 m-b-10">
#if($product->product_status == 1)
<!-- Button -->
<button class="flex-c-m sizefull bg1 bo-rad-23 hov1 s-text1 trans-0-4">
Add to Cart
</button>
#else Out Of Stock #endif
</div>
</form>
model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Cart
{
private $contents;
private $totalQty;
private $contentsPrice;
public function __construct($oldCart){
if ($oldCart) {
$this->contents = $oldCart->contents;
$this->totalQty = $oldCart->totalQty;
$this->totalPrice = $oldCart->totalPrice;
}
}
public function addProduct($product, $qty){
$products = ['qty' => 0, 'price' => $product->price, 'product' => $product];
if ($this->contents) {
if (array_key_exists($product->slug, $this->contents)) {
$product = $this->contents[$product->slug];
}
}
$products['qty'] +=$qty;
$products['price'] +=$product->price * $product['qty'];
$this->contents[$product->slug] = $product;
$this->totalQty+=$qty;
$this->totalPrice += $product->price;
}
public function getContents()
{
return $this->contents;
}
public function getTotalQty()
{
return $this->totalQty;
}
public function getTotalPrice()
{
return $this->totalPrice;
}
}
First of all your form method in the view is POST but you don't have a post route.
Second, the route that you have defined expect a parameter(product) you can change the form action as below BUT I think you want to send the user to another page so you can use a link instead of form.
Here's the form action:
action="{{ route('addToCart', $product->id) }}"
And if you want to use link, you can do something like this:
.....
Your method should be POST. In the form, you're calling it Post method but in route.php file, you defined as get to change it as Route::post
Route::post('/addToCart/{product}', 'Admin\ProductController#addToCart')->name('addToCart');
In addition, your route.php file expecting {product} so you need to pass it in form route so your action be like {{ route('addToCart',$product->id) }}
<form method="POST" action="{{ route('addToCart',$product->id) }}" enctype="multipart/form-data">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

codeigniter session with ajax input is not working

view
<input type="text" class="form-control" placeholder="Username" name="username" id="username">
<input type="password" class="form-control" placeholder="Password" name="password" id="password">
<button type="button" class="btn btn-primary btn-block btn-flat" id="login">Sign In</button>
here i pass the values to the controller using ajax
<script>
$(function()
{
$('#login').click(function()
{
var username=$("#username").val();
var password=$("#password").val();
$.ajax({
url:"<?php echo base_url();?>home/check_login",
type:"POST",
async:false,
data:{username:username,password:password},
success:function(data)
{
var obj = JSON.parse(data);
var count = Object.keys(obj).length;
console.log(obj);
console.log(count);
if(obj.length==1)
{
window.location.href = "<?php echo base_url();?>home/show_dashboard";
}
else if(obj.length==0)
{
$('#modal_warning').modal('show');
}
}
});
});
});
</script>
and my controller is
public function check_login()
{
$username= $this->input->post('username');
$password= $this->input->post('password');
$newdata = array(
'username' => $username,
);
$this->session->set_userdata('ci_session',$newdata);
$details=$this->user_model->check_username($username,$password);
echo json_encode($details);
}
when click log out button
public function log_out()
{
if($this->session->unset_userdata('ci_session'))
{
$this->load->view('login');
}
else
{
echo "nooo";
exit;
}
}
when i click the logout button it gives me "noo" which i placed in else part.
When i try to print the session data, it prints nothing. How can I set session which data is passing by ajax.
I also loaded session library
You are doing $this->set_userdata('ci_session',$newdata); without the session. Do it like so to set session variables. $this->session->set_userdata('ci_session',$newdata);
Also make sure the session driver is loaded. To access the session variable you can do print_r($this->session->ci_session)
Further:
Unset userdata doesn't actually return anything:
/**
* Unset userdata
*
* Legacy CI_Session compatibility method
*
* #param mixed $key Session data key(s)
* #return void
*/
public function unset_userdata($key)
{
if (is_array($key))
{
foreach ($key as $k)
{
unset($_SESSION[$k]);
}
return;
}
unset($_SESSION[$key]);
}
hence its always evaluating to false. The function itself is just an alias for unset($_SESSION[$key]) you can view the function in the session core file. There is no need for the conditional statement; just $this->session->unset_userdata('ci_session'); redirect(...); is sufficient.

Magento 1.8.0.0: Add custom payment method redirecting to a new page

I'm working locally with magento 1.8.0.0. I succeeded to create a custom payment method. The method is appearing to the list of payment method at the "Payment Information" during the checkout. The problem is that when I select it, it automatically brings a credit card form, which is not what I want. What I want is to select it and once I click the "continue" button I get redirected to another php page containing my own form.
Solution by OP.
For you who want to redirect to the gateway and want the gateway to redirect back to your controller's action method, here is how things work:
In the file app/code/local/Yourcompany/Yourmodule/Model/PaymentMethod.php ,do as follow:
class Yourcompany_Yourmodule_Model_PaymentMethod extends Mage_Payment_Model_Method_Abstract{
protected $_code = "yourmodule";
protected $_isGateway = true;
protected $_canAuthorize = true;
protected function _getCheckout() {
return Mage::getSingleton('checkout/session'); }
public function getOrderPlaceRedirectUrl() { return Mage::getUrl(yourmodule/index/youraction', array('_secure' => true)); }}
In the line return Mage::getUrl(yourmodule/index/youraction', array('_secure' => true)); , "index" means that my controller php file is named IndexController.php. You may change the name as you wish.
In the file app/code/local/Yourcompany/Yourmodule/controllers/IndexController.php , you may code as follow:
class Yourcompany_Yourmodule_IndexController extends Mage_Core_Controller_Front_Action{
public function indexAction() {
$this->loadLayout();
$block = $this->getLayout()->createBlock('Mage_Core_Block_Template','yourmodule',array('template' => 'yourmodule/redirect.phtml'));
$this->getLayout()->getBlock('content')->append($block);
$this->renderLayout(); }
/*In the response action, you may code like this*/
public function responseAction() {
$status=$_REQUEST['param1'];
$orderNo=$_REQUEST['param2'];
if(somecondition)
{
/*update order status */
$ordera = Mage::getModel('sales/order')->loadByIncrementId($orderNo);
$ordera->setState(Mage_Sales_Model_Order::STATE_PENDING_PAYMENT, true)->save();
$this->_redirect("checkout/onepage/success");
}
else
{
$this->_redirect("checkout/cart/");
}
} }
The indexAction() is redirecting to a template redirect.phtml file. This file will collect some parameters to send to the gateway (order number, customer name, total money, etc.). You may put that phtml file here:
app/design/frontend/base/default/template/yourmodule/redirect.phtml
Its content may be coded as follow:
<?php
$orderId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order = Mage::getSingleton('sales/order')->loadByIncrementId($orderId);
$order_amount=$order->getGrandTotal();
$customerData = Mage::getSingleton('customer/session')->getCustomer();
$customerAddressId = Mage::getSingleton('customer/session')->getCustomer()->getDefaultBilling(); //oder getDefaultShipping
$address = Mage::getModel('customer/address')->load($customerAddressId);
$customer_name=$address->getFirstname().' '.$address->getLastname();
$customer_email=$customerData->getEmail();
?>
<form name="myjs" method="post" action="http://yourgatewayaddreshere">
<input type="hidden" name="customername" value="<?php echo $customer_name; ?>">
<input type="hidden" name="customermail" value="<?php echo $customer_email; ?>">
<input type="hidden" name="TotalMoney" value="<?php echo $order_amount; ?>">
</form>
<script type="text/javascript">
document.myjs.submit();
</script>

Models in codeigniter

In CodeIgniter, I designed a page, which there is a login form, and a simple home page.
The validation I did client side validation only.
view login.php :-
<form name="login" id="login" action="<?php echo base_url() ?>login/success" onsubmit="return validatelogin()" method="post">
... HTML
<input type="text" id="username" name="username" />
<input type="password" id="passwrd" name="passwrd">
Javascript validation in the view page "login.php",
function validatelogin(){
var x=document.forms["login"]["username"].value;
var y=document.forms["login"]["passwrd"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
if (y==null || y=="")
{
alert("Password field must be filled out");
return false;
}
if(x!="monisha" && y!="monisha"){
alert("Username and Password incorrect");
return false;
}
return true;
}
Controller - login.php :-
class Login extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->library('session');
}
function index(){
$this->load->view('login');
}
function success() {
$data = array('username' => "monisha");
$this->session->set_userdata($data);
redirect ('home');
}
}
I created the table "login", which is having the username and password fields.
I need to validate it using the database and the database query. Can anybody please assist me on what all changes I have to do in controller file, and the view page, to get this done.?
Learn form validation in CI first! http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html
You need to change this accordingly.
In Controller:
$this->load->helper(array('form')); #no need to do this if already loaded
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required||is_unique[table_name.column_name]');
$this->form_validation->set_rules('passwrd', 'Password', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('view_name');
}
else
{
redirect('controller/function', 'refresh');
}
In view page:
<?php echo validation_errors(); ?>

Resources