Load div content on same page using AJAX in Codeigniter - php

i am newbie on codeigniter but trying to develop simple CMS on it.
my question is i have a side column in my main CMS view which have several links to other views,what i want to do is to load all the links in main CMS view in center div instead of going to another page every time. I know i can achieve this task through ajax but dont know how to do it on CODEIGNITER.
Here is how i want to acheieve it to my knowledge.
<script type="text/javascript">
function onLinkClick(value){
jQuery('#mang_server').load(value,
function(){alert('Content Successfully Loaded.')}
);
}
</script>
<body>
<div id="main">
<div id="header"> <img src="../img/logo.gif" width="101" height="29" alt="" />
<div id="middle">
<div id="left-column">
<h3>Header</h3>
<ul class="nav">
<?php foreach($ops as $operations)
{$op_name = $operations['admin_op'];
$op_link = $operations['link_to'];
?>
<li><?php echo $op_name ;?></li>
<?php } ?>
</ul>

Take a look on this simple example for ajax in codeigniter:
$.ajax({
url: '<?php echo base_url() ?>/controller_namer/method_name',
type: 'POST',
data: {view_param: "sidebar_html"},
success: function(response){
$('#div_id').html(response);
}
});
Now go to controllers/controller_name.php and create a method method_name;
function method_name() {
// Get Post Data
$View_Name = $this->input->post("view_param");
$this->load->view($View_Name);
// Alternate is create your html here
// ......
}
hope this will help you.

#jogesh_pi
View Portion:
<script>
function onLinkClick(value){
/*Query('#mang_server').load(value,
function(){alert('Content Successfully Loaded.')}
);*/
$.ajax({
url: '<?php echo base_url() ?>/admin/load_view/',
type: 'POST',
data: {view_param: "value"},
success: function(response){
//$('#mang_server').html(response);
alert("response recieved");
}
enter code here
});
}
</script>
<li><?php echo $op_name ;?></li>
Controller Portion : admin
public function load_view($view_name){
$data['view_link'] = $this->admin_model->load_view_model($view_name);
$this->load->view($data);
}
Model portion : load_view_model
public function load_view_model($view_name){
$this->db->where('admin_op',$view_name);
$query = $this->db->get('admin_operations');
if($query->num_rows()>0){
foreach($query->results() as $rows ){
$data['link'] = $rows->link_to;
}
return $data->result_arrays();
}
}

Related

how to built ajax tabs in wordpress?

I try to display the departments in my website as tabs, when click one tab it will display the data related to this department according to department_id.
I try this code Execute php function only when clicked (wordpress) but I need the tabs number to be dynamic.
<div class="tabs">
<ul>
<?php
$arr1=array(2,3,5,10,22,25,27,28,29,30);
$arr2=array("dep1","dep2","dep3","dep4",
"dep5","dep6","dep7","dep8","dep9","dep10");
for($i=0;$i<10;$i++){?>
<li><a href="#tab" id="<?php echo $arr1[$i]; ?>"><?php echo
$arr2[$i];?>
</a></li>
<?php } ?>
</ul>
</div>
<div id="tab" class="section">
</div>
functions.php:
<?php
add_action('wp_ajax_tabsfunction', 'tabsfunction');
add_action('wp_ajax_nopriv_tabsfunction', 'tabsfunction');
function tabsfunction() {
$dept_id=$_GET[id];
/** Here I print data according to $dept_id **/
die();
}
?>
script.js:
jQuery(document).ready(function() {
jQuery('.tabs a').click(function(e) {
e.preventDefault();
var tab_id = jQuery(this).attr('id');
console.log(tab_id);
jQuery.ajax({
type: "GET",
url: "wp-admin/admin-ajax.php",
dataType: 'html',
data: ({ action: 'tabsfunction', id: tab_id}),
success: function(data){
jQuery('#tab').html(data);
},
error: function(data)
{
alert("Error!");
return false;
} });}); });
it dose not work, it displays data only for one tab.
console.log(tab_id) ----> it display the id for the first tab clicked
and did not change when click another tab.
You need to echo the output from the tabsfunction and also add the die() at end of the function like below :
add_action('wp_ajax_tabsfunction', 'tabsfunction');
add_action('wp_ajax_nopriv_tabsfunction', 'tabsfunction');
function tabsfunction() {
$dept_id=$_GET[id];
/** Here display data according to $dept_id **/
echo 'output';
die();
}
Hope it helps.
can you please correct your tab list code.
<div class="tabs">
<ul>
<?php
$arr1 = array(2,3,5,10,22,25,27,28,29,30);
$arr2 = array("dep1","dep2","dep3","dep4","dep5","dep6","dep7","dep8","dep9","dep10");
for($i=0;$i<10;$i++)
{
?>
<li><?php echo $arr2[$i];?></li>
<?php
}
?>
</ul>
</div>
<?php for($i=0;$i<10;$i++)
{
?>
<div id="tab<?php echo $arr1[$i]; ?>" class="section">
</div>
<?php
}
?>
Also return proper response on ajax request.
<?php
add_action('wp_ajax_tabsfunction', 'tabsfunction');
add_action('wp_ajax_nopriv_tabsfunction', 'tabsfunction');
function tabsfunction() {
$dept_id = $_GET[id];
echo $dept_id; // this just dispay requsted id as tab content here you can add your logic for dynamic content based on id
die();
}
?>
And your script js look like this
jQuery(document).ready(function() {
jQuery('.tabs a').click(function(e) {
e.preventDefault();
var tab_id = jQuery(this).attr('id');
console.log(tab_id);
jQuery.ajax({
type: "GET",
url: "wp-admin/admin-ajax.php",
dataType: 'html',
data: ({ action: 'tabsfunction', id: tab_id}),
success: function(data){
jQuery('#tab'+tab_id).html(data);
},
error: function(data)
{
alert("Error!");
return false;
} });}); });

displaying codeigniter database error using ajax

I get error 500 internal server error
I want to display database error to view, so far i can produce the response only in chrome network response
Model classes, I omit the constructor
class Size_mdl extends MY_Model {
public function create($data) {
return $this->insert($data);
}
}
class MY_Model extends CI_Model {
public function insert($data) {
$success = $this->db->insert($this->table_name, $data);
if ($success) {
return true;
} else {
$msg = $this->db->error();
return $msg;
}
}
controller
$data['test_r'] = var_dump($this->Size_mdl->create($data));
$this->load->view('size/create_size_view',$data);
View
This is Welcome.php, the most outer with header and footer
<div class="page">
<!-- Page Header-->
<header class="page-head"></header>
<!-- Page Content-->
<main id="main_content" class="page-content"></main>
<!-- Page Footer-->
<footer class="page-foot section-60 section-xl-150 text-center text-lg-left">
Inside that page i have create_size_view loaded to main_content, previously it was homepage, bunch of stuff.
<head>
<style>
</style>
</head>
<body>
<div id="container">
<div id="content">
<h5>Create New Size</h5>
<div id="inner_container">
<div id="create_part">
<?php
if (isset($test_r)){
echo $test_r;
}?>
<?php echo validation_errors(); ?>
<?php
$attributes = array('id' => 'create_size_form');
echo form_open("size/create", $attributes);
?>
<p>
<?php echo lang('size_short_name_label', 'short_name'); ?>
<?php
$short_name = array(
'name' => 'short_name',
'id' => 'short_name',
'maxlength' => '100'
);
echo form_input($short_name);?>
</p>
<p>
<?php echo lang('size_long_name_label', 'long_name'); ?>
<?php
$long_name = array(
'name' => 'long_name',
'id' => 'long_name',
'maxlength' => '100',
);
echo form_input($long_name);?>
</p>
<p>
<?php echo form_submit('submit', lang('create_size_submit_btn')); ?>
</p>
<?php echo form_close(); ?>
</div>
</div>
</div>
</div>
<script>
$('form#create_size_form').submit(function (e) {
var form = $(this);
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url('size/create'); ?>",
data: form.serialize(), // <--- THIS IS THE CHANGE
dataType: "html",
success: function (result) {
$('#main_content').html(result);
},
});
});
</script>
</body>
Now i need the response for failed insert appear replacing main_content welcome.php or its children div from create_size_view.php. I can produce the successful insert by reloading create_size_view.php
In Codeigniter predefined error handler for MySQL.
if error encountered Codeigniter throw HTML content with 500 server site error
for avoiding this page 500 status code put Codeigniter ENVIRONMENT in production then your code will work properly.
change ajax url property. use url like "/size/create" dont use whith domain like "www.site.com/size/create";
use text for binding data
$.ajax({
type: "POST",
url: "<?php echo site_url('size/create'); ?>",
data: form.serialize(), // <--- THIS IS THE CHANGE
dataType: "html",
success: function (result) {
$('#main_content').text(result);
}
});

refresh an included page

I have a page index.php
Inside of it is a friendlist that updates the db with a button click without refreshing the page. Now I want that only the friendlist refreshs so its updated
<html>
<body>
<?php
include ("friendlist.php");
?>
</body>
</html>
friendlist.php:
<script>
function adduser() {
var data=$("#adduserform").serialize();
$.ajax({
type: "POST",
url: "addfriend.php",
data: data,
dataType: "html",
success: function(data)
{
//refresh myFriendlist or requser so its updated
}
});
}
</script>
<div id="myFriendlist" class="friendlist-content">
<?php if(!empty($request)) { ?>
<div id="req">
<h2 id="reqh">Anfragen</h2>
<?php foreach($request as $row) {
$row['userAname'] = (strlen($row['userAname']) > 5) ? substr($row['userAname'], 0, 5) . '...' : $row['userAname'];
?>
<div id="requser">
<a class="reqimg" style="padding:0px;" href="user.php?id=<?php echo ($row['id']);?>">
<img class="reqpb" src="./users/<?php echo ($row['userAid']); ?>/pb.jpg" alt="Bild nicht gefunden" onerror="this.src='./img/no_pb.png';"></img>
</a>
<a class="reqnm" style="padding:0px;" href="user.php?id=<?php echo ($row['userAid']);?>"><?php echo $row['userAname']; ?></a>
<img id="aimg" src="./img/accepticon.png">
<form id="adduserform" name="adduserform">
<input type="hidden" id="reqid" name="reqid" value="<?php echo $row['userAid'];?>" />
<input type="hidden" id="reqnm" name="reqnm" value="<?php echo $row['userAname'];?>" />
</form>
<img id="aimg" src="./img/dntaccepticon.png">
</div>
<?php
}
?>
</div>
<?php
}
?>
</div>
How can I do that?
You can refresh an external file using ajax. For example, if you had a div with the id "friendslist" you could refresh its contents this way:
$.ajax({
url: "friendlist.php"
}).done(function(response) {
$( '#friendslist' ).html( response );
});
The documentation for ajax is on the jQuery site here: http://api.jquery.com/jquery.ajax/.
If you can make "addfriend.php" to return the new complete list of users, so that would be:
<?php foreach($request as $row) {
$row['userAname'] = (strlen($row['userAname']) > 5) ? substr($row['userAname'], 0, 5) . '...' : $row['userAname'];
?>
you could use that response, which you will receive when you do the AJAX call, to refresh the friendlist, using the jquery HTML function (http://api.jquery.com/html/)
you can follow this code but not tested
first update your index.php
<html>
<body>
<div id="friendlist">
<?php
include ("friendlist.php");
?>
</div>
</body>
</html>
then update your addfriend.php as like
<?php
// your code here
// then include your frindlist.php content
include 'yourpath/frindlist.php'
?>
then update your javascript code like this
function adduser() {
var data=$("#adduserform").serialize();
$.ajax({
type: "POST",
url: "addfriend.php",
data: data,
dataType: "html",
success: function(data)
{
$('#friendlist').html(data);
}
});
}

Jquery reload div content on select change using php ajax

OK here is my code
portfolio.php
<select name="portfolio" id="portfolio_dropdown" class="service-dropdown">
<?php foreach($years as $year){ ?>
<option value="<?php echo $year['year']; ?>"><?php echo $year['year']; ?></option>
<?php } ?>
</select>
<div class="loading"></div>
<div id="portfolio">
<div id="port-cont">
<?php foreach($portfolios as $portfolio){ ?>
<div class="video">
<div class="play">
Play
</div>
<iframe src="http://www.youtube.com/v/<?php echo $portfolio['url']; ?>"frameborder="0" allowfullscreen></iframe>
<h3><?php echo $portfolio['title']; ?></h3>
<p><?php echo $portfolio['text']; ?></p>
</div>
<?php } ?>
</div>
</div>
my js code
$("body").on('change','#portfolio_dropdown',function(){
var year = $(this).val();
$.ajax({
type: "POST",
url: "catalog/controller/portfolio.php",
data: "year="+year,
beforeSend: function(){
$(".loading").show();
$("#portfolio").empty();
},
success: function(portfolio_data){
$(".loading").hide();
$("#portfolio").html(portfolio_data);
}
});
});
my portfolio controller file
if(isset($_POST['year'])){
include_once "../../system/validation.php";
include_once "../model/DataBase.php";
include_once "../model/Display.php";
$year = integer($_POST['year']);
$get_portfolio_data = new Display("portfolio");
$portfolios = $get_portfolio_data->getDataByColumnName("year",$year);
include_once "../view/themes/default/template/portfolio_data.php";
exit();
}
My portfolio file "the first one " i get my data with another function that i get my last year(2014) portfolio data
so when i change the year i call my controller file to get the data related to that year
my question here is how to return $portfolios that i got from my controller file so i don't have to change my template file code or include another file as i did
i mean i need to reload my portfolio.php template content
i tried something like this
$("body").on('change','#portfolio_dropdown',function(){
var year = $(this).val();
$.ajax({
type: "POST",
url: "catalog/controller/portfolio.php",
data: "year="+year,
beforeSend: function(){
$(".loading").show();
$("#portfolio").hide();
},
success: function(portfolio_data){
$(".loading").hide();
$("#portfolio").show().load("portfolio" + " #port-cont");
}
});
});
but i don't know how to send my new $portfolios data to the same div without including another template file
Actually i'm little confused how to do this properly
So i hope you got what i want to do :)
You can create a separate portfolio-div.php file that only contains the code you want to replace with, and call that from the $.ajax call.
Or you can add a $_GET parameter like ?skiptemplate=1 to portfolio.php so that when you call the file with that parameter, the surrounding template markup is skipped when the file is called from an ajax call.
If you do not have the opportunity to change the server-side code, you can load the whole template file again, but extract only the #port-cont part to replace the existing content. Don't use load() (which itself will call an URL), use html() instead:
$("#portfolio").show().html(portfolio_data);
(though this will insert all HTML, not only the #port-cont part)
$("#portfolio").html(portfolio_data)
Just pass the parameter into html

How to integrate AJAX to avoid page redirection of PHP CMS

I have used a CMS built with PHP and MySQL. It works great and I have fully customized it to my liking. The only thing now to do is make a more efficient way of loading the data. When a user wants to select an article I want the browser to stay on the same exact page/url without reloading or redirecting. Here is a demo of the CMS: DEMO LINK
For example, the above line of code was exerted from the homepage.php script. It is an anchor tag for the user to select to view the whole content of a particular article, which was only partially displayed in the homepage. When this link is clicked, the user is directed away from the homepage and taken to the article's specific URL. How can I get the full article content page to load inside of the homepage and hide the original homepage content to avoid the page redirect problem. Is this something that can be done with this particular CMS? I can provide any PHP script from the CMS if needed. Thanks in advance.
ARCHIVE.php SCRIPT:
<?php foreach ( $results['articles'] as $article ) { ?>
<li>
<h2>
<span class="pubDate"><?php echo date('j F Y', $article->publicationDate)?></span><br><?php echo htmlspecialchars( $article->title )?>
</h2>
<p class="summary">
<?php if ( $imagePath = $article->getImagePath( IMG_TYPE_THUMB ) ) { ?>
<a href=".?action=viewArticle&articleId=<?php echo $article->id?>">
<div class="floated_child0" style="background-repeat:none; background-image:url('<?php echo $imagePath?>');"></div></a>
<?php } ?>
<?php echo htmlspecialchars( $article->summary )?> (more)
</p>
</li>
<?php } ?>
If you can get the content of the article using ajax and put that content below that title of that article, for ex let say you have a php function in backend which you can call to get the content of article given the article id then you can make a GET ajax request to get the article content and put in the desired div. something like:
<script language="javascript">
$("#view_more").click(function(){
var dataString = "id="+article_ID;
$.ajax({
type: "GET",
url: 'http://myhost.com/articles/getArticleContent',
data: dataString,
success: function(response) {
$('div #description').html(response);
}
});
return false;
});
</script>
update:27-11-2012
you can try something like this, if that helps you understanding better. it may not be exactly what you want but I hope it will help you understanding how you can proceed.
<?php foreach ( $results['articles'] as $article ) { ?>
<li>
<h2>
<span class="pubDate"><?php echo date('j F Y', $article->publicationDate)?></span><br><?php echo htmlspecialchars( $article->title )?>
</h2>
<p class="summary" id="<?php echo $article->id?>">
<?php if ( $imagePath = $article->getImagePath( IMG_TYPE_THUMB ) ) { ?>
<a href=".?action=viewArticle&articleId=<?php echo $article->id?>">
<div class="floated_child0" style="background-repeat:none; background-image:url('<?php echo $imagePath?>');"></div></a>
<?php } ?>
<?php echo htmlspecialchars( $article->summary )?> (more)
</p>
</li>
<?php } ?>
<script language="javascript">
function viewFullArticle(article_ID){
var dataString = "id="+article_ID;
$.ajax({
type: "GET",
url: 'http://myhost.com/articles/getArticleContent',
data: dataString,
success: function(response) {
$('p #'+article_ID).html(response); //assuming response is everything you want to display within summary paragraph
}
});
return false;
};
</script>

Categories