bootstrap tree view plugin convert in codigniter? - php

I want to convert Bootstrap Treeview plugin into CodeIgniter, it runs normally on core PHP but when I convert it into CodeIgniter, it shows only array result.
Result: My code output
Source: Bootstrap Treeview source I want to convert it into CodeIgniter
fetch.php - controller
<?php
class Fetch extends MY_Controller {
public function index() {
$this->load->view('dashboard');
// $query (= " SELECT * FROM country_state_city ";
$query = $this->db->query("SELECT * FROM country_state_city ");
// (" SELECT * FROM country_state_city ")->result_array() ;
//$output = array();
foreach ($query->result_array() as $row) {
$sub_data["id"] = $row["id"];
$sub_data["name"] = $row["name"];
$sub_data["text"] = $row["name"];
$sub_data["parent_id"] = $row["parent_id"];
$data[] = $sub_data;
}
foreach ($data as $key => &$value) {
$output[$value["id"]] = &$value;
}
foreach ($data as $key => &$value) {
if ($value["parent_id"] && isset($output[$value["parent_id"]])) {
$output[$value["parent_id"]]["nodes"][] = &$value;
}
}
foreach ($data as $key => &$value) {
if ($value["parent_id"] && isset($output[$value["parent_id"]])) {
unset($data[$key]);
}
}
echo json_encode($data);
}
}
?>
dashboard.php - view
<!DOCTYPE html>
<html>
<head>
<title>ajax jaquey tree grid</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
<script type="text/javascript" charset="utf8"
src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.js"></script>
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.css"/>
<style>
</style>
</head>
<body>
<br/><br/>
<div class="container" style="width:500px;">
<h2 align="center">Make Treeview using Bootstrap Treeview Ajax JQuery with PHP</h2>
<br/><br/>
<div id="treeview"></div>
</div>
</body>
</html>
<script>
$(document).ready(function () {
$.ajax({
url: "<?php echo base_url();?>fetch",
method: "POST",
dataType: "json",
success: function (data) {
$('#treeview').treeview({data: data});
}
});
});
</script>

If you want to load data using ajax request then no need to load it in index() function.
You have to load the only view in an index() and make another function for tree view like this:
You load all data on page load then also make ajax call which is not correct.
Controller:
<?php
class Test_c extends CI_Controller {
public function index() {
$this->load->view('test');
}
function tree() {
// $query (= " SELECT * FROM country_state_city ";
$query = $this->db->query("SELECT * FROM country_state_city ");
// (" SELECT * FROM country_state_city ")->result_array() ;
//$output = array();
foreach ($query->result_array() as $row) {
$sub_data["id"] = $row["id"];
$sub_data["name"] = $row["name"];
$sub_data["text"] = $row["name"];
$sub_data["parent_id"] = $row["parent_id"];
$data[] = $sub_data;
}
foreach ($data as $key => &$value) {
$output[$value["id"]] = &$value;
}
foreach ($data as $key => &$value) {
if ($value["parent_id"] && isset($output[$value["parent_id"]])) {
$output[$value["parent_id"]]["nodes"][] = &$value;
}
}
foreach ($data as $key => &$value) {
if ($value["parent_id"] && isset($output[$value["parent_id"]])) {
unset($data[$key]);
}
}
echo json_encode($data);
}
}
?>
Try like this. It works.
Rest of things is correct.
Hope you solve your error using my solution.
Greetings....

Related

Autocomplete does't work properly in ci

controller: welcome.php
public function lookup()
{
$keyword = trim($_GET['term']);
$data['response'] = 'false';
$query = $this->Main_tutorial->lookup($keyword);
print_r($query);
if( ! empty($query) )
{
$data['response'] = 'true';
$data['message'] = array();
$data['auto_com'] = array();
foreach( $query as $row )
{
$data['message'][] = array('tutorial_name' => $row['tutorial_name']);
$data['auto_com'][] = $row['tutorial_name'];
}
}
if('IS_AJAX')
{
echo json_encode($data['auto_com']);
}
else
{
$this->load->view('index',$data);
}
}
view: index.php
<html>
<head>
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>resource/css/jquery-ui.css">
<link rel="stylesheet" href="http://static.jquery.com/ui/css/demo-docs-theme/ui.theme.css" type="text/css" media="all" />
</head>
<body>
<input type="text" class="search-bg__text" name="tutorial_name" id="tutorial_name">
<script src="<?php echo base_url(); ?>resource/js/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#tutorial_name").autocomplete({
source:"<?php echo base_url(); ?>welcome/lookup",
minLength:1,
select:function(b,c)
{
var a=c.item.value;
a=encodeURIComponent(a);
location.href=a+"-tutorial";
return false
}
});
});
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js" type="text/javascript"></script>
</body>
</html>
model: Main_tutorial.php
public function lookup($keyword)
{
$this->db->select('tutorial_name')->from('tutorial');
$this->db->like('tutorial_name',$keyword,'after');
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
In this code I want to create an autocomplete suggestion box using codeigniter. Now what happen when I write something inside the tutorial_name input field and inspect the element then select network and click on link it show me the output but can't see on display I don't know why ?. So how can I fix this issue ?Please help me.
Thank You
In autocomplete() you need output as json format. Here you are printing json data with echo json_encode($data['auto_com']); But before it you are also displaying data print_r($query);. Which create invalid json output. so you have to remove it. Also note that your if('IS_AJAX') will always become true
public function lookup()
{
$keyword = trim($_GET['term']);
$data['response'] = 'false';
$query = $this->Main_tutorial->lookup($keyword);
if( ! empty($query) )
{
$data['response'] = 'true';
$data['message'] = array();
$data['auto_com'] = array();
foreach( $query as $row )
{
$data['message'][] = array('tutorial_name' => $row['tutorial_name']);
$data['auto_com'][] = $row['tutorial_name'];
}
}
if('IS_AJAX') //This condition always become true
{
echo json_encode($data['auto_com']);
}
else
{
$this->load->view('index',$data);
}
}

My script is not working for bootstrap treeview

I'm trying to connect the bootstrap treeview but the json script is not working. here is the fetch.php source code: `
$sub_data["id"] = $row["id"];
$sub_data["invited"] = $row["invited"];
$sub_data["text"] = $row["invited"];
$sub_data["caller_id"] = $row["caller_id"];
$data[] = $sub_data;
foreach ($data as $key => &$value)
{
$output[$value["id"]] = &$value;
}
foreach ($data as $key => &$value)
{
if ($value["caller_id"] && isset($output[$value["caller_id"]]))
{
$output[$value["caller_id"]]["nodes"][] = &$value;
}
}
foreach ($data as $key => &$value)
{
if ($value["caller_id"] && isset($output[$value["caller_id"]]))
{
unset($data[$key]);
}
}
echo json_encode($data);`
and this is the treeshow.php script code:
$(document).ready(function(){
$.ajax({
url: "fetch.php",
method:"POST",
dataType: "json",
success: function(data)
{
$('#treeview').treeview({data: data});
}
});
});
and mysql db fields: id, invited, caller_id what is wrong with this codes?

Post JSON object to php using Ajax

I am dynamically adding table rows by selecting options from dropdown and then I am trying to send html table rows to php function using ajax as array in json format. However php function does not print all rows in the console log, when I am submitting more than one row. I got the desired output like once or twice. I think I am missing something in the php function. Please check once. If anymore information about the code is required, let me know, I will update.
Javascript:
function storeClgValues() {
var CollegeData= new Array();
$('#collegetable tr').each(function(row, tr){
CollegeData[row]={
"college" : $(tr).find('td:eq(0)').text()
}
});
CollegeData.shift();
return CollegeData;
}
$('#submit').click(function() {
CollegeData=storeClgValues();
CollegeData=$.toJSON(CollegeData);
$.ajax({
type:"POST",
url: '<?php echo base_url();?>ajaxController/insertcollege',
data: "CollegeData=" + CollegeData,
success: function(msg) {
console.log(CollegeData);
console.log(msg);
}
});
});
PHP function in AjaxController class:
public function insertcollege()
{
$data=array();
$data=stripcslashes($_POST['CollegeData']);
$data=json_decode($data, TRUE);
//echo $data[0]['college'].'<br>';
//echo $data[1]['college'].'<br>';
if (is_array($data) || is_object($data))
{
foreach ($data as $key => $item) {
echo $item['college'].'<br>';
}
}
}
Output in console in three tries:
[{"college":"College of Agriculture"}]
College of Agriculture
[{"college":"College of Agriculture"},{"college":"College of Business"}]
College of Agriculture
College of Business
[{"college":"College of Agriculture"},{"college":"College of Business"}, {"college":"College of Comm & Educati"}]
<!--nothing gets printed-->
Try like this...
<?php
$json = '[{"college":"College of Agriculture"},{"college":"College of Business"}, {"college":"College of Comm & Educati"}]';
$data = json_decode($json,TRUE);
//print_r($data);
if (is_array($data) || is_object($data))
{
foreach ($data as $key => $item) {
$output[]=$item['college'].'<br>';
}
}
echo json_encode($output);
?>
OR
<?php
$json = '[{"college":"College of Agriculture"},{"college":"College of Business"}, {"college":"College of Comm & Educati"}]';
$data = json_decode($json,TRUE);
//print_r($data);
if (is_array($data) || is_object($data))
{
foreach ($data as $key => $item) {
foreach($item as $value){
$output[] = $value."</br>";
}
}
}
echo json_encode($output);
?>

PHP/Codeigniter elseif not processing

I can't seem to get the elseif to process in the below php code. My database setup is noted below:
<?php // the following php is the bootstrapper for the friendship connector
$selectedId = $_REQUEST['id'];
$myuserid = $this->session->userdata('userid');
$friendshipQuery = $this->db->query("SELECT * FROM friends");
$row = $friendshipQuery->row();
foreach ($friendshipQuery->result() as $row) {
if ($myuserid == $selectedId) { ?>
<script type="text/javascript">
$(document).ready(function() {
$("#addFriend").hide();
});
</script>
<?php } elseif ($row->relationType == 'requested') { ?>
<script type="text/javascript">
$(document).ready(function() {
alert("hello");
$("#addFriend").replaceWith(<input type="submit" value="Accept Friend" style="width: 95px; height: 28px" class="button1" />);
});
</script>
<?php } } ?>
Your problem is right here:
$friendshipQuery = $this->db->query("SELECT * FROM friends");
$row = $friendshipQuery->row();
foreach ($friendshipQuery->result() as $row) {
Your assigning the query as a ->row() element. Take that line out and on the foreach just add this:
foreach($friendshipQuery->result() as $row)
That should solve it.
Have you checked the generated html? If it doesn't contain that part, it means that $myuserid == $selectedId is always true.

CKEditor with json not passing content

I am trying to submit a form without leaving the page using json.
However, the method below ignores the data I have entered into the CKEditor.
Any ideas (and feel free to correct my terminology)?
<script type="text/javascript">
$(document).ready( function() {
$("#addStory input[type=submit]").click(function(e) {
e.preventDefault();
$.post('_posteddata.php', $("#addStory").serialize(), function(result) {
alert(result.adminList);
}, "json");
});
});
</script>
<form name="addStory" action="" method="post" id="addStory">
<label for="story_story">Story: </label><textarea id="story_story" name="story_story"><p></p></textarea>
<?php
// Include the CKEditor class.
include("ckeditor/ckeditor.php");
// Create a class instance.
$CKEditor = new CKEditor();
$CKEditor->basePath = '/ckeditor/'
$CKEditor->replace("story_story");
?>
<input type="submit" value="Submit" />
</form>
_posteddata.php:
include 'connection.php';
function check_input($value, $quoteIt)
{
// Stripslashes
if (get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
// Quote if not a number
if (is_null($value) || $value=="") {
$value = 'NULL';
} else if (!is_numeric($value) && $quoteIt == 1) {
$value = "'" . mysql_real_escape_string($value) . "'";
}
return $value;
}
// CKEDITOR STUFF FOR STORY_STORY
if (isset($_POST)) {
$postArray = &$_POST;
}
foreach ( $postArray as $sForm => $value )
{
if($sForm == "story_story") {
$story_story = check_input($value, 1);
}
}
$query = "INSERT INTO story_table (story) VALUES ($story_story)";
mysql_query($query) or die(mysql_error() . $query);
$return = array();
$return['adminList'] = "New story added with ID: " . mysql_insert_id();
header('application/json');
echo json_encode($return);
mysql_close();
In this kind of situation you must force CKEditor to update the contents of the textarea
So your function would be something like this:
$(document).ready( function() {
$("#addStory input[type=submit]").click(function(e) {
e.preventDefault();
CKEDITOR.instances.story_story.updateElement(); // Update the textarea
$.post('_posteddata.php', $("#addStory").serialize(), function(result) {
alert(result.adminList);
}, "json");
});
});

Categories