Generate Web Page Using PHP Class - php

I am a university student experimenting with OOP and PHP. I was wanting to build up a page using a BuildPage class.
<?php
Class BuildPage {
private $title;
private $style;
private $head;
private $header;
private $page;
private $footer;
private $finalPage;
public function __construct($title, $style)
{
$this->title = $title;
$this->style = $style;
}
public function addHead()
{
$this->head = "
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>$this->title</title>
<link href='$this->style' rel='stylesheet' type='text/css'>
<link rel='stylesheet' href='style.css'>
</head>";
}
public function addToPage($partOfPage)
{
if(empty($this->page) || !isset($this->page))
{
$this->page = $partOfPage;
}
else {
$this->page .= "<br> " . $partOfPage;
}
}
public function addHeader($header)
{
$this->header = "<body><div class='container'><header> " . $header . "
</header>";
}
public function addFooter($footer)
{
$this->footer .= "<BR><footer> " . $footer . " </footer></div></body>
</html>";
}
public function getPage()
{
$this->finalPage = $this->head . $this->header . $this->page .
$this->footer;
return $this->finalPage;
}
}
?>
However, when I try to build the page using the functions, I cannot understand how to use PHP within the argument as below:
$buildPage->addToPage("
<!-- Here is our page's main content -->
<!-- Use function to display songs -->
<?php $music->displaySongs('xmlfiles/songs.xml'); ?>
");
If I escape the $ like \$ to try and make it a string, for some reason the becomes a comment in HTML. Is it possible for this approach to work at all?
Many Thanks
EDIT:
This is the index page below, i call the class at the bottom with an echo.
<?php
require_once('phpclasses/Connect.php');
require_once('phpclasses/BuildPage.php');
require_once('phpclasses/MusicIE.php');
$dbconnect = new Connect();
$music = new MusicIE();
$buildPage = new BuildPage("Music Website", "style.css");
$buildPage->addHead();
$buildPage->addHeader("
<!-- Here is the main header that is used accross all the pages of my
website
-->
<div class='PageHeading'>Available Music Listed Below:</div>
<nav>
<ul>
<li><a href='#'>Home</a></li>
<li><a href='#'>Register</a></li>
<li><a href='#'>Login</a></li>
</ul>
</nav>
<form>
<input type='search' name='q' placeholder='Search query'>
<input type='submit' value='Go!'>
</form>
");
$buildPage->addToPage("
<!-- Here is our page's main content -->
<!-- Use function to display songs -->
" . $music->displaySongs('xmlfiles/songs.xml'));
$buildPage->addFooter("
<!-- And here is my footer that is used across all the pages of our website
-->
<p>©Copyright 2017 by Kris Wilson. All rights reversed.</p>
");
echo $buildPage->getPage();
?>

Since you are passing a string to the function BuildPage::addToPage($partOfPage) you could try to pass the result of $music->displaySongs('xmlfiles/songs.xml') instead of the literal function call as a string. Like so:
$buildPage->addToPage("
<!-- Here is our page's main content -->
<!-- Use function to display songs -->
". $music->displaySongs('xmlfiles/songs.xml'));

Seems that your code is wrong on the addToPage function call. you should call it like this:
$buildPage->addToPage("
<!-- Here is our page's main content -->
<!-- Use function to display songs -->
".$music->displaySongs('xmlfiles/songs.xml'));
You should add the $music->displaySongs('xmlfiles/songs.xml') output to the end of the string.

Related

Error Code 1 when trying to insert video along with its details into mysql database in php

I am trying to make youtube clone website in php. I am stuck at a stage where i want to insert video that i am trying to upload into mysql database but it says error code 1. My project structure is as follows in below image
Screenshot of my website when i upload the entry as below
When click on upload button, i get the error as below image
Here is my upto date code that i have tried.
index.php File:
<?php require_once("includes/header.php"); ?>
<?php require_once("includes/footer.php"); ?>
header.php file:
<?php require_once("includes/config.php"); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>VideoTube</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="assets/css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="assets/js/commonActions.js"></script>
</head>
<body>
<div id="pageContainer">
<!-- Master Head Container -->
<div id="mastHeadContainer">
<!-- Hamburger Menu Button -->
<button class="navShowHide">
<img src="assets/images/icons/menu.png">
</button> <!--End of Hamburger Menu Button -->
<!-- Site Logo -->
<a class="logoContainer" href="index.php">
<img src="assets/images/icons/VideoTubeLogo.png" title="logo" alt="Site logo">
</a> <!-- End of Site Logo -->
<!-- Search Bar -->
<div class="searchBarContainer">
<form action="search.php" method="GET">
<input type="text" class="searchBar" name="term" placeholder="Search...">
<button class="searchButton">
<img src="assets/images/icons/search.png">
</button>
</form>
</div> <!-- End of Search Bar -->
<!-- Right Icons Area -->
<div class="rightIcons">
<a href="upload.php">
<img class="upload" src="assets/images/icons/upload.png">
</a>
<a href="#">
<img class="upload" src="assets/images/profilePictures/default.png">
</a>
</div> <!-- End of Right Icons Area -->
</div> <!-- End of Master Head Container -->
<div id="sideNavContainer" style="display:none;">
</div>
<div id="mainSectionContainer">
<div id="mainContentContainer">
footer.php file:
</div>
</div>
</div>
</body>
</html>
config.php file:
<?php
ob_start(); // turns on output buffering
date_default_timezone_set("Asia/Calcutta");
try {
$con = new PDO("mysql:dbname=VideoTube;host=localhost", "root", "");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
}catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
VideoDetailsFormProvider.php file:
<?php
class VideoDetailsFormProvider {
private $con;
public function __construct($con) {
$this->con = $con;
}
public function createUploadForm() {
$fileInput = $this->createFileInput();
$titleInput = $this->createTitleInput();
$descriptionInput = $this->createDescriptionInput();
$privacyInput = $this->createPrivacyInput();
$categoriesInput = $this->createCategoriesInput();
$uploadButton = $this->createUploadButton();
return "<form action='processing.php' method='POST' enctype='multipart/form-data'>
$fileInput
$titleInput
$descriptionInput
$privacyInput
$categoriesInput
$uploadButton
</form>";
}
private function createFileInput() {
return "<div class='form-group'>
<input type='file' class='form-control-file' id='exampleFormControlFile1' name='fileInput' required>
</div>";
}
private function createTitleInput() {
return "<div class='form-group'>
<input class='form-control' type='text' placeholder='Title' name='titleInput'>
</div>";
}
private function createDescriptionInput() {
return "<div class='form-group'>
<textarea class='form-control' placeholder='Description' name='descriptionInput' rows='3'></textarea>
</div>";
}
private function createPrivacyInput() {
return "<div class='form-group'>
<select class='form-control' name='privacyInput'>
<option value='0'>Private</option>
<option value='1'>Public</option>
</select>
</div>";
}
private function createCategoriesInput() {
$query = $this->con->prepare("SELECT * FROM categories");
$query->execute();
$html = "<div class='form-group'>
<select class='form-control' name='categoryInput'>";
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$id = $row["id"];
$name = $row["name"];
$html .= "<option value='$id'>$name</option>";
}
$html .= "</select>
</div>";
return $html;
}
private function createUploadButton() {
return "<button type='submit' class='btn btn-primary' name='uploadButton'>Upload</button>";
}
}
?>
VideoProcessor.php file:
<?php
class VideoProcessor {
private $con;
private $sizeLimit = 500000000;
private $allowedTypes = array("mp4", "flv", "webm", "mkv", "vob", "ogv", "ogg", "avi", "wmv", "mov", "mpeg", "mpg");
public function __construct($con) {
$this->con = $con;
}
public function upload($videoUploadData) {
$targetDir = "uploads/videos/";
$videoData = $videoUploadData->videoDataArray;
$tempFilePath = $targetDir . uniqid() . basename($videoData["name"]);
//uploads/videos/5aa3e9343c9ffdogs_playing.flv
$tempFilePath = str_replace(" ", "_", $tempFilePath);
$isValidData = $this->processData($videoData, $tempFilePath);
if(!$isValidData) {
return false;
}
if(move_uploaded_file($videoData["tmp_name"], $tempFilePath)) {
$finalFilePath = $targetDir . uniqid() . ".mp4";
if(!$this->insertVideoData($videoUploadData, $finalFilePath)) {
echo "Insert query failed";
return false;
}
}
}
private function processData($videoData, $filePath) {
$videoType = pathInfo($filePath, PATHINFO_EXTENSION);
if(!$this->isValidSize($videoData)) {
echo "File too large. Can't be more than " . $this->sizeLimit . " bytes";
return false;
}
else if(!$this->isValidType($videoType)) {
echo "Invalid file type";
return false;
}
else if($this->hasError($videoData)) {
echo "Error code: " . $videoData["error"];
return false;
}
return true;
}
private function isValidSize($data) {
return $data["size"] <= $this->sizeLimit;
}
private function isValidType($type) {
$lowercased = strtolower($type);
return in_array($lowercased, $this->allowedTypes);
}
private function hasError($data) {
return $data["error"] != 0;
}
private function insertVideoData($uploadData, $filePath) {
$query = $this->con->prepare("INSERT INTO videos(title, uploadedBy, description, privacy, category, filePath)
VALUES(:title, :uploadedBy, :description, :privacy, :category, :filePath)");
$query->bindParam(":title", $uploadData->title);
$query->bindParam(":uploadedBy", $uploadData->uploadedBy);
$query->bindParam(":description", $uploadData->description);
$query->bindParam(":privacy", $uploadData->privacy);
$query->bindParam(":category", $uploadData->category);
$query->bindParam(":filePath", $filePath);
return $query->execute();
}
}
?>
VideoUploadData.php File:
<?php
class VideoUploadData {
public $videoDataArray, $title, $description, $privacy, $category, $uploadedBy;
public function __construct($videoDataArray, $title, $description, $privacy, $category, $uploadedBy) {
$this->videoDataArray = $videoDataArray;
$this->title = $title;
$this->description = $description;
$this->privacy = $privacy;
$this->category = $category;
$this->uploadedBy = $uploadedBy;
}
}
?>
processing.php File:
<?php
require_once("includes/header.php");
require_once("includes/classes/VideoUploadData.php");
require_once("includes/classes/VideoProcessor.php");
if(!isset($_POST["uploadButton"])) {
echo "No file sent to page.";
exit();
}
// 1) create file upload data
$videoUploadData = new VideoUploadData(
$_FILES["fileInput"],
$_POST["titleInput"],
$_POST["descriptionInput"],
$_POST["privacyInput"],
$_POST["categoryInput"],
"REPLACE-THIS"
);
// 2) Process video data (upload)
$videoProcessor = new VideoProcessor($con);
$wasSuccessful = $videoProcessor->upload($videoUploadData);
// 3) Check if upload was successful
?>
upload.php File:
<?php
require_once("includes/header.php");
require_once("includes/classes/VideoDetailsFormProvider.php");
?>
<div class="column">
<?php
$formProvider = new VideoDetailsFormProvider($con);
echo $formProvider->createUploadForm();
?>
</div>
<?php require_once("includes/footer.php"); ?>
Per https://www.php.net/manual/en/features.file-upload.errors.php:
UPLOAD_ERR_INI_SIZE
Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.
You should be able to increase upload_max_filesize in php.ini to resolve the issue.

How to set dynamic title to extended public variable with OOP?

I hope someone can help me. How can I best dynamically change page title, desc, or key vs..vs..by extending the original class? Here is what I have so far:
<?php
class siteGlobal
{
public $arr = array('title'=>'Page Default title','desc'=>'Page default description');
public function pageHeader()
{ ?>
<!doctype html><html>
<?php }
public function metaTags()
{ ?>
<head>
<meta charset="utf-8">
<title><?php echo $this->arr['title'];?></title>
<meta name="description" content="<?php echo $this->arr['desc'];?>">
<?php }
public function pageBody()
{ ?>
</head>
<body>
<?php }
public function pageFooter()
{ ?>
</body>
</html>
<?php }
} ?>
OTHER PAGE
require_once('siteGlobal.php');
class pageDetail extends siteGlobal
{
public function __construct()
{
$this->pageHeader();
$this->newMetas();
$this->startBody();
$this->sayfaBilgileri();
$this->pageFooter();
}
public function newMetas()
{
parent::metaTags();
}
public function sayfaBilgileri()
{
//HOW I can write a new title and description in this function to siteGlobal.php (public $metaInfo) ?>
<div style="width:640px; margin:0 auto;">
<h1>Page New Title</h1>
<h2>Page New Subtitle</h2>
<p>Lorem Ipsum, bla bla....</p>
</div>
<?php }
}
$writePage = new pageDetail(); ?>
You can try to create a method in the parent class say:
protected function setTitle($title){
$this->arr['title'] = $title;
}
and use it in the extended class this way:
parent::setTitle("My title");

How to pass dynamic variable through class function

I'm trying to pass every value through the function (it's a part of cms) so later on user can view content and then when he confirms it is saved to database and a separate file is made that looks exactly as preview but I don't know and have no idea how to pass a dynamic variable like $_POST['champno'.$i] right below
public function display($patch, $champ_number){
echo '<h1 style="float: left;">PATCH ';
echo $patch.'</h1>
<nav id="header-menu">
<ul>
<li>PATCHES</li>
<li>CHAMPIONS</li>
<li>ITEMS</li>
<li>CHANGES</li>
</ul>
</nav>
<div id="title">
<h2>CHAMPION BALANCE CHANGES</h2>
</div>';
for($i=1;$i<=$champ_number; $i++){
?>
<style type="text/css" scoped>
#media(min-width: 640px){
.<?php echo $_POST['champno'.$i]; ?>{
background-image: url('../../assets/champions/<?php echo $_POST['champno'.$i]; ?>_pc.jpg');
Extract the information from $_POST['champno'.$i] into a dedicated array and call the function with that:
$champions = array();
for ($i = 1; $i <= $champ_number; $i++)
$champions[] = $_POST['champno' . $i];
$obj->display($patch, $champions);
In the function:
function display($patch, $champions) {
...
foreach ($champions as $champion) {
$champion = htmlspecialchars($champion);
?>
<style type="text/css" scoped>
#media(min-width: 640px) {
.<?php echo $champion; ?> {
background-image: url('../../assets/champions/<?php echo $champion; ?>_pc.jpg');
...
<?php
}
}
Then you can use the function with the database and all other input sources.

CodeIgniter create a layout/template library

Before I begin I have to say that I have recently started learning CodeIgniter, so I'm sorry if I repeat this subject once again.
In procedural php I would do something like this
// the header.php
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="blah blah">
<title>My Site</title>
<link href="css/main.css" rel="stylesheet" media="screen">
<php? if($current_page == 'about.php'): ?>
<link href="css/secondary.css" rel="stylesheet" media="screen"> // or some embed styles (<stlye> ... </style>)
<?php endif; ?>
<script src="http://code.jquery.com/jquery.js"></script>
<script src="js/main_script.js"></script>
<php? if($current_page == 'contact.php'): ?>
<script src="js/validation.js"></script>
<?php endif; ?>
</head>
<body>
// end of header.php
include('template/header.php');
<h1>Heading1</h1>
<p>Lorem Ipsum...</p>
include('template/footer.php');
//footer.php
//maybe some js and here
</body>
</html>
So I would like to do something similar and in CI. All pages/views will have the same main styles or scripts, but in some cases, some specific pages (like contact.php) may include, and only in these pages, some specific styles or scripts (like the validation.js).
I have found this video that shows how to create a template/layout library using CI, but I'm not quite sure how I can apply this functionality to work properly.
Put the bottom class in libraries/Layout.php (your app not the sys). In the autoload add the library:
$autoload['libraries'] = array('layout');
In your controller just write $this->layout->render();
The class will render the layout views/layouts/default.php and the view views/$controller.views/$method.php
In the default layout just put
<?php $this->load->view($view,$data); ?>
and thats it.
The code is
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
class Layout
{
public $data = array();
public $view = null;
public $viewFolder = null;
public $layoutsFodler = 'layouts';
public $layout = 'default';
var $obj;
function __construct()
{
$this->obj =& get_instance();
}
function setLayout($layout)
{
$this->layout = $layout;
}
function setLayoutFolder($layoutFolder)
{
$this->layoutsFodler = $layoutFolder;
}
function render()
{
$controller = $this->obj->router->fetch_class();
$method = $this->obj->router->fetch_method();
$viewFolder = !($this->viewFolder) ? $controller.'.views' : $this->viewFolder . '.views';
$view = !($this->view) ? $method : $this->view;
$loadedData = array();
$loadedData['view'] = $viewFolder.'/'.$view;
$loadedData['data'] = $this->data;
$layoutPath = '/'.$this->layoutsFodler.'/'.$this->layout;
$this->obj->load->view($layoutPath, $loadedData);
}
}
?>
I'm doing layout thing is like bellow.
I get content to data['content'] variable.
This is my controller.
class Article extends MY_Controller {
function __construct() {
parent::__construct();
$this->load->model('article_model');
}
public function index() {
$data['allArticles'] = $this->article_model->getAll();
$data['content'] = $this->load->view('article', $data, true);
$this->load->view('layout', $data);
}
This is my Layout.I'm using bootstrap layout.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Starter Template for Bootstrap</title>
<base href="<?php echo base_url(); ?>" />
<!-- Bootstrap core CSS -->
<link href="assets/bootstrap3.0.1/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<!-- <link href="starter-template.css" rel="stylesheet">-->
<!-- Just for debugging purposes. Don't actually copy this line! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"> Article Management System</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#"> Admin <span class="caret"></span></a>
<ul class="dropdown-menu">
<li>Add Article</li>
<li>All Article</li>
</ul>
</li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
<div class="container" style="margin-top: 80px;">
<?php echo $content; ?>
</div><!-- /.container -->
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="assets/bootstrap3.0.1/js/bootstrap.min.js"></script>
</body>
</html>
This is my content view
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="page-header">
<h4>All Articles </h4>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th></th>
</tr>
</thead>
<tbody>
<?php foreach ($allArticles as $row) { ?>
<tr>
<td><?php echo $row->title; ?></td>
<td><?php echo substr($row->description,0,100); ?> ....</td>
<td></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
I have achieved the same thing with the following:
Put this code in your ./application/core/MY_Controller.php file:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Controller extends CI_Controller
{
protected $layout = 'layout/main';
public function __construct()
{
parent::__construct();
}
protected function render($file = NULL, &$viewData = array(), $layoutData = array())
{
if( !is_null($file) ) {
$data['content'] = $this->load->view($file, $viewData, TRUE);
$data['layout'] = $layoutData;
$this->load->view($this->layout, $data);
} else {
$this->load->view($this->layout, $viewData);
}
$viewData = array();
}
}
Create a layout folder inside ./application/views directory and then create your files with the entire html in it. Just put the <?php echo $content; ?> in that file where you want to put the dynamic content in it. Then in your controllers use $this->render(); and pass your file path and data. If you want to use a different layout for specific page just put the $this->layout = 'path_to_your_layout_file'; it will override the layout file to be used.
I have struggled with a similar problem not long ago. My solution to it was the following :
In your controller constructor create 2 arrays one of css files and one of js files and put in them the files common to all views.
And in each function in the controller add to them logic specific files.
For your example you'll have something like this :
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->page_data = array();
$this->page_data['css']=array('main.css','bootstrap.css');
$this->page_data['js']=array('main.js','bootstrap.js');
}
public function about()
{
array_push($this->page_data['css'],'secondary.css');
$this->load->view('main_layout',$this->page_data)
}
public function contact()
{}
}
And in your view file you'll just iterate over the $css and $js array and include them one by one.
You can extend that easily to include header and footer templates by pushing them into the page_data array.
I ended up switching to doing all the templating on the client-side with Backbone and using Code Igniter as a REST API only but this technique gave me relatively clean code for what I needed.
5 Simple Steps to create CodeIgniter Template:
Step #1
Template.php # libraries
Step #2
Write following code
/* Start of file Template.php */
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Template {
var $template_data = array();
function set($name, $value)
{
$this->template_data[$name] = $value;
}
function load($template = '', $view = '' , $view_data = array(), $return = FALSE)
{
$this->CI =& get_instance();
$this->set('contents', $this->CI->load->view($view, $view_data, TRUE));
return $this->CI->load->view($template, $this->template_data, $return);
}
}
/* End of file Template.php */
/* Location: ./system/application/libraries/Template.php */
Step #3
open config/autoload.php
at line 55 replace
$autoload['libraries'] = array('database', 'session','encrypt');
with this code
$autoload['libraries'] = array('database', 'session','encrypt', 'template');
Step #4
On my controller call template as
//start
$this->template->load(TEMPLATE_NAME, VIEW_NAME , $this->data);
//end
Step #5
On views
create a file as custom_template.php
And place there following code--
//start
<?php $this->load->view('elements/header'); ?>
<div><?php echo $contents;?></div>
<?php $this->load->view('elements/footer'); ?>
//end
N.B. In views in elements folder create two files as header.php And footer.php
I use this, in older version of CodeIgniter and it works for version 3 as well.
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
class Layout
{
var $obj;
var $layout;
function Layout($layout = "layout_main")
{
$this->obj =& get_instance();
$this->layout = $layout;
}
function setLayout($layout)
{
$this->layout = $layout;
}
function view($view, $data=null, $return=false)
{
$loadedData = array();
$loadedData['content_for_layout'] = $this->obj->load->view($view,$data,true);
if($return)
{
$output = $this->obj->load->view($this->layout, $loadedData, true);
return $output;
}
else
{
$this->obj->load->view($this->layout, $loadedData, false);
}
}
}
?>
and to call this in the controller I use:
$this->layout->view('apps/apps', $data);

Following a Codeigniter/Ajax/Jquery tutorial: Can't seem to debug what I'm doing wrong

I'm following the tutorial here:
http://www.jotorres.com/2012/01/using-jquery-and-ajax-with-codeigniter/
For my view, I have:
<script type="text/javascript" src="<?php echo jquery ?>"></script>
<button type="button" name="getdata" id="getdata">Get Data.</button>
<div id="result_table">
</div>
<script type="text/javascript" language="javascript">
$('#getdata').click(function(){
$.ajax({
url: "<?php echo base_url().'users/get_all_users';?>",
type:'POST',
dataType: 'json',
success: function(output_string){
$("#result_table").append(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
</script>
The header and footer are predominantly links to other pages on the website but the relevant sections of the header and beginning are:
<!DOCTYPE html>
<!-- Website template by Jeremiah Tantongco, jtantongco#gmail.com -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?php echo $title ?> </title>
<link rel="stylesheet" href="<?php echo template ?>" type="text/css" />
<link rel="stylesheet" href="<?php echo display_elements ?>" type="text/css" />
</head>
Note: template and display_elements are variables pointing to css files somewhere on the server declared in config/constants
Note: jquery is a variable declared in config/constants that points to the newest jquery file on the server. It is the newest developer version available.
for controller methods:
public function test(){
$this->renderTemp_noData('users/test', 'Test page');
}
public function get_all_users(){
$query = $this->db->get('users');
if($query->num_rows > 0){
$header = false;
$output_string = "";
$output_string .= "<table border='1'>\n";
foreach ($query->result() as $row){
$output_string .= "<tr>\n";
$output_string .= "<th>{" . $row->uid ."}</th>\n";
$output_string .= "</tr>\n";
}
$output_string .= "</table>\n";
}
else{
$output_string = "There are no results";
}
//echo $output_string;
echo json_encode($output_string);
}
public function renderTemp_noData($page, $title) {
$data['title'] = $title;
$accountType = $this->session->userdata('aid');
switch ($accountType) {
case 0:
$this->load->view('templates/LI_header', $data);
$this->load->view($page);
$this->load->view('templates/LI_footer');
break;
case 1:
$this->load->view('templates/LI_header_role1',$data);
$this->load->view($page);
$this->load->view('templates/LI_footer_role1');
break;
case 2:
$this->load->view('templates/LI_header_role2',$data);
$this->load->view($page);
$this->load->view('templates/LI_footer_role2');
break;
case 3:
$this->load->view('templates/LI_header_role3',$data);
$this->load->view($page);
$this->load->view('templates/LI_footer_role3');
break;
default:
redirect('/sessions/log_in/','refresh');
}
}
When I go to the page with the Get Data button, I press it and nothing happens. So if anyone knows how to expose the error message that would be great. Also, When I test to see output for get_all_users, this is what I get:
"<table border='1'>\n<tr>\n<th>{1}<\/th>\n<\/tr>\n<tr>\n<th>{2}<\/th>\n<\/tr>\n<tr>\n<th>{3}<\/th>\n<\/tr>\n<tr>\n<th>{4}<\/th>\n<\/tr>\n<tr>\n<th>{5}<\/th>\n<\/tr>\n<tr>\n<th>{6}<\/th>\n<\/tr>\n<tr>\n<th>{7}<\/th>\n<\/tr>\n<tr>\n<th>{8}<\/th>\n<\/tr>\n<tr>\n<th>{9}<\/th>\n<\/tr>\n<tr>\n<th>{10}<\/th>\n<\/tr>\n<tr>\n<th>{12}<\/th>\n<\/tr>\n<tr>\n<th>{13}<\/th>\n<\/tr>\n<tr>\n<th>{14}<\/th>\n<\/tr>\n<tr>\n<th>{15}<\/th>\n<\/tr>\n<tr>\n<th>{16}<\/th>\n<\/tr>\n<tr>\n<th>{17}<\/th>\n<\/tr>\n<tr>\n<th>{18}<\/th>\n<\/tr>\n<\/table>\n"
Is JSON supposed to look this way? My gut says no but this is the first time I've ever used JSON, Jquery, and AJAX. Also, The numerical values are correct. Looking at my database, there are only UIDs 1-18 with no 11.
Your get_all_users() function adds HTML to your $output_string, which you are then json_encoding. That's not quite how JSON works. Replace with:
public function get_all_users() {
$this->output->set_content_type('text/javascript; charset=UTF-8');
$query = $this->db->get('users');
echo json_encode($query->result());
}
That said, your database calls should live in a model, not your controller.

Categories