Use CodeIgniter to render to a view at a specific anchor - php

In order to delete a person from the database, I would like to check its connections with other objects like inventories before deleting then display a bootstrap dialog message within the same page.
Using CodeIgniter, I have a page named "Person's details" that has a link to check these connections like so:
<a class="btn btn-custom" href="person/checkConnections/<?=$ID_Person?>">Delete</a>
In the controller "person", the method "checkConnections" looks like:
public function checkConnections($ID_Person)
{
$data["strConnections"] = "3 connections with inventories found";
$this->load->view("person/showdetails", $data)
// launch the dialog box #deleteMsg
???
}
How can I launch the bootstrap dialog box which has an id="deleteMsg" and which is in the "Person's details" page?
if it was an html url, the url would look like : http://mywebsite/person/showdetails/134#deleteMsg. But how can I have the same result using the codeIgniter method to render a view?
I can check these connections when loading the page the first time. But it wouldn't be efficient to do it every time since the delete action is rarely used.

You can use ajax to call the delete method and then show the response in a model form like below.
$('.btn-custom').click(function(e){
var url = $(this).attr('href');
$.ajax({
type: 'GET',
url: url,
success: function(rtn)
{
//load the bootstrap model setting the rtn as html content.
}
});
return false;
});
the controller should return the html output of your view.
public function checkConnections($ID_Person)
{
$data["strConnections"] = "3 connections with inventories found";
echo $this->load->view("person/showdetails", $data, true);
}
note the third parameter true of the view load method, this will return the output of the view.

Related

Show data from another table with modal - Codeigniter

i have 2 tables
Now when i click detail , i want to show data from table 2 which have reportcode as i click on table 1 (image 1)
And now i want to show it on modal , so here is the example
1) click detail button -> get reportcode -> show reimbursename,etc to modal
Can you explain to me what should i do first ? and can you suggest me a plan please ,any answers will be appreciated. Thanks
My suggestion is:
1 - Add one class to detail button, i.e: detailButton and a data attribute or href with the especific reportCode.
<table>
<tr>
<td> ... </td>
<td> <button class='detailButton' href='<?php echo $reportCode; ?>' ... </button> </td>
2 - Add jquery to the bottom of the page:
$('.detailButton').click(function(e){
e.preventDefault();
var reportCode = $(this).attr('href');
var url = "yourUrl/controller/function";
$.post(url,{ code:reportCode },function(data){
//do stuff
//i.e: $('.modal').html(data).show();
});
});
Now you have a function that gets the reportCode, sends it to your controller by POST, you return something and the function gets the response and attach to a html.
Note, this way you must return a table from your controller. You could build dinamically too.
Hope it helps!
UPDATE:
You could check the values to your model and then use a exisitin template (for example one that generates the detail table), and return to your view as data to be attached at the correct position (method 1):
function detail(){
$getcode= $this->input->post('reportCode');
$data['showdetail'] = $this->model_expreport->showdetail($getcode);
$ret = $this->load->view('detail_template',$data,true); //return as data
print_r($ret);
}
Or you could use the Method 2:
function detail(){
$getcode= $this->input->post('reportCode');
$data['showdetail'] = $this->model_expreport->showdetail($getcode);
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($data));
}
This way, the view will recive a JSON that you could iterate and build your own page. Or you could create the full view and return it as data (in order to only append to your view).
You could use both.
In the view, you will recive either a full view:
$.post(url,{ code:reportCode },function(data){
$('#modal').html(data); //put the 'detail' response to the modal
}
Or with JSON you must iterate and build your own div dinamically, there are a lot of tutorials for this: https://uno-de-piera.com/cargar-json-con-jquery-y-codeigniter/

After getting value from javascript redirect to another page in codeigniter with url parameters

I am making a simple auto search, where when user after searching, the search results get displayed on the dropdown box. If he clicks to any of the search items, it will take the user to another page where more details will be shown regarding that item.
So as, if he clicks on "Discrete Maths", then the new page url will be
localhost/example/search?s=discrete+maths
and the details will be shown regarding that topic
My javascript code :
function searchclick(subid,subjct){
//subid is subject id and subjct is subject name
var search_var = {
action : "gosearch",
subid : subid,
subjct : subjct
};
$.ajax({
type : "POST",
url : "<?php echo base_url(); ?>search",
cache : false,
data : search_var,
success : function(r)
{
}
});
}
I have a controller called Search which loads the view known as search.
I want to pass those data to that controller which will then redirect to the Search view with the url like this --> localhost/example/search?s=discrete+maths as well as the title of the page will change to the name of the item searched.
I can't figure out a way. I'm new to codeigniter.
I just want to redirect to that view after getting the data and change the url parameters. Nothing else. Only this will be helpful.
After sending data to controller in controller do whatever you need to do and redirect directly to desired URL:
public function search() {
/* your code */
header("Location: http://www.example.com/");
}
If you need to send back some data to front end you can send new URL to JS on front end and redirect there:
// controller
public function search() {
/* your code */
$arr = array('redirect' => 'http://example.com/', 'other_data' => 1);
header('Content-Type: application/json');
echo json_encode( $arr );
}
// javascript
success : function(response){
window.location.replace(response['redirect'])
},
This is not codeigniter specific information. This is general AJAX method.

ng-repeat behaviour with $watch

I am newbie to AngularJs. I am using AngularJS as front end and Laravel As backend.
I have a situation where I want page to be refreshed on ajax success (when user post data).
I have template index.blade.php like this :
#extends(layout)
#section
header page
post page
main page
footer page
#endsection
Now thing is that User is posting update from post page and
on that success i want data to be refreshed which is on main page
function addpost ($scope, $http){
$scope.loadData = function(){
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
$http.post( baseurl+"alldata").success(function(data)
{
$scope.posts = data;
});
}
$scope.addComment = function(post){
if("undefined" != post.hoot){
// Angular AJAX call
$http({
method : "POST",
url :baseurl+ "url",
data : "post="+post
}).success(function(data){
$scope.posts = data;//json response
// here i want page to be refreshed or div refresh of sub-main page
});`
$scope.post = ' ';`
}
}
$scope.loadData();
}`
Now thing is that if i am posting data from other sub page and then showing it on other sub page. Iam calling addcomment to add posted data in model and then loaddata() to get all data from model for ng-repeat in a view.
if i am going to fire watch event . it will keep on refreshing model thus view data. Suppose i am working on comment section where we can like , dislike and comment on post. and i want to use ng-click event inside ng-repeat(which is refreshing view).
Test.controller('Testing',['$scope', '$http', function($scope,$http){
$scope.products = {};
$http.post( baseurl+"ajax/getall").success(function(data)
{
$scope.products = data;
});
$scope.$watch("products", function(newValue, oldValue) {
if (newValue === oldValue) { return; } // AKA first run
$scope.products= newValue;
});
});
$scope.Hello= function(){
alert("hello");
}
}]);
It will keep on refreshing page and thus don't click event inside ng-repeat which is ng-click.
I have fired ng-click="Hello()" event but it doesn't fire.
You can register a listener to $scope.data in any part of the application that had a reference to scope. This way, everything will keep up to date when data is updated.
Like so:
$scope.$watch('data', callback)
You are thinking the jQuery way. You have to put that away and think data-binding and angularjs.
To do what you are asking is pretty easy if you think the angularjs way.
First of all, you need the php page of yours to print out a html page with a {{updateMe}}
then in your code
.success(function(data){
$scope.updateMe = data
......

Using one delete function for a post jquery request of php request

I'm looking to find out how I can accomplish this next task. I have a controller that loads a view with a table that lists pages in my database. In every row that is made in the table there is a spot for a icon that when clicked will do one of two things.
If the user does not have javascript enabled:
Clicking on the icon will redirect to the delete function in the controller with id of the page as a paramter
Delete controller function will run delete function in model sending page id to delete model function
Delete function in model will delete the page from the database and when returned back to page controller delete function it will redirect back to index function to show list of pages table again.
After redirect it will display a title and message as to a success/fail.
If the user does have javascript enabled:
Send a post to the delete function in controller with jquery post
method with the data page id
Delete controller function will run delete function in model sending page id to delete model function
Delete function in model will delete the page from the database and when returned back to page controller delete function it create a message array for the json object to return to the success function of the post request.
A message with my pnotify plugin will create a message that is formed from that json object and display it to the user
What I would like to know is with doing this how to properly accommodate for these two scenarios? I have started attempting this but would like to some clarification if I have made a mistake so far.
<?php
// Controller delete function
public function delete($content_page_id)
{
if (isset($content_page_id) && is_numeric($content_page_id))
{
$content_page_data = $this->content_page->get($content_page_id);
if (!empty($content_page_data))
{
//update is ran instead of delete to accompodate
//for the soft delete functionality
$this->content_page->update('status_id', 3);
if ($this->input->is_ajax_request())
{
//return json data array
}
}
}
}
?>
Global JS file to be used for multiple tables with delete buttons
/* Delete Item */
$('.delete').click(function(event) {
event.preventDefault();
var item_id = $(this).attr('rel');
$.post(<?php echo current_url(); ?>'delete', { item_id : item_id }, function(data)
{
if (data.success)
{
var anSelected = fnGetSelected( oTable );
oTable.fnDeleteRow( anSelected[0] );
}
}, 'json');
});
I think that you should have two functions in PHP:
public function delete($content_page_id) {
// Your delete code
return "a string without format";
}
public function deleteAjax($content_page_id) {
return json_encode($this->delete($content_page_id));
}
So, when the user has JS enabled, you call deleteAjax passing a parameter in your $.post function to let PHP know that JS is enabled:
$.post(<?php echo current_url(); ?>'delete', { item_id : item_id, js: 1 }, function(data)
{
if (data.success)
{
var anSelected = fnGetSelected( oTable );
oTable.fnDeleteRow( anSelected[0] );
}
}, 'json');
And if JS is disabled, call the other function. You should use an AJAX specialized controller instead a function in the same class.
1) As far as "displaying a message" - the view-itself could be ready for a 'message' if one exists. Bringing us back to...
2) Can you have your delete function return the message you want displayed? Your AJAX approach will ignore this message while your View will display it...
3) I agree that your 'Controller delete function' should 'finish' with different outcomes based on whether the request is AJAX or not. I like what #Skaparate (answered Aug 30 at 18:37) was doing with adding: js:1 In your delete function, you could use this in a simple conditional:
if js = 1
header('HTTP/1.1 200');
else
call view and include/pass-in the 'message'

CodeIgniter Initial Page Load Variable?

I'm looking for a solution to loading the header/footer/navigation only on the initial page view.
The reasoning behind this is that my navigation panel uses Ajax to render the content of the destination link in the main content div instead of actually loading the page itself.
However, I need to be able to say something along the lines of if its the initial view, load the header, navigation, then the actual page, then the footer. But if its not the initial view and the page is loaded in the content div area so for example a navigation link or a form submit, it doesn't load the header, navigation and footer but only the actual page.
So for example I have these 4 views:
header_view
navigation_view
page_a_view
footer_view
And this controller:
controller_a
The navigation has a link which is 'Page A' and points to http://myurl.com/controller_a. If that link is clicked I only wanted controller_a to load the page_a_view view, because the navigation link will load the data of that page into the div.
However if I directly go to http://myurl.com/controller_a, it needs to render the the header/navigation/footer also.
The solution I thought I was on the right lines with was something like a base controller with a function load_page() which would be something like:
function load_page($page, $data) {
if($this->uri->segment($this->uri->total_segments()) == "initial_page_load") {
$this->load->view('header_view');
$this->load->view('navigation_view');
$this->load->view($page, $data);
$this->load->view('footer_view');
} else {
$this->load->view($page, $data);
}
}
So if I was to go to http://myurl.com/controller_a/initial_page_load it would load the header/navigation/footer but if I went to http://myurl.com/controller_a it wouldn't.
However this doesn't cover all possibilities.
Another way I thought of is checking if there is a referring URL, if there is, don't load the header/navigation/footer. But again, this doesn't cover things such as what if the link was referred by an external website?
Does anyone have any suggestions to how I can achieve what I need?
Let this be your view page for all views. For your other pages, you are going to change the content on div, 'page_content' dynamically via ajax.
**application/views/your_template_view.php**
<?php
$this->load->view('header_view');
$this->load->view('navigation_view');
?>
<a href="javascript:void(0)" id='home' class='my_links'>Home</a>
<a href="javascript:void(0)" id='about_us' class='my_links'>About us</a>
<!--
Make sure the id of the page is same as
the file name of view page for respective pages
-->
<div id='page_content'><?php echo $page_content; ?></div>
<?php
$this->load->view('footer_view');
?>
<script lang='javascript'>
$('.my_links').click(function(){
$.post(
'<?php echo site_url('test_controller/get_page_content') ?>',
{'page_content':$(this).attr('id')},
function(response){
if(response != '')
$('#page_content').text(response);
},'json'
);
});
</script>
Let this be your controller :
**application/controller/test_controller.php**
function your_page($param1 = '', $param2 ='') {
/*this one is for your initial page*/
if($param1)
// send mail
if($param2)
// send mail
$data['page_content'] = $this->load->view('initial_page_load');
$this->load->view('your_template_view', $data);
}
function get_page_content()
{
/*this one is for other pages, this provides page content
for the request made from ajax*/
$page_title = $this->input->post('page_title');
$page_content = $this->load->view($page_title);
echo json_encode($page_content);
}
Make a session variable to denote whether the header/footer is loaded, and if it is, just skip them
if (!$this->session->userdata('nav_loaded')) {
$this->load->view('header_view');
}
etc...
This will work for all your pages, no matter where are they called from, provided that all the post-initial calls are done by AJAX.
EDIT
If you want to mix ajax and non-ajax calls after that, the session varable won't work, of course. Perhaps you could put an ajax parameter in your urls and adjust the controllers according to that.
public function index($ajax = false) {
...
if (!ajax) {
$this->load->view('header_view');
}
etc...
}
So, all the AJAX call will have that additional parameter in the url set to true (almost anything except zero: index/1, index/ajax, etc.).
Although I'm still testing this it seems to be doing exactly what I expect so far! It's one of those ones which is simple but does the complete job so hopefully no problems pop up...
In MY_Controller.php
function load_page($page, $data) {
if(!$this->input->is_ajax_request()) {
$this->load->view('header_view');
$this->load->view('navigation_view');
}
$this->load->view($page, $data);
if(!$this->input->is_ajax_request()) {
$this->load->view('footer_view');
}
}
Managed to stumble across that function when looking in the Input class documentation

Categories