retrieve data and show in my webpage by seperating view and model - php

This is my second question on php. I'm trying to query mysql database and show it on my page.
Currently, I'm doing it on php page and the code is as below.
<?php
$host = "localhost";
$dbUserName = "myUserId";
$dbPassword = "MyPwd";
$dbname = "MyDBName";
try
{
$conn = new mysqli($host, $dbUserName, $dbPassword, $dbname);
}
catch(Exception $ex)
{
echo 'Error : ' . $ex->getMessage();
}
$SELECT = "SELECT * FROM OpenPositions";
$result = mysqli_query($conn, $SELECT);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="wrap">
<div class="welcome-two">
<div class="container">
<div class="welcome-detail">
<div class="row">
<div class="col">
<h2>Open <b>one</b></h2>
<div class="tabs">
<?php
while ($row = mysqli_fetch_assoc($result))
{ ?>
<div class="tab">
<input type="radio" id="rd<?php echo $row['JobId']; ?>" name="rd">
<label class="tab-label" for="rd<?php echo $row['JobId']; ?>"><?php echo $row['Title']; ?></label>
<div class="tab-content">
<?php echo $row['JobDescription']; ?><br/>
<p><button id="myBtn">Open Modal</button>
</p>
</div>
</div>
<?php
} ?>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
var accItem = document.getElementsByClassName('accordionItem');
var accHD = document.getElementsByClassName('accordionItemHeading');
for (i = 0; i < accHD.length; i++) {
accHD[i].addEventListener('click', toggleItem, false);
}
function toggleItem() {
var itemClass = this.parentNode.className;
for (i = 0; i < accItem.length; i++) {
accItem[i].className = 'accordionItem close';
}
if (itemClass == 'accordionItem close') {
this.parentNode.className = 'accordionItem open';
}
}
// Get the modal
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
</body>
</html>
Using this, I'm able to retrieve my data and display it. But, This is working when I save it as php.
Here I've 2 questions.
How can I separate the code and have HTML displaying data and php doing db related tasks?
When I click on the button, how can I pass the id and show it in the modal?
Thanks

You can't really separate all of the php and HTML thing. But you can do something like this:
first create 2 file:
db_connection_function.php
index.php // Yeah, you can't escape from .php file extension.
relocate your database connection and query to file db_connection_function.php
<?php
$host = "localhost";
$dbUserName = "myUserId";
$dbPassword = "MyPwd";
$dbname = "MyDBName";
try
{
$conn = new mysqli($host, $dbUserName, $dbPassword, $dbname);
}
catch(Exception $ex)
{
echo 'Error : ' . $ex->getMessage();
}
$SELECT = "SELECT * FROM OpenPositions";
$result = mysqli_query($conn, $SELECT);
?>
And this content of file index.php
<?php include 'db_connection_function.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="wrap">
<div class="welcome-two">
<div class="container">
<div class="welcome-detail">
<div class="row">
<div class="col">
<h2>Open <b>one</b></h2>
<div class="tabs">
<?php
while ($row = mysqli_fetch_assoc($result))
{ ?>
<div class="tab">
<input type="radio" id="rd<?php echo $row['JobId']; ?>" name="rd">
<label class="tab-label" for="rd<?php echo $row['JobId']; ?>"><?php echo $row['Title']; ?></label>
<div class="tab-content">
<?php echo $row['JobDescription']; ?><br/>
<p><button id="myBtn">Open Modal</button>
</p>
</div>
</div>
<?php
} ?>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
var accItem = document.getElementsByClassName('accordionItem');
var accHD = document.getElementsByClassName('accordionItemHeading');
for (i = 0; i < accHD.length; i++) {
accHD[i].addEventListener('click', toggleItem, false);
}
function toggleItem() {
var itemClass = this.parentNode.className;
for (i = 0; i < accItem.length; i++) {
accItem[i].className = 'accordionItem close';
}
if (itemClass == 'accordionItem close') {
this.parentNode.className = 'accordionItem open';
}
}
// Get the modal
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
</body>
</html>
About how to pass id to your modal is like this:
first, put your data 'id' in the attribute of modal button
...
<p><button class="myBtn" data-id="<?php echo $row['JobId']; ?>" data-toggle="modal" data-target="#myModal">Open Modal</button>
...
must change "myBtn" to class, because id can't be used to many data.
And this is for your modal
$(".myBtn").click(function(){
JobId = $(this).data('id')
// put the id into modal
$('div#myModal div.modal-content p').html(JobId)
})

Related

How to fix code PHP DOM HTML Parse - Loop

I started to play building a PHP HTML Parser,
and I have some trouble:
The HTML code is as follows:
<div class="list">
<div class="b">
<div class="c">
<a href="http://link.com">
<div class="d">Category</div>
<div class="e">
<img src="https://link.com/img.png">
</div>
<h1>TITLE</h1>
<div class="f">paragraph 1</div>
<div class="g">paragraph 2</div>
<div class="h">
<div class="i">
<div class="j">Quot</div>
</div>
</div>
</a>
</div>
</div>
<div class="b">
<div class="c">
<a href="http://link2.com">
<div class="d">Category2</div>
<div class="e">
<img src="https://link2.com/img.png">
</div>
<h1>TITLE 2</h1>
<div class="f">paragraph 12</div>
<div class="g">paragraph 22</div>
<div class="h">
<div class="i">
<div class="j">Quot 2</div>
</div>
</div>
</a>
</div>
</div>
My PHP Code:
$classname = "list";
$xPath = new DomXPath($dom);
$find = $xPath->query("//*
[contains(#class, '$classname')]");
$get = $find->item(0);
$link = $get->getElementsByTagName('a');
$data = array();
foreach ($link as $val)
{ $data[] = array(
'link' => $link->item($no)
->getAttribute('href'),
);
$no++;
}
I want the results like this:
-http://link.com
-category
-http://link.com/img.png
-paragraph 1
-paragraph 2
-quot
-http://link2.com
-category2
-http://link2.com/img.png
-paragraph 12
-paragraph 22
-quot2
Here is how you could do it using jQuery and Mustache js a templating tool.
https://jsfiddle.net/mcroteau/zyouxfq4/
<script type="text/javascript" src="jQuery.js"></script>
<script type="text/javascript" src="Mustache.js"></script>
<script type="text/javascript">
var row = `
<div class="content-row">
<div class="link">
{{link}}
</div>
<h1>{{category}}</h1>
<img src="{{image}}" style="border:solid 1px #ddd; height:20px; width:20px;"/><br/>
<p>{{paragraphOne}}</p>
<p>{{paragraphTwo}}</p>
<p>{{quote}}</p>
</div>
<hr/>`;
$(document).ready(function(){
var $mainContentDiv = $(".list")
var $mainList = $(".b");
$mainList.each(function(){
var data = {}
var content = $(this).find(".c")
var $content = $(content)
var link = getLink($content)
var category = getCategory($content)
var image = getImage($content)
var paragraphOne = getParagraph($content, 'f')
var paragraphTwo = getParagraph($content, 'g')
var quote = getQuote($content)
data["link"] = link
data["category"] = category
data["image"] = image
data["paragraphOne"] = paragraphOne
data["paragraphTwo"] = paragraphTwo
data["quote"] = quote
var html = Mustache.to_html(row, data);
$('#links-container').append(html);
})
function getQuote($content){
return $content.find(".j").html()
}
function getParagraph($content, className){
return $content.find("." + className).html()
}
function getImage($content){
return $content.find("e").find("img").attr("src")
}
function getCategory($content){
var category = $content.find(".d")
return $(category).html()
}
function getLink($content){
return $content.find("a").attr("href")
}
$mainContentDiv.remove()
})
</script>
Is this something like you wanted to achieve?

Ajax request to the same PHP page gives no errors but doesn't work

I am making a product displaying page of an ecommerce website. The products are to be filtered by brands on the basis of brands that are checked by the customer. For this I have used an ajax request everytime a brand is checked. The problem is that the page cannot receive the get variables that i am sending to the same page. The ajax request is not giving any errors and also the chrome debugger side is also not showing any error at all. This is the page:
snapshot of the products page
And this is the code of the page:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<?php
session_start();
include('includes/pdo_connect.php');
include('includes/pdo_functions.php');
$logged_in;
$user_first_name;
if(isset($_SESSION['user'])){ //Determining if the user is logged in or not.
if($_SESSION['user']=='user'){
$user_id = $_SESSION['user_id'];
global $logged_in;
$logged_in = true;
global $user_first_name;
$user_first_name = $_SESSION['user_first_name'];
}
} else {
$_SESSION['user'] = 'guest';
$user_id = $_SERVER['REMOTE_ADDR'];
}
$cat;
if(isset($_GET['cat'])){
global $cat;
$cat = $_GET['cat'];
}
include('includes/logged_in.php');
if(isset($_GET['brand_list'])){
$brand_list = $_GET['brand_list'];
} else {
echo "<script>alert('value not received');</script>";
}
?>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="styles/list_style.css?<?php echo time(); ?>">
<link rel="stylesheet" type="text/css" href="styles/thickbox.css" media="screen">
<script type="text/javascript" src="js/jquery-3.1.1.js"></script>
<script type="text/javascript" src="js/thickbox.js"></script>
<?php
$where = array();
if(!empty($brand_list)){
echo "ajax working";
if(strpos($brand_list, ',')!==false){
$brand_choices = explode(',', $brand_list);
$barray = array();
foreach($brand_choices as $value) {
$barray[] = "brand_id = $value";
}
$where[] = '('.implode(' OR ', $barray).')';
} else {
$where[] = '(brand_id= '.$brand_list.')';
}
} else {
//echo "ajax not working ";
}
$w = implode(' AND ', $where);
$w = "where product_cat=$cat ".$w;
$filter_query = "select * from products $w ";
echo "filter query: ".$filter_query;
$first_load = 'filter';
function show_filtered(){
//echo "<script>alert('filter query working');</script>";
global $filter_query;
global $con;
global $brand_name;
try{
$stmt = $con->prepare($filter_query);
$stmt->execute();
$result = $stmt->fetchAll();
foreach ($result as $data) {
$product_id = $data['product_id'];
$product_cat = $data['product_cat'];
$product_brand = $data['product_brand'];
$product_title = $data['product_title'];
$product_price = $data['product_price'];
$product_desc = $data['product_desc'];
$product_image = $data['product_image'];
echo "
<div class='product_container $brand_name'>
<a href='details.php?pid=".$product_id."' alt='".$product_title."'>
<div class='img_div'>
<img src='admin/product_images/".$product_image."?".time()."' alt='".$product_title."'/>
</div>
<div class='index_product_desc'>".$product_title."</div>
<div class='index_product_price'>₹".$product_price."</div>
</a>
</div>
";
}
} catch(PDOException $e){
echo "Error in show_list(): ".$e->getMessage();
}
}
function show_brands(){
global $con;
global $cat;
global $brand_name;
try{
$query = "select * from cat_brand where cat_id = $cat";
$stmt = $con->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll();
//$brand = array();
foreach ($result as $data) {
$brand_id = $data['brand_id'];
//echo "<script>alert('$brand_id');</script>";
$query1 = "select * from brands where brand_id = $brand_id";
$stmt1 = $con->prepare($query1);
$stmt1->execute();
$result1 = $stmt1->fetchAll();
echo "<ul>";
foreach ($result1 as $data1) {
$brand_name = $data1['brand_title'];
echo "<li><input type='checkbox' value='$brand_id' id='$brand_name' class='brand_check' name='brandchoice'> $brand_name</li>";
}
echo "</ul>";
}
} catch(PDOException $e){
echo "Error in show_brands: ".$e->getMessage();
}
}
function show_price(){
}
?>
</head>
<body>
<div class="wrapper">
<header>
<div class="home_logo">
<a href="index.php">
<img src="images/skyshop_sumopaint.png" alt="Site Home">
</a>
</div>
<div class="login">
<?php user();?> |
<?php login_status(); ?>
</div>
<div class="form">
<form method="get" target="" name="searchbar_form">
<input type="text" name="searchbar" id="searchbar">
<input type="submit" id="search_button" value="Search">
</form>
</div>
</header>
<div class="menubar">
<div class="dropdown">
<button onclick="dropdownToggle()" class="dropdown-button">Shop By Category</button>
<ul class="dropdown-content" id="dropdownContent">
Categories
<?php getcats(); ?>
</ul>
</div>
<div class="menubar-div">
<ul class="menu-items">
<?php getcats(); ?>
</ul>
</div>
<div class="cart">
Cart (0)
</div>
</div>
<div class="content">
<div class="nav">
</div>
<div class="list_wrapper">
<!--/////////////////////////////////////////////// Filter div /////////////////////////////////////////////////////-->
<div class="filter">
<span class="filter_heading">Select Brands</span>
<a href="" class="clear" id="clear_brands">Clear<a>
<div class="brand_div">
<?php
show_brands();
?>
</div>
<div class="price_div">
</div>
</div>
<!--/////////////////////////////////////////////// List div ///////////////////////////////////////////////////////-->
<div class="list">
<div class="loading">
<img src="images/loadingAnimation.gif">
</div>
<?php
show_filtered();
?>
</div>
</div>
<div class="footer">
FOOTER
</div>
</div>
</div>
<?php
?>
<script type="text/javascript">
$(window).on('load', function(){
function filter(){
//alert("filter called");
$('.filter .list').css('opacity', 0.5);
$('.loading').css('visibility', 'visible');
var brandchoice = new Array();
$('input[name="brandchoice"]:checked').each(function(){
brandchoice.push($(this).val());
$('#clear_brands').css('visibility', 'visible');
});
if(brandchoice==""){
$('#clear_brands').css('visibility', 'hidden');
}
var brand_list = '&brand_list='+brandchoice;
var data = brand_list.substring(1, brand_list.length);
//alert(data);
$.ajax({
url: "list.php",
type: "GET",
data: data,
cache: false,
success: function(result){
$(".filter .list").css("opacity", 1);
$(".loading").css("visibility", "hidden");
},
error: function(jqxhr, exception){
console.log(jqxhr);
},
beforeSend: function(){
console.log("before send: "+data); //This is showing "brand_list=1" which is correct.
}
});
}
$('input[type="checkbox"]').on('change', filter);
$('#clear_brands').on('click', function(){
$('.brand_check').removeAttr('checked');
filter();
$('#clear_brands').css('visibility', 'hidden');
});
}); //end of jquery
</script>
</body>
</html>
I am using alert() in the beforeSend in the ajax request and it returns the correct data as expected. But the PHP section of the page does not received the values. There are no errors on the PHP side or the browser debug window.
I checked your code line by line. and figure out that you have code for ajax inside the function named "filter" function filter().
Now you are calling this filter function on by onclick event of the element with id clear_brands
$('#clear_brands').on('click', function(){
$('.brand_check').removeAttr('checked');
filter();
$('#clear_brands').css('visibility', 'hidden');
});
and by this code i came to know that at the end your ajax call is not being made because you click event was not triggered,
So either you should trigger this event on your document get ready or you have to do it by clicking on that element.
Just think about the flow once.
i was testing your script in my local and
with some modification i have made it working.
did some changes like
at the end of the script i just putted this code below.
$(document).ready(function(){
$('#clear_brands').trigger("click");
});
And ajax call was executed..
check out my entire HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<a href="" class="clear" id="clear_brands">Clear<a>
<script type="text/javascript">
$(window).on('load', function(){
function filter(){
//alert("filter called");
$('.filter .list').css('opacity', 0.5);
$('.loading').css('visibility', 'visible');
var brandchoice = new Array();
$('input[name="brandchoice"]:checked').each(function(){
brandchoice.push($(this).val());
$('#clear_brands').css('visibility', 'visible');
});
if(brandchoice==""){
$('#clear_brands').css('visibility', 'hidden');
}
var brand_list = '&brand_list='+brandchoice;
var data = brand_list.substring(1, brand_list.length);
//alert(data);
$.ajax({
url: "list.php",
type: "GET",
data: data,
cache: false,
success: function(result){
$(".filter .list").css("opacity", 1);
$(".loading").css("visibility", "hidden");
},
error: function(jqxhr, exception){
console.log(jqxhr);
},
beforeSend: function(){
console.log("before send: "+data); //This is showing "brand_list=1" which is correct.
}
});
}
$('input[type="checkbox"]').on('change', filter);
$('#clear_brands').on('click', function(){
$('.brand_check').removeAttr('checked');
filter();
$('#clear_brands').css('visibility', 'hidden');
});
}); //end of jquery
$(document).ready(function(){
$('#clear_brands').trigger("click");
});
</script>
</body>
</html>
In Chrome do Ctrl+Shift+I to open Developer Tools and check Console for errors and Network tab to see if the data is passed in request.

PHP and HTML commenting system

I'm trying to build a comment system
this is my code
<html>
<head>
<link rel="stylesheet" type="text/css" href="css.css">
<style>
.back_glob{width: 350px}
</style>
<script type="text/javascript" src="jquery-3.1.0.min.js"></script>
<script type="text/javascript">
$(function(){
$( ".tombol_login" ).click(function() {
var txt = $("[name=comment]").val();
$("#comment").submit();
})});
</script>
<style>
.back_glob{width: 450px}
</style>
</head>
<body>
<div class = "back_glob">
<div class="tableC">
<img src="img\back.png" alt="back" height="42" width="42">
<div class ="back_header">
<h4>comment</h4>
</div>
<div class= "table">
<form id="comment" name="comment" action="contet2.php" method="post">
<div class="row">
<div class="col">comment</div>
<div class="col">:</div>
<div class="col"><textarea name="comment" rows ="10" cols="40"></textarea></div>
</div>
<div class="tom">
<button type="button" class="tombol_login">Submit</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
<?php
$servername = "localhost";
$dbname = "databaseform";
$username = "root";
$password = "";
session_start();
$page = 2;
$conn = new PDO("mysql:host =$servername ; dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT form.Username, comment.Comment, comment.time FROM
form, comment WHERE
form.pkey=comment.pkey AND
comment.page=$page
ORDER BY comment.time DESC";
$result = $conn->query($query);
$hasil = $result->fetchAll();
$Comment = $_POST['comment'];
try
{
// injec
$query = "INSERT INTO comment (pkey,Comment,time,page)
VALUES (:Username,:Comment,NOW(),:page)";
$sql = $conn->prepare($query) ;
$sql->BindValue(':Username',reset($_SESSION['txt_login']));
$sql->BindValue(':Comment',$Comment);
$sql->BindValue(':page',$page);
$sql->execute();
$query = "SELECT form.Username, comment.Comment, comment.time FROM
form, comment WHERE
form.pkey=comment.pkey AND
comment.page=$page
ORDER BY comment.time DESC";
$result = $conn->query($query);
$hasil = $result->fetchAll();
echo '<div class="back_glob">';
echo '<div class = "table">';
echo '<div class = "tableC">';
echo '</div>';
}
catch(PDOException $e)
{
echo $query . "<br>" . $e->getMessage();
}
for($i = 0 ; $i < count($hasil);$i++)
{
echo'<div class="row">';
echo '<div class="col2">'.$result[$i]['Username'].'</div>';
echo '<div class="col2">'.$result[$i]['Comment'].'</div>';
echo '<div class="col2">'.$result[$i]['time'].'</div>';
echo'</div>';
}
?>
but the php part won't recognize the $_POST['comment'] before the submit button , i can't show the previous comment unless I click the submit button.
Is there any solution to correct this ??
I am really confused about your way of asking a question. I think you should have to read this tutorial of Smashing Magazine. So you can better understand of code and comment system.
I hope it will help you.

Ajax does not display the result from mysql database

I have an issue with my ajax request and I can't figure out what is wrong, in console there is no error...
Here is my javascript file:
$(document).ready(function(){
done();
});
function done(){
setTimeout(function(){
updates();
done();
}, 50000);
}
function updates() {
$.getJSON("sedinte.php", function(data){
$("#results").empty();
$(".pagination").empty();
$.each(data.result, function() {$("#results").append("<tr class='"+this['aclass']+"'><td>"+this['object']+"</td><td>"+this['date']+"</td><td>"+this['amount']+"</td><td>"+this['paid']+"</td></tr>");
});
$.each(data.pagination, function() {
$("ul.pagination").append(this['controls']);
});
});
}
$("#btnAdd").click(function(){
$.post(
$("#addForm").attr("action"), $("#addForm :input").serializeArray(), function(info) {
$("#feedback").html(info);
});
clearInput();
});
$("#addForm").submit(function(){
return false;
});
function clearInput() {
$("#addForm :input").each( function() {
$(this).val(' ');
});
}
Here is my file I want to request:
<?php
#Get the total number of rows
$rows = $db->getTotalRows("sedinte");
#Set number of result to show on each page
$page_rows = 10;
#Get the last page
$last = ceil($rows/$page_rows);
#Make sure the last page is not below 1
if($last <1)
{
$last = 1;
}
$pagenum = 1; #Default page
#Get page number from URL vars if it is pressent, else it is = 1
if(isset($_GET['page']))
{
$pagenum = preg_replace('#[^0-9]#', '', $_GET['page']);
}
#Make sure the page number isn't below 1, or more than our last page
if($pagenum < 1)
{
$pagenum = 1;
}
else if($pagenum > $last)
{
$pagenum = $last;
}
#This sets the range of rows to query for the chosen page number
$limit = 'LIMIT ' .($pagenum - 1) * $page_rows . ',' .$page_rows;
#This is for grabbing just one page worth of rows by applying limit
$sql = "SELECT * FROM sedinte ORDER BY id DESC $limit";
$query = mysqli_query($db->Conn(), $sql);
#Enstablish the pagination controls variable
$paginationCtrls = null;
#<li>2 <span class="sr-only">(current)</span></li>
#If there is more than 1 page worth of results
if($last != 1)
{
if($pagenum > 1)
{
$previous = $pagenum - 1;
$paginationCtrls .= '<li>«</li>';
#Render clickable number links that should appear on the left of the target page number
for($i = $pagenum - 4; $i < $pagenum; $i++)
{
if($i > 0)
{
$paginationCtrls .= '<li>'.$i.'</li>';
}
}
}
#Render the current page
$paginationCtrls .= '<li class="active">'.$pagenum.'<span class="sr-only">(current)</span></li>';
#Render clickable number lnks that should appear on the right of the target page number
for($i = $pagenum+1; $i <= $last; $i++)
{
$paginationCtrls .= '<li>'.$i.'</li>';
if($i >= $pagenum+4)
{
break;
}
}
if($pagenum != $last)
{
$next = $pagenum + 1;
$paginationCtrls .= '<li>»</li>';
}
}
$paginationArray = array();
array_push($paginationArray, array('controls' => $paginationCtrls));
$listTest = null;
$resultArray = array();
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC))
{
//$id = $row['id'];
$obiect = $row['obiect'];
$data = $row['data'];
$suma = $row['suma'];
$achitat = $row['achitat'];
if($achitat == 'Da')
{
$active_class= null;
}
else
{
$active_class= "danger";
}
array_push($resultArray, array('object' => $obiect,
'date' => $data,
'amount' => $suma,
'paid' => $achitat,
'aclass' => $active_class
));
/*
$listTest .=' <tr class="'.$active_class.'">
<td>'.$obiect.'</td>
<td>'.$data.'</td>
<td>'.$suma.'</td>
<td>'.$achitat.'</td>
</tr>';*/
}
echo json_encode(array("result" => $resultArray, "pagination" => $paginationArray));
mysqli_close($db->Conn());
?>
And here is my index file:
<?php
require 'includes/settings.php';
?>
<!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">
<title>Sedinte</title>
<!-- Bootstrap -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css">
<!-- Latest compiled and minified JavaScript -->
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-xs-12 col-md-12">
<div role="tabpanel">
<!-- Nav tabs -->
<ul class="nav nav-tabs" role="tablist">
<li role="presentation" class="active"><span class="glyphicon glyphicon-eye-open"></span> Vezi Sedinte</li>
<li role="presentation"><span class="glyphicon glyphicon-plus-sign"></span> Adauga Sedinta</li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div role="tabpanel" class="tab-pane active" id="sedinte">
<div class="row">
<div class="col-xs-6 col-md-4">
<h4><span class="glyphicon glyphicon-usd"></span> Buget: 460 RON</h4>
</div>
<div class="col-xs-6 col-md-4 col-md-offset-4">
<h4><span class="glyphicon glyphicon-calendar"></span> Data: <?php echo date('D d M Y');?></h4>
</div>
</div>
<table class="table table-striped table-hover">
<thead>
<tr>
<th><span class="glyphicon glyphicon-edit"></span> Obiect</th>
<th><span class="glyphicon glyphicon-calendar"></span> Data</th>
<th><span class="glyphicon glyphicon-usd"></span> Suma</th>
<th><span class="glyphicon glyphicon-ok"></span> Achitat</th>
</tr>
</thead>
<tbody id="results">
<?php //echo $listTest;?>
</tbody>
</table>
<ul class="pagination">
<?php //echo $paginationCtrls;?>
</ul>
</div>
<div role="tabpanel" class="tab-pane" id="adauga">
<div class="row">
<div class="col-md-6 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-body">
<form action="add.php" method="post" id="addForm">
<div class="form-group">
<label for="obiect">Obiect</label>
<input type="text" class="form-control" name="boxObiect" placeholder="M, L, R">
<!--
<select name="boxObiect" class="form-control">
<option>Matematica</option>
<option>Romana</option>
<option>Logica</option>
</select>
-->
</div>
<div class="form-group">
<label for="data">Data: </label>
<input type="text" class="form-control" name="boxData" placeholder="YYYY-MM-DD">
</div>
<div class="form-group">
<label for="radioAchitat">Achitat: </label>
<label class="radio-inline">
<input type="radio" name="radioAchitat" id="radioAchitat" value="Da"> Da
</label>
<label class="radio-inline">
<input type="radio" name="radioAchitat" id="radioAchitat" value="Nu" checked="checked"> Nu
</label>
</div>
<button type="submit" id="btnAdd" class="btn btn-primary">Adauga</button>
</form>
</div>
</div>
<div id="feedback"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script src="ajax/main.js"></script>
</body>
</html>
My data from the database is not showing... just the main template.
Please help me!
I Don't kow what's the problem because i did not read the full code, but that is a bug that i found so you can correct that and can try again :), i hope it will work, Thanks
header('Content-type: application/json');
echo json_encode(array("result" => $resultArray, "pagination" => $paginationArray));
mysqli_close($db->Conn());

Render new data of modal inside modal PHP, jQuery

I have a MySQL database of a bible that I query via php. Right now i'm in the testing phase. Below is my test file where I display a specific Chapter of a Book in a modal. The problem is that I have no idea how to essentially 'display the next chapter (or previous chapter)' when a user clicks the left or right arrow buttons on the footer of the modal.
Currently the test file shows "Genesis 12". How can I allow the user to see Genesis 13 (inside the same modal) when the user clicks the right arrow button (at the bottom)?
<!DOCTYPE html>
<html>
<head>
<?php require "config.php"; ?>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link rel='stylesheet' type='text/css' href='http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.1.0/css/font-awesome.min.css'/>
<script>
$(document).ready(function() {
$('.btn').click(function() {
$("#myModal").modal('show');
});
});
</script>
<style>
p, span, div { font-family:"Helvetica Neue",Verdana,Helvetica,Arial,sans-serif;font-size:1.3rem;line-height:1.8;}
.selverse { border-bottom:1px dotted blue;}
</style>
</head>
<body>
<button type='button' class='btn btn-success'>Click</button>
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<?php
$book = "Genesis";
$chapter = "12";
$verse = "5";
$v_under = "<span style='text-decoration:underline;'>";
$v_end = "</span>";
echo "<h4 class='modal-title'>".$book." ".$chapter."</h4>";
echo "</div><div class='modal-body'>";
$result = $db->prepare("SELECT * FROM `asv` WHERE Book = :book AND Chapter = :chapter");
$result->BindParam(':book',$book);
$result->BindParam(':chapter',$chapter);
$result->execute();
$y = 0;
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$bookx = $row['Book'];
$chapterx = $row['Chapter'];
$versex = $row['Verse'];
$versetext=$row["VerseText"];
if ($versex == $verse) {
echo "<span style='color:rgb(57, 128, 57);font-weight:bold;'><sup style='padding-left:0.5em;'>".$versex."</sup></span><span class='selverse' id='v".$versex."'>".$versetext."</span>";
} else {
echo "<span style='color:rgb(57, 128, 57);font-weight:bold;'><sup style='padding-left:0.5em;'>".$versex."</sup></span><span id='v".$versex."'>".$versetext."</span>";
}
}
?>
</div>
<div class="modal-footer" style='text-align:center;'>
<a href='javascript:;'><i style='float:left;margin-left:1em;' class='fa fa-angle-left fa-2x'></i></a>
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
<a href='javascript:;'><i style='float:right;margin-right:1em;' class='fa fa-angle-right fa-2x'></i></a>
</div>
</div>
</div>
</div>
</body>
</html>
.. Any help will be greatly appreciated!!
You should look into AJAX to do something like that properly, what AJAX basically does is load content after the page has finished loading. So you can get rows out of your database without reloading the page. A very basic approach would be:
Change the href of the arrows to call the JavaScript function loadNew();
<div class="modal-footer" style='text-align:center;'>
<a href='javascript:loadNew('previous');'><i style='float:left;margin-left:1em;' class='fa fa-angle-left fa-2x'></i></a>
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
<a href='javascript:loadNew('next');'><i style='float:right;margin-right:1em;' class='fa fa-angle-right fa-2x'></i></a>
</div>
Add the loadNew function to your script tag:
<script>
$(document).ready(function() {
$('.btn').click(function() {
$("#myModal").modal('show');
});
});
function loadNew(type){
//We pass the type (previous or next row) and the current ID of the row as GET variables to the fetch.php script
$.get("http://yoursiteurl.com/fetch.php?type="+type, function(data){
$(".modal-header").html(data);
});
}
</script>
Now all that's left is to create the PHP file (fetch.php), that would be something like:
<?php
session_start();
if(!isset($_SESSION['book'])){
$_SESSION['book'] = "Genesis";
$_SESSION['chapter'] = 12;
$_SESSION['verse'] = 5;
}
if($_GET['type'] == 'next'){
//Select the next verse, you are probably going to want to add a check to see if the chapter is available, if not go to the first chapter or something like that
$_SESSION['chapter'] = $_SESSION['chapter'] + 1;
} else{
$_SESSION['chapter'] = $_SESSION['chapter'] - 1;
}
$book = $_SESSION['book'];
$chapter = $_SESSION['chapter'];
$verse = $_SESSION['verse'];
$v_under = "<span style='text-decoration:underline;'>";
$v_end = "</span>";
echo "<h4 class='modal-title'>".$book." ".$chapter."</h4>";
echo "</div><div class='modal-body'>";
$result = $db->prepare("SELECT * FROM `asv` WHERE Book = :book AND Chapter = :chapter");
$result->BindParam(':book',$book);
$result->BindParam(':chapter',$chapter);
$result->execute();
$y = 0;
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$bookx = $row['Book'];
$chapterx = $row['Chapter'];
$versex = $row['Verse'];
$versetext=$row["VerseText"];
if ($versex == $verse) {
echo "<span style='color:rgb(57, 128, 57);font-weight:bold;'><sup style='padding-left:0.5em;'>".$versex."</sup></span><span class='selverse' id='v".$versex."'>".$versetext."</span>";
} else {
echo "<span style='color:rgb(57, 128, 57);font-weight:bold;'><sup style='padding-left:0.5em;'>".$versex."</sup></span><span id='v".$versex."'>".$versetext."</span>";
}
}
?>
Then save the file and edit the path http://yoursiteurl.com/fetch.php to the correct one.

Categories