questions about MVC architecture in web application - model-view-controller

I have certain questions since I'm doing a web app, and I feel kinda confused about keeping the mvc structure in a web application without using any frameworks.
Here is the structure of my app.
index:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<!--<link rel="stylesheet" type="text/css" href="index.css" />-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script src="js/functions.js"></script>
<script>
$(document).ready(function() {
loginSend();
});
</script>
<title></title>
</head>
<body>
<div id="login">
Username: <input type="text" id="username" name="username"><br>
Password: <input type="password" id="password" name="password"><br>
<input id="send" type="button" value="Enviar">
</div>
</body>
</html>
The loginsend function sends the data to service.php
<?php
include('server/main.php');
$action = $_POST['action'];
switch($action){
case "loginCheck":
$username=$_POST['username'];
$password=$_POST['password'];
$users = new users();
echo $users->loginCheck($username,$password);
break;
}
?>
And the service uses some classes I defined in main.php
<?php
class db{
public function conn() {
try{
$dbhost = "localhost";
$dbname = "eout";
$dbuser = "root";
$dbpass = "";
if($conn = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass)){
return($conn);
}
}
catch (Exception $e){
echo "Se ha presentado un error al conectar con la base de datos".$e;
}
}
}
class users{
function loginCheck($username, $password) {
try{
$db = new db();
$conn = $db->conn();
$pass_encriptada = md5 ($password);
$SQL_LOGIN_CHECK = "SELECT * FROM users where username='".$username."' and password='".$pass_encriptada."' and deleted='0'";
$conn->prepare($SQL_LOGIN_CHECK);
foreach($check = $conn->query($SQL_LOGIN_CHECK) as $row) {
$username_check = $row['username'];
if ($username_check == $username){
session_start();
$_SESSION['logged'] = 1;
$_SESSION['user_id'] = $row['id'];
$_SESSION['username'] = $row['username'];
$_SESSION['namelastname'] = $row['name'] ." ".$row['lastname'];
$usertype_id = $row['usertype_id'];
if ($usertype_id == 1 ){ //problema
$_SESSION['teacher'] = 1;
$response = "teacher";
$json = json_encode($response);
echo $json;
}
if ($usertype_id != 1 ){ //problema
$response = "user";
$json = json_encode($response);
echo $json;
}
}
}
}
catch(Exception $e){
echo "Se ha presentado un error en loginCheck".$e;
}
}
}
?>
In this case, I understand that index.php its my view, however I have certain doubts about the model/controller part. I understand in my example that the main file is the one that interacts with data, so it must be the model... in my case... its service.php my controller? Since is the one that interacts with the model? I feel kinda confused about this. In case I am wrong. How can I make a controller?
Thanks in advance.

Related

how to add alert in to login my login page like "login successfully"?

I have login page but i am dont know where i can take this alerts ,
i will take my script like this
echo ("<SCRIPT LANGUAGE='JavaScript'> window.alert('Your Login Succesfully ,'); window.location.href='home'; </SCRIPT>");
but i dont know how to make if else condition on my query in the model and contoller .I using num_rows but its didnt work .
my controller
public function login()
{
$u = $this->input->post('username');
$p = $this->input->post('password');
$data = $this->app_model->getlogindata($u,$p);
return $data;
}
my model
public function getlogindata($username,$password)
{
$u = $username;
$p = md5($password);
$cek_login = $this->db->get_where('login', array('username' => $u,'password'=>$p));
if(count($cek_login->result())>0)
{
foreach ($cek_login->result() as $qck)
{
if($qck->level=='puskesmas')
{
// $ambil_data = $this->db->get_where('puskesmas',array('id_puskesmas' => $u));
$this->db->select('*');
$this->db->from('puskesmas');
$this->db->join('login', 'puskesmas.id_puskesmas=login.id_puskesmas');
$this->db->where('username', $u);
$ambil_data = $this->db->get();
foreach ($ambil_data->result() as $qad)
{
$sess_data['logged_in'] = 'yes';
$sess_data['id_puskesmas'] = $qad->id_puskesmas; //
$sess_data['nama_puskesmas'] = $qad->nama_puskesmas;
$sess_data['alamat_puskesmas'] = $qad->alamat_puskesmas;
$sess_data['nama_petugas'] = $qad->nama_petugas;
$sess_data['nomor'] = $qad->nomor;
$sess_data['email'] = $qad->email;
$sess_data['level'] = $qad->level;
$this->session->set_userdata($sess_data);
}
header('location:'.base_url().'puskesmas');
} //xammp mu aktif?
elseif($qck->level=='dinas')
{
//$ambil_data = $this->db->get_where('dinas',array('id_dinas' => $u));
$this->db->select('*');
$this->db->from('dinas');
$this->db->join('login', 'dinas.id_dinas=login.id_dinas');
$this->db->where('username', $u);
$ambil_data = $this->db->get();
foreach ($ambil_data->result() as $qad)
{
$sess_data['logged_in'] = 'yes';
$sess_data['id_dinas'] = $qad->id_dinas;
$sess_data['nama_dinas'] = $qad->nama_dinas;
$sess_data['alamat_dinas'] = $qad->alamat_dinas;
$sess_data['kode_pos'] = $qad->kode_pos;
$sess_data['level'] = $qad->level;
$this->session->set_userdata($sess_data);
}
header('location:'.base_url().'dinas');
}
elseif($qck->level=='admin')
{
//$ambil_data = $this->db->get_where('admin',array('id_admin' => $u));
$this->db->select('*');
$this->db->from('admin');
$this->db->join('login', 'admin.id_admin=login.id_admin');
$this->db->where('username', $u);
$ambil_data = $this->db->get();
foreach ($ambil_data->result() as $qad)
{
$sess_data['logged_in'] = 'yes';
$sess_data['id_admin'] = $qad->id_admin;
$sess_data['nama_admin'] = $qad->nama_admin;
$sess_data['alamat_admin'] = $qad->alamat_admin;
$sess_data['status'] = $qad->status;
$sess_data['level'] = $qad->level;
$this->session->set_userdata($sess_data);
}
header('location:'.base_url().'admin');
}
else{
echo ("<SCRIPT LANGUAGE='JavaScript'> window.alert('Record Updated Successfully'); window.location.href='web'; </SCRIPT>");// i add this and still didnt work
}
}
}
}
in this script i just didnt know where i can take this alerts and what a parameter can i use to add this alerts . like if num_rows = 1 , echo = blablabla
thanks you sir
you have to use flash data in code igniter or you can use ajax callback in success you can alert what you want and redirect to whatever you like.
Controller
$this->session->set_flashdata('error_message', 'Incorrect Username or Password ! Please try again.');
redirect(URL.'backend/login');
View
<?php
if ($this->session->flashdata('error_message'))
{
?>
<div class="alert alert-danger" style="color: #fff;">
<!-- <button class="close" data-close="alert"></button> -->
<span><?php echo $this->session->flashdata('error_message'); ?></span>
</div>
<?php
}
if ($this->session->flashdata('ok_message'))
{
?>
<div class="alert alert-success">
<!-- <button class="close" data-close="alert"></button> -->
<span><?php echo $this->session->flashdata('ok_message'); ?></span>
</div>
<?php
}
?>
try this.i hope it will help you.
else{
echo '<script language="javascript">';
echo 'alert("Record Updated Successfully")';
window.location.href = 'web';
echo '</script>';
}

Polling Chat message content to screen using ajax JSON

Hi I successfully designed a chat message system between users and it works fine. The only problem I am having at this point is polling data from chat table to browser real time.
The messages are displayed using ajax and the setInterval works as I checked the console. The issue is that it does not capture new entries to the table for display and hence the user has to keep refreshing the page to see new content.
Please help. My code is below. Please forgive my file naming convention as I will change it later on.
PS this is developed using codeigniter framework.
**Chats.php - Controller**
public function ajax_get_chat_messages(){
echo $this->_get_chat_messages();
}
function _get_chat_messages($recipient = null)
{
$user_id = $this->session->userdata('user_id');
$recipient = $this->input->post('recipient');
$data['recipient'] = $this->User_model->get_users($user_id);
$data['chats_count'] = $this->Chats_model->get_chat_messages_count($recipient);
$content = $this->Chats_model->get_chat_messages_count($recipient);
$data['chats'] = $this->Chats_model->get_chat_messages($user_id);
$result = array('status' =>'ok', 'content'=>$content);
return json_encode($result);
}
**Model - Chats_model.php**
public function get_chat_messages_count($recipient = null){
$session = $this->session->userdata('user_id');
$this->db->select('*');
$this->db->from('chat_messages');
$this->db->join('users', 'users.user_id = chat_messages.user_id');
$this->db->where(array('chat_messages.user_id' => $session));
$this->db->where(array('chat_messages.recipient' => $recipient));
$this->db->or_where(array('chat_messages.user_id' => $recipient));
$this->db->where(array('chat_messages.recipient' => $session));
$this->db->where_in(array('chat_messages.chat_id' => $session , $recipient));
$query = $this->db->get();
return $query->result_array();
}
**View - chats_view.php**
<script type="text/javascript">
var user = "<div class='timeline-item' id='view'><ul><?php foreach($chats_count as $chat){echo '<li>'; echo $chat['username']; echo '</li>'; }?></ul></div>";
</script>
<div class="wrapper wrapper-content">
<div class="row animated fadeInRight">
<div class="col-lg-12">
<div class="ibox float-e-margins">
<div class="ibox-title">
<h5>Chat</h5>
<div class="ibox-tools" >
</div>
</div>
<div class="ibox-content inspinia-timeline" id="view1" >
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
**JS - chat2.js**
$(document).ready(function(){
setInterval(function() { get_chat_messages(); }, 2500)
$("input#chat_message").keypress(function(e){
if(e.which == 13){
$("a#submit_message").click();
return false;
}
});
function get_chat_messages(){
$.post(base_url +"user/chats/ajax_get_chat_messages",{user: user}, function(data) {
if(data)
{
var current_content = $("#view1").html();
$("#view1").html(user);
console.log(user);
}
else
{
}, "json");
}
get_chat_messages();
});
Images attached showing the table structure, the chat page on browser and console data.
[Chat page on browser, only showing username for testing purposes][1]
[Chat Table][2]
[Console Data, only showing username for testing purposes][3]

dynamic master template in codeigniter

My problem is this:
I have a masterpage:
<head>
<meta charset="utf-8" />
<title><?php echo isset($title)? $title: NULL; ?></title>
<?php $this->load->view('layout/header'); ?>
</head>
<body>
<!-- BEGIN PAGE BASE CONTENT -->
<?php $this->load->view($content);?>
<!-- END PAGE BASE CONTENT -->
</body>
and my dashboard controller:
class Dashboard extends CI_Controller {
public function index()
{
if($this->session->userdata('login') == true){
$data['title'] = 'Dashboard';
$data['content'] = 'pages/dashboard';
$this->load->view('layout/master', $data);
}
else{
redirect('auth');
}
}
and my add controller:
if($this->session->userdata('login') == true){
$data['title'] = 'افزودن مشتری';
$data['content'] = 'pages/add_customer';
$this->load->view('layout/master', $data);
}
else{
redirect('auth');
}
My problem is that at first when i call dashboard, everything is OK. but when i call add, everything mess up like there is no CSS attached or something.
Should i do something before set value to $content?
I cant understand what the problem is.
When in a function you can't do anything with it. But can't do anything outside. Like your else statement.
public function add(){
$data['title'] = 'افزودن مشتری';
$data['content'] = 'pages/add_customer';
$this->load->view('layout/master', $data);
}
else{
redirect('auth');
}
This is completely wrong practices. Just use
public function add(){
$data['title'] = 'افزودن مشتری';
$data['content'] = 'pages/add_customer';
$this->load->view('layout/master', $data);
}
Load Codeigniter for the Arabic Letters
Codeigniter by default is set to use UTF-8 for much of its internal functionality, so just make sure the charset is set to UTF-8 in your application/config/config.php file.
$config['charset'] = "UTF-8";
And set the header too
header('Content-Type: text/html; charset=utf-8');

Overriding Metadata in codeigniter template

I am a newbie in codeigniter and I am not the first web developer of the project however I discovered in views folder it has template.php which loads in all pages. how can i override the metadata of the header inside views folder which loads the header of the template.php? I wan it to have different metadata.
Here's the code of Template.php
<title>I Sold My Business - Your one-stop shop for online business brokerage</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<meta name="description" content="Whether you’re an entrepreneur trying to buy a business online or a broker who wants to sell businesses, I Sold My Business is here to help you. Visit us today!">
<meta name="keywords" content="sold business online, buy business online, sell business online">
<?php echo #$template['framework']; ?>
<?php echo #$template['bootstrap']; ?>
<?php echo #$template['head']; ?>
<link rel="stylesheet" type="text/css" href="<?php echo base_url('templates/site/reconvert_style.css'); ?>" />
<link rel="stylesheet" type="text/css" href="<?php echo base_url('templates/site/stylesheet.css'); ?>" />
<script type='text/javascript'>
(function (d, t) {
var bh = d.createElement(t), s = d.getElementsByTagName(t)[0];
bh.type = 'text/javascript';
bh.src = '//www.bugherd.com/sidebarv2.js?apikey=rkdoxsrzmxvrsrt6ailjsa';
s.parentNode.insertBefore(bh, s);
})(document, 'script');
</script>
Here's the code inside controllers folder home.php
class Home extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('business_category_model');
$this->load->model('franchise_category_model');
$this->load->model('account_model');
$this->load->model('country_model');
}
public function index()
{
$template = array();
$template['title'] = "Home";
$this->load->model(array('business_listing_model', 'featured_business_model', 'franchise_model'));
$this->load->helper('text');
$page = array();
$page['countries'] = $this->country_model->get_all();
$featured_businesses = $this->featured_business_model->random(3);
$featured_count = 0;
foreach($featured_businesses->result() as $index => $featured_business)
{
if($featured_business->type == 'business' || $featured_business->type == 'video')
{
$page['featured_businesses'][$featured_count] = (array) $this->business_listing_model->get_one($featured_business->business_id);
}
else
{
$page['featured_businesses'][$featured_count] = (array) $this->franchise_model->get_one($featured_business->business_id);
}
$page['featured_businesses'][$featured_count]['f_type'] = $featured_business->type;
$featured_count++;
}
if($featured_businesses->num_rows() < 3)
{
$limit = 3 - $featured_businesses->num_rows();
$random_business = $this->business_listing_model->get_random($limit);
foreach($random_business->result() as $index => $featured_business)
{
$page['featured_businesses'][$featured_count] = (array) (array) $this->business_listing_model->get_one($featured_business->business_listing_id);
$page['featured_businesses'][$featured_count]['f_type'] = 'business';
$featured_count++;
}
}
$page['business_categories'] = $this->business_category_model->get_all('', array('business_category_title' => 'asc'));
$page['franchise_categories'] = $this->franchise_category_model->get_all();
$template['content'] = $this->template->get_view('home', $page, 'site');
$this->template->render($template, 'site');
}
public function sell_your_biz()
{
$username = $this->session->userdata('username');
$account_type = $this->session->userdata('account_type');
$account = $this->account_model->get_by_username($username);
if(strlen($username)==0)
{
$this->template->notification('Please login or create an account to post a listing', 'error');
redirect('/login/');
}
$template = array();
$template['title'] = "Sell Your Biz";
$page = array();
$template['content'] = $this->template->get_view('sell_your_biz', $page, 'site');
$this->template->render($template, 'site');
}
public function view_reconvert()
{
$template = array();
$template['title'] = "Home";
$page = array();
$page['countries'] = $this->country_model->get_all();
$page['business_categories'] = $this->business_category_model->get_all();
$page['franchise_categories'] = $this->franchise_category_model->get_all();
$template['content'] = $this->template->get_view('home2', $page, 'site');
$this->template->render($template, 'site' , 'template_rconvert');
}
}
This is just one way of doing it, but you can eg set/define your meta data in your controller as such:
public function index()
{
$template = array();
$template['title'] = "Home";
$page['meta_desc'] = "Description here";
$page['meta_key'] = "Keywords here";
Then change the view file to correspond to the same variables:
<meta name="description" content="<?= $meta_desc?>" />
<meta name="keywords" content="<?=$meta_key" />

joomla dynamic dropdown registrationform

1) I have a basic Joomla form that has three drop downs for Country, Town and Shop
2) I need to get the dropdown list based on the dropdown list provided above.
I have achieved to get the data from database and create drop down by coding in registration.xml in
usercomponent
What needs to be achieved:
I am trying to create dynamic drop downs based on the above data selected in the dropdown.
Please help me I am working hard for this I couldn't find the solution and code break through
I've created a basic non-Joomla example of this here
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>
<body>
<?php
$username = "USERNAME";
$password = "PASSWORD";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
$selected = mysql_select_db("DATABASE", $dbhandle) or die("Could not select examples");
$result = mysql_query("SELECT * FROM `values`");
$values=array();
$counter=0;
while($row = mysql_fetch_array($result))
{
$values[$counter]=$row{'country'};
$counter++;
}
mysql_close($con);
?>
<?php
$i=0;
$countries=array();
foreach($values as $value) {
$exists=false;
if(count($countries)>0) {
foreach($countries as $something) {
if($something==$value) {
$exists=true;
}
}
}
if($exists==false) {
$countries[$i]=$value;
$i++;
}
}
?>
<select id="first-choice">
<option selected value="base">Please Select</option>
<?php
$k=0;
while($k<count($countries)) {
echo "<option value='".$countries[$k]."'>" . $countries[$k] . "</option>";
$k++;
}
?>
</select>
<br />
<select id="second-choice">
<option>Please choose from above</option>
</select>
<br />
<select id="third-choice">
<option>Please choose from above</option>
</select>
<script type="text/javascript">
$("#first-choice").change(function() {
$("#second-choice").load("getter.php?country=" + $("#first-choice").val());
});
$("#second-choice").change(function() {
$("#third-choice").load("getter.php?town=" + $("#second-choice").val());
});
</script>
</body>
</html>
File called getter.php
<?php
$username = "USERNAME";
$password = "PASSWORD";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
$selected = mysql_select_db("DATABASE", $dbhandle) or die("Could not select examples");
if($_GET['country']) {
$countries = mysql_real_escape_string($_GET['country']);
$query = "SELECT * FROM `values` WHERE country='".$countries."'";
$result = mysql_query($query);
$values=array();
$i=0;
while($row = mysql_fetch_array($result))
{
$values[$i]=$row{'town'};
$i++;
}
$i=0;
$towns=array();
foreach($values as $value) {
$exists=false;
if(count($towns)>0) {
foreach($towns as $town) {
if($town==$value) {
$exists=true;
}
}
}
if($exists==false) {
$towns[$i]=$value;
$i++;
}
}
$k=0;
echo "<option selected value='base'>Please Select an Option</option>";
while ($k<count($towns)) {
echo "<option value=".$towns[$k].">" . $towns[$k] . "</option>";
$k++;
}
} elseif ($_GET['town']) {
$town = mysql_real_escape_string($_GET['town']);
$query = "SELECT * FROM `values` WHERE town='".$town."'";
$result = mysql_query($query);
echo "<option selected value='base'>Please Select an Option</option>";
while ($row = mysql_fetch_array($result)) {
echo "<option>" . $row{'shop'} . "</option>";
}
}
?>
Based on the tutorial here. To Joomla this up. You will need to put the getter.php file into the model and call it through JSON (with a suitable controller). Remember to replace all visable text with JText - so it can be made with a language file. You also need to add the jquery into the header with JDocument::addScript or if your using Joomla 3.0 then JHtml::_('jquery.framework'); suffices. Also you must connect to the database through Joomla using JFactory::getDBO
I've put a basic example of this here.
Some notes: You may wish to call a specific version of JQuery as its constantly being updated. 1.9.0 works fine - but I don't know what will be hosted on that link when 2.0.0 comes out and what browser compatibility will be included.
This assumes a database structure of just
id country town shop. of course I doubt your database schemes are that easy. So remember to adapt this as necessary.
Hopefully this should start you going :)

Resources