ajax bugs in codeigniter - codeigniter

i have a controller having following script
class get extends CI_Controller
{
function get_password()
{
$this->load->model('fetch_model');
$user_pass=$this->fetch_model->get_password();
$data['user_pass'] = json_encode($user_pass);
echo $data['user_pass'];
}
}
and a script on view page as this
function get_password(){
$.post("<?php echo base_url();?>admin.php/get/get_password",function(data)
{
for(i=0;i<data.length;i++)
{
$('#password').val(data[i].password);
$('#username').val(data[i].username);
}
},"json");
}
now if i use the following script in model then the ajax post is working perfectly..
class fetch_model extends CI_Model
{
function get_password()
{
return $this->db->query("SELECT * FROM td_admin_user")->result_array();
}
}
but when i change the model script into this, then the ajax script isnt working
class fetch_model extends CI_Model
{
function get_password()
{
foreach($this->db->query("SELECT * FROM td_admin_user")->result() as $r_pass)
{
$pass=$r_pass->password;
$user=$r_pass->username;
}
$user_pass=array('username'=>$user,
'password'=>$pass);
return $user_pass;
}
}
but to be very frankly, i need to send data in the following way
$user_pass = array('username'=>$user, 'password'=>$pass);
and not as result_array()
so please help me in this context, thanks in advance

This is not a bug! Did you even look at what type of data is returned in each call?
In your JS, you are using:
$('#password').val(data[i].password);
Where data is an indexed array - exactly what is returned by ->result_array()
But you want it to be a key based array:
$user_pass=array('username'=>$user, 'password'=>$pass);
If that's the case, you should forget using the for loop on JS (specially if your query only results in one row) and use
$('#password').val(data.password);
Instead.
Also look at console.log (if you are using firebug/developer tools) and try print_r or var_dump on the PHP side to understand the data formats you are returning.

Related

Model function call in a Template

I have model called Page and view called view.blade.php
//this is a model
public function Test()
{
return 'test';
}
//this is the template
<h1>{{$Test}}</h1>
how can I do this? please help me?
As I understood, you want to call model function inside your view? Do it like this:
{{Page::Test()}}
Edit:
If you need to use $this in your function to pass some data for your function (if that was what you were asking in comments below), you can do something like this. First define your static function:
public static function getPages()
{
return [
//some logic (get all pages)
];
}
Now, let's say this function will return multiple pages. If you want to filter them, and to display only one page on your view, you can pass the id of that view as a parameter to a next function which you will then pass to your view:
public function getSinglePage()
{
return self::getPages()[$this->id];
}
Lastly, in order to display the output of that function, use the same method as above, with new function name:
{{Page::getSinglePage()}}

Returning same variable to every controller in laravel

I need to send the same result to almost every view page, so I need to bind the variables and return with every controller.
My sample code
public function index()
{
$drcategory = DoctorCategory::orderBy('speciality', 'asc')->get();
$locations = Location::get();
return view('visitor.index', compact('drcategory','locations'));
}
public function contact()
{
$drcategory = DoctorCategory::orderBy('speciality', 'asc')->get();
$locations = Location::get();
return view('visitor.contact', compact('drcategory','locations'));
}
But as you see, I need to write same code over and over again. How can I write it once and include it any function whenever I need?
I thought about using a constructor, but I cannot figure out how I can implement this.
You are able to achieve this by using the View::share() function within the AppServicerProvider:
App\Providers\AppServiceProvider.php:
public function __construct()
{
use View::Share('variableName', $variableValue );
}
Then, within your controller, you call your view as normal:
public function myTestAction()
{
return view('view.name.here');
}
Now you can call your variable within the view:
<p>{{ variableName }}</p>
You can read more in the docs.
There are a few ways to implement this.
You can go with a service, a provider or, like you said, within the constructor.
I am guessing you will share this between more parts of your code, not just this controller and for such, I would do a service with static calls if the code is that short and focused.
If you are absolutely sure it is only a special case for this controller then you can do:
class YourController
{
protected $drcategory;
public function __construct()
{
$this->drcategory = DoctorCategory::orderBy('speciality', 'asc')->get();
}
// Your other functions here
}
In the end, I would still put your query under a Service or Provider and pass that to the controller instead of having it directly there. Maybe something extra to explore? :)
For this, you can use View Composer Binding feature of laravel
add this is in boot function of AppServiceProvider
View::composer('*', function ($view) {
$view->with('drcategory', DoctorCategory::orderBy('speciality', 'asc')->get());
$view->with('locations', Location::get());
}); //please import class...
when you visit on every page you can access drcategory and location object every time
and no need to send drcategory and location form every controller to view.
Edit your controller method
public function index()
{
return view('visitor.index');
}
#Sunil mentioned way View Composer Binding is the best way to achieve this.

How do I send data to partial views from controller in laravel?

I have setup my navigation menu from a ViewComposer (see laravel view composers: https://laravel.com/docs/5.6/views#view-composers) like this
View::composer('partials.nav', function ($view) {
$view->with('menu', Nav::all());
});
What I need is that from some controllers to setup which navigation item is active, ie "current section".
Question:
How do I send from some controllers a variable to "partials.nav" like currentNavItem?
Do I send it with the rest of the variables for returned view?
like
return view('page.blade.php",$viewVariables + $optionalVariablesForPartialsViews);
It looks spammy
Side notes:
I use laravel 5.6
Later edit
It looks Laravel 5.1 : Passing Data to View Composer might be an options. I will try and get back .
Because the $variable you want to send differs in different controller's actions yes you need to specify the $variable
return view('page.blade.php",$viewVariables,$variablesForPartialsViews);
of course you might need to set a default value for the $variable in order to avoid undefined variable error
You should handle the parameters.
for exemple:
public function compose(View $view)
{
$view->with('page', $this->getPage());
}
public function getPage()
{
$viewVariables = 2;
$optionalVariablesForPartialsViews = 1;
return $viewVariables + $optionalVariablesForPartialsViews;
}
Under your app folder make a class named yourClassNameFacade. Your class would look like this.
class yourClassNameFacade extends Facade
{
protected static function getFacadeAccessor()
{
return 'keyNameYouDecide';
}
}
Then go to the file app/Providers/AppServiceProvider.php and add to the register function
public function register()
{
$this->app->bind('keyNameYouDecide', function (){
//below your logic, in my case a call to the eloquent database model to retrieve all items.
//but you can return whatever you want and its available in your whole application.
return \App\MyEloquentClassName::all();
});
}
Then in your view or any other place you want it in your application you do this to reference it.
view is the following code:
{{ resolve('keyNameYouDecide') }}
if you want to check what is in it do this:
{{ ddd(resolve('keyNameYouDecide')) }}
anywhere else in your code you can just do:
resolve('keyNameYouDecide'))

codeigniter child function after submit parent function

In my project I have a controller call load and it has a fuction call search() that has a form, i want to submit this form in a child function of search() like this,,
localhost/ci/index.php/load/search
to
localhost/ci/index.php/load/search/something/
how can i do this after submission a form?
this is my contoller like
class Load extends CI_Controller {
function search() {
$this->load->view('search');
}
function something() {
$this->load->view('something');
}
}
This is not child function something()
You can define routes as per your requirements.
After search function call , you can use redirect() method, that will redirect to your route like 'base_url/controller/search/searchresult/'.
Routes.php
$route['Load/search/searchresult'] = 'Load/something';
Load Controller code :
class Load extends CI_Controller {
function search() {
$this->load->view('search');
// after form submission
redirect('Load/search/searchresult');
}
function something() {
$this->load->view('something');
}
}
This is not a child function of search function so you can call it like
localhost/ci/index.php/load/something/
Add this url to your form action and your form will be submitted to something() function
For clarity: localhost/ci/index.php/load/search/something/ does this...
Enters search() method of Load and provides something as a parameter e.g. search($param = 'something') (this is not correct syntax but just for show).
function search($term = null) {
if (is_null($term)) {
// user hasn't searched
} else {
// user searched for $term e.g. something
}
}
The only way you can achieve what you want is to either use the above somehow to your advantage knowing that /something will have to be the search parameter. Or you can use routing as another answerer suggested.

Codeigniter : calling a method of one controller from other

I have two controllers a and b.
I would like to call a method of controller a from a method of controller b.
Could anyone help explain how I can achieve this?
This is not supported behavior of the MVC System. If you want to execute an action of another controller you just redirect the user to the page you want (i.e. the controller function that consumes the url).
If you want common functionality, you should build a library to be used in the two different controllers.
I can only assume you want to build up your site a bit modular. (I.e. re-use the output of one controller method in other controller methods.) There's some plugins / extensions for CI that help you build like that. However, the simplest way is to use a library to build up common "controls" (i.e. load the model, render the view into a string). Then you can return that string and pass it along to the other controller's view.
You can load into a string by adding true at the end of the view call:
$string_view = $this->load->view('someview', array('data'=>'stuff'), true);
test.php Controller File :
Class Test {
function demo() {
echo "Hello";
}
}
test1.php Controller File :
Class Test1 {
function demo2() {
require('test.php');
$test = new Test();
$test->demo();
}
}
Very simple way in codeigniter to call a method of one controller to other controller
1. Controller A
class A extends CI_Controller {
public function __construct()
{
parent::__construct();
}
function custom_a()
{
}
}
2. Controller B
class B extends CI_Controller {
public function __construct()
{
parent::__construct();
}
function custom_b()
{
require_once(APPPATH.'controllers/a.php'); //include controller
$aObj = new a(); //create object
$aObj->custom_a(); //call function
}
}
I agree that the way to do is to redirect to the new controller in usual cases.
I came across a use case where I needed to display the same page to 2 different kind of users (backend user previewing the page of a frontend user) so in my opinion what I needed was genuinely to call the frontend controller from the backend controller.
I solved the problem by making the frontend method static and wrapping it in another method.
Hope it helps!
//==========
// Frontend
//==========
function profile()
{
//Access check
//Get profile id
$id = get_user_id();
return self::_profile($id);
}
static function _profile($id)
{
$CI = &get_instance();
//Prepare page
//Load view
}
//==========
// Backend
//==========
function preview_profile($id)
{
$this->load->file('controllers/frontend.php', false);
Frontend::_profile($id);
}
I posted a somewhat similar question a while back, but regarding a model on CI.
Returning two separate query results within a model function
Although your question is not exactly the same, I believe the solution follows the same principle: if you're proposing to do what you mention in your question, there may be something wrong in the way you're coding and some refactoring could be in order.
The take home message is that what you're asking is not the way to go when working with MVC.
The best practice is to either use a Model to place reusable functions and call them in a controller that outputs the data through a view -- or even better use helpers or libraries (for functions that may be needed repeatedly).
You can do like
$result= file_get_contents(site_url('[ADDRESS TO CONTROLLER FUNCTION]'));
Replace [ADDRESS TO CONTROLLER FUNCTION] by the way we use in site_url();
You need to echo output in controller function instead of return.
You can use the redirect() function.
Like this
class ControllerA extends CI_Controller{
public function MethodA(){
redirect("ControllerB/MethodB");
}
}
Controller to be extended
require_once(PHYSICAL_BASE_URL . 'system/application/controllers/abc.php');
$report= new onlineAssessmentReport();
echo ($report->detailView());
You can use the redirect URL to controller:
Class Ctrlr1 extends CI_Controller{
public void my_fct1(){
redirect('Ctrlr2 /my_fct2', 'refresh');
}
}
Class Ctrlr2 extends CI_Controller{
public void my_fct2(){
$this->load->view('view1');
}
}
very simple
in first controllr call
$this->load->model('MyController');
$this->MyController->test();
place file MyController.php to /model patch
MyController.php should be contain
class MyController extends CI_Model {
function __construct() {
parent::__construct();
}
function test()
{
echo 'OK';
}
}

Resources