call to codeigniters controller function is not working - codeigniter

i am using $.post() to call a controllers function from view(though i know its bad practice) and in that function i am loading a view and its not working.
this is HTML code : <li id='files' class="active" >My Files</a></li>
this is JS Code :
$("#files").click(function()
{
alert('hi2'); //just for checking
var loadUrl = "/Fast-Docs/index.php/Docs/updatefiles";
$.post(
loadUrl,
{un:"<?php echo $username?>"});
});
this is function in controller:
public function updatefiles()
{
$this->load->model('DocsModel');
$un=$this->input->post('un');
$files=$this->DocsModel->getAllFiles($un);
$data['files']=$files;
$this->load->view('files',$data);
}

You need to actually display your code after the ajax call, ie
$.post(
loadUrl,
{un:"<?php echo $username?>"}
});
Becomes
$.post(
loadUrl,
{un:"<?php echo $username?>"},
function(data) {
$("#yourDiv").html(data);
}
});

Related

Json Data print after insert a record using Jquery Ajax in CodeIgniter

I am using Jquery Ajax in Codeigniter, after register a user via bootstrap modal I got JSON data as below instead of fetching the data from table. Where I am wrong? please help!
{"success":true,"type":"add"}
Here is my Jquery function
```
<script>
$(function(){
display();
//add new
function display(){
$.ajax({
type:'ajax',
url:'<?php echo base_url()?>frame_cont/display',
async: false,
dataType:'json',
success:function(data){
var html='';
var i;
for(i=0;i<data.length;i++){
html +='<tr>'+
'<td>'+data[i].id+'</td>'+
'<td>'+data[i].username+'</td>'+
'<td>'+data[i].email+'</td>'+
'<td>'+data[i].password+'</td>'+
'<tr>';
}
$('#showdata').html(html);
},
error:function(){
alert('Could not get Data from Database');
}
});
};
});
</script>```
and here is controller class
<?php
class Frame_cont extends CI_Controller{
public function index(){
$this->load->view('index');
}
public function register(){
$this->load->model('frame');
$result=$this->frame->insert();
$msg['success']=false;
$msg['type']='add';
if($result){
$msg['success']=true;
}
echo json_encode($msg);
}
public function display(){
$this->load->model('frame');
$result=$this->frame->display();
echo json_encode($result);
}
}
This is all about the code and sorry for the english
in your register function you doing echo json_encode($msg); at the end. you should echo inserted value inside if condition
The issue occur because of I am using type="submit" instead of type="button" in my form button.

codeigniter Click button to call a view

I am having a view with 2 buttons in my codeigniter view:
<div class="btn-main col-md-3 col-md-offset-3">
<button id="simu-mono" type="button" class="btn btn-default">SIMULATION MONO SITE</button>
</div>
<div class="btn-main col-md-3">
<button id="simu-multi" type="button" class="btn btn-default">SIMULATION MULTI SITE</button>
</div>
I would like to call another a controller to launch then a view when the button is clicked
I tried out to call the controller simu_mono by javascript, putted on /controller/simu_mono.php but doesn' t work
$(document).ready(function(){
$("#simu-mono").click(function(){
type:'GET',
url:'simu_mono'
});
$("#simu-multi").click(function(){
});
});
simu_mono.php:
<?php
class simu_mono extends CI_Controller {
public function index()
{
$this->load->view('simu_mono');
echo 'Hello World!';
}
}
?>
Thanks for your helps
Cheers
Please, if u want to redirect only use following code:
$(document).ready(function(){
$("#simu-mono").click(function(){
window.location = base_url + "/simu_mono";
});
$("#simu-multi").click(function(){
window.location = base_url + "/simu_multi";
});
});
Note that you might need base_url, use this snippet to load base_url in JavaScript variable
<script>
base_url = <?= base_url()?>
</script>
put code above in some kind of view that is loaded always (before any other JavaScript code is executed)
Additional step would be to set up routes that take care of ugly underscore symbol (_)
something like:
routes.php
$route['simu-mono'] = "simu_mono";
$route['simu-multi'] = "simu_multi";
this way you go to your page and controller following way: yourserver.ufo/simu-mono and yourserver.ufo/simu-multi
You're not doing any class of AJAX call within your javascript. I assume you're using jQuery, so, your call should be something like:
$("#simu-mono").click(function(){
$.ajax({
url: "http://your-url.com/controller/method",
type: 'post', // <- Or get option, whatever you prefer
dataType: 'json', // <- This is important to manage the answer in the success function
//data: { param1: "value1", param2: "value2"}, <- You could add here any POST params you wanted
success: function(data){
if (data.view) {
$('#here_view').html(data.view); // <- '#here_view' would be the id of the container
}
if (data.error){
console.log(data.error);
}
}
});
});
This will call your method, where you will have to indicate you want to pass the view:
<?php
class simu_mono extends CI_Controller {
public function index()
{
$return = array(
'view' => $this->load->view('simu_mono')
);
echo json_encode( $return );
}
}
?>
json_encode will allow you easily pass vars and data from PHP to your javascript, and manage them in the client view. As you see in the javascript, I added data.error, this is just in case you'll have more logic, maybe change the view you're sending, send an error if you sent data and want to control them, etc.
Of course, in your javascript you could take the url from the clicked button, and in data.view parat of the success function, you may print in the screen a modal, send the view to a container, whatever you wanted, XD

Loading files via AJAX with CodeIgniter/MVC

I'm currently in the process of rewriting an entire site of mine so that it's compatible with CI. I'm fairly new with CI and the MVC pattern in general. I followed this tutorial and have made a pretty decent template for the view part of the MVC pattern. The thing is, a lot of my site uses jQuery/AJAX to make it more dynamic. For example, on all of my pages on my site, I have an input field that uses jQuery to load a PHP file upon keyup.
<script type="text/javascript">
$("#search_bar").keyup(function(){
var search = $("#search_bar").val();
var url = "search_bar.php";
var data = "q="+ search;
$('#livesearch').load(url, data);
$("#livesearch").slideDown("fast");
});
</script>
<input type='text' maxlength='30' id='search_bar' autocomplete='off' placeholder='Browse Teams' />
<div id='livesearch' style='display:none;'></div>
All of the backend work that's required to load the results happens in the PHP file that loaded via jQuery (search_bar.php). So, should "search_bar" be its own View that's triggered by its own Controller and then Modeled by a model called "search_bar"? Again, I'm very new to the MVC pattern and am not quite sure how properly integrate AJAX with a object oriented framework like CI.
Thanks
Directly calling the view in ajax request is not a good practice call the controller which loads the view or directly do the stuff in the controller's function
<script type='text/javascript'>
$('#search_bar').keyup(function(){
$.ajax({
url: 'yourcontrollername/search_bar_yourfunction',
type:'POST',
data: {q: search,
success: function(result){
$("#livesearch").html(result);
$("#livesearch").slideDown("fast");
}
});
});
</script>
Your controller code
class yourcontrollername extends My_Controller {
public function search_bar_yourfunction() {
//do your stuff and store in the $data[] array
$this->load->view("search_bar",$data); //search_bar.php
die();
}
}
}
You should go from your View to the Controller:
<script type='text/javascript' language='javascript'>
$('#search_bar').keyup(function(){
$.ajax({
url: 'search_bar.php',
type:'GET',
data: {q: search,
success: function(result){
//Insert code here
} // End of success function of ajax form
}); // End of ajax call
});
</script>
Then in your controller, load a model if necessary:
public function weigeren() {
$user = $this->CI->authex->getUserInfo();
$data['title'] = "Test";
$this->load->model('search_model');
$query = $this->input->get('q');
if (isset($user)) {
echo $this->search_model->search($query);
}
}
I find one way to load ajax (jquery) in CodeIgniter 3. Example,
structure of folder:
controllers/Upload.php
view/admin/ajax_view/ajax_images.php
controllers/upload:
public function process()
{
$data['my_picture'] = array(
'pic_id' => '1',
'pic_path' => 'http://example.com/images',
);
$this->load->view('admin/ajax_view/ajax_images', $data);
}
view/admin/ajax_view/ajax_images:
<?php foreach($my_picture as $key => $row): ?>
<td><?php echo $my_picture['pic_path']; ?></td>
<?php endforeach; ?>
view/admin/form_upload:
<tbody>
<tr class="trbody">
<th scope="row">1</th>
<!-- <td></td> --> <!--comments this because appends element jquery-->
</tr>
</tbody>
<script type="text/javascript">
$(document).ready(function(){
$('#my_button').click(function(e){
e.preventDefault;
$.ajax({
url: 'upload/process',
dataType: 'text',
type: 'post',
success: function(data){
$('.trbody')
.append(
'<td>'+ data + '</td>'
);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
});
</script>
To this way, I separated view of ajax of whole pages and load ajax view when
event trigger.

Page navigation using ajax in codeigniter

IN codeigniter I am repeatedly using the controllers to load all the templates of my page....
I have divided the page into header, top navigation, left navigation and content and footer.
This is what I do at present
public function get_started() {
if (test_login()) {
$this->load->view('includes/header');
$this->load->view('includes/topnav');
$this->load->view('includes/leftbar');
$this->load->view('login_nav/get_started');
$this->load->view('includes/footer');
} else {
$this->load->view('errors/needlogin');
}
}
Is there any jquery-ajax helpers or plugins in codeigniter which would allow me to keep header footer and topnavigation static and allow me to load specific views using ajax.
thanks in advance..
You can use the constructor to set your static header:
//in your controller
public $data;
function __construct()
{
$this->data['header'] = 'static_header';
$this->data['static_footer'] = 'static_footer';
}
function get_started(){
if (test_login()) {
$this->data['subview'] = 'login_nav/get_started';
} else {
$this->data['subview'] = 'errors/needlogin';
}
$this->load->view('template',$this->data);
}
function get_page(){
$view = $this->load->view('your_dynamic_view','',TRUE);
print json_encode(array('success' => TRUE, 'view' => $view);
}
// in your template.php
<div id="header"><?php echo $this->load->view('header');?></div>
<div id="subview"><?php echo $this->load->view('subview');?></div>
<div id="footer"><?php echo $this->load->view('footer');?></div>
// in your script - used to load dynamic view on you subview div
<script type="text/javascript">
$.get('controller/get_page',{},function(data){
if(data.success){
$('#subview').html(data.view);
}
},'json')
</script>
Message me if there's a problem with my code
Happy coding ---> :D
The answer from PinoyPal is theoreticaly correct, but it didn't work for me in practice because it lacks one major detail: a route.
Take a look at this part of their script:
// in your script - used to load dynamic view on you subview div
<script type="text/javascript">
$.get('controller/get_page',{},function(data){
if(data.success){
$('#subview').html(data.view);
}
},'json')
</script>
Here in place of 'controller/get_page' there should be a url for an actual GET request. This is how it is generally supposed to look:
$("a.your_navigation_element_class").on('click',function(e){
e.preventDefault(); //this is to prevent browser from actually following the link
var url = $(this).attr("href");
$.get(url, {}, function(data){
if (data.success){
$('#subview').html(data.view);
}
},'json')
});
Now here's a question: where will this GET request end up? In the default controller route, that's right. This is why you need to 1) modify your request url and 2) set up a route, so that this request will be passed to an ajax-serving controller. Or just add an ajax-serving function to your default controller and re-route ajax requests to it.
Here follows how it should all look wrapped up
In ...\application\controller\Pages.php:
class Pages extends CI_Controller {
...
public function serve_ajax ($page) {
$view = $this->load->view($page, '', TRUE);
print json_encode( array('success' => TRUE, 'view' => $view);
}
...
}
In ...\application\config\routes.php:
...
$route['ajax/(:any)'] = 'pages/serve_ajax/$1';
On your page:
...
<body>
...
<div id="page"></div>
...
<script>
$("a.navigation").on('click',function(e){
e.preventDefault();
var url = $(this).attr("href");
$.get("/ajax" + url, {}, function(data){
//The trailing slash before "ajax" places it directly above
//the site root, like this: http://yourdomain.com/ajax/url
if (data.success){
$('#page').html(data.view);
}
},'json')
});
</script>
</body>
And you're all set.

Codeigniter ajax information needed

I am a beginner with Codeigniter. This will be my first time to use Ajax. I want only "content" part change when I click the navigation links. I need to learn how to use ajax in my site.
MY_Controller.php :
class MY_Controller extends CI_Controller {
protected $data = array();
function __construct() {
parent::__construct();
}
function render_page($view) {
if( ! $this->input->is_ajax_request() )
{
//do this to don't repeat in all controllers...
$this->load->view('templates/header', $this->data);
//menu_data must contain the structure of the menu...
//you can populate it from database or helper
}
$this->load->view($view, $this->data);
if( ! $this->input->is_ajax_request() )
{
$this->load->view('templates/menu');
$this->load->view('templates/footer', $this->data);
}
}
My home/about controller view function:
public function view($page = 'home')
{
$this->load->helper('text');
$this->data['records']= $this->services_model->getAll();
if ( ! file_exists('application/views/pages/'.$page.'.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
$data['title'] = ucfirst($page); // Capitalize the first letter
$this->render_page('pages/'.$page,$data);
}
I think , I could enable ajax in MY_Controller.php. What to do after this? How shall i enable posts in the view?
Edit : I made some more research about jquery and ajax.
This is my navigation menu part of html :
<div id="sidebar-content">
<ul id="menu">
<li class="current">ANASAYFA</li>
<li>HAKKIMIZDA</li>
......
I have written and ajax.js file in the head section as :
//Navigation
$("#sidebar-content ul li a").click( function(){
$.ajax({
url: "<?php echo site_url('about'); ?>",
type: 'POST';
data: JSON,
success: function(msg) {
$('#content').body(msg);
}
});
});
return false;
});
Can you refine my code ? One more problem is :If I use the ajax in the head part,how can i post different pages as urls?
Your problem is a little ambiguous, but here are some issues I can see with your JQuery:
You have set data: Json in your JQuery, but it looks like you are
returning HTML, so change this to HTML.
You have a semi colon after type: post when it should be just a
comma
The url points to the controller, not the method. Change it to "<?php echo site_url('about/view'); ?>",
There is no such thing as JQuery .body(), you want .html() or the complete line for your success function: $('#content').html(msg);. Obviosult make sure you have a element named id="content".JQuery will then replace this with the reponse from the server, which should be pure html returned from your controller. You can use codeigniters $this->load->view() to return the correct file.
Other notes - it seems you need to read up on JQuery, especially the ajax function
Here's a good tutorial to follow about using Ajax with CI - http://net.tutsplus.com/tutorials/php/codeigniter-from-scratch-day-8-ajax/
Finally, use the console and network features in Chrome's developer tools web inspector or get Firebug for Firefox this way you can see js errors and monitor ajax requests (XHR)

Resources