Pagination jTable in PHP - javascript

How to use paging in jTable use PHP?
I have code below in employeeTable.php
<script src="jtable.2.4.0/jquery.jtable.min.js" type="text/javascript"></script>
//Get record count
$result = mysql_query("SELECT COUNT(*) AS RecordCount FROM employee;");
$row = mysql_fetch_array($result);
$recordCount = $row['RecordCount'];
//Get records from database
$result = mysql_query("SELECT * FROM employee ORDER BY '" . $_REQUEST["jtSorting"] . "' LIMIT '" . $_REQUEST["jtStartIndex"] . "','" . $_REQUEST["jtPageSize"] . "';");
//Add all records to an array
$rows = array();
while($row = mysql_fetch_array($result))
{
$rows[] = $row;
}
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['TotalRecordCount'] = $recordCount;
$jTableResult['Records'] = $rows;
print json_encode($jTableResult);
Then I realize the problem is in here
$result = mysql_query("SELECT * FROM employee ORDER BY '" . $_REQUEST["jtSorting"] . "' LIMIT '" . $_REQUEST["jtStartIndex"] . "','" . $_REQUEST["jtPageSize"] . "';");
if I change $_REQUEST["jtSorting"] = rowname, $_REQUEST["jtStartIndex"] = number, $_REQUEST["jtPageSize"] = number, it works.
But if I don't change it, it shows 'An Error Occured While Communicating to the server'.
here is the code in jquery.jtable.min.js, when there are line about jtSorting, jtStartIndex, jtPageSize
/* Adds jtSorting parameter to a URL as query string.
*************************************************************************/
_addSortingInfoToUrl: function (url) {
if (!this.options.sorting || this._lastSorting.length == 0) {
return url;
}
var sorting = [];
$.each(this._lastSorting, function (idx, value) {
sorting.push(value.fieldName + ' ' + value.sortOrder);
});
return (url + (url.indexOf('?') < 0 ? '?' : '&') + 'jtSorting=' + sorting.join(","));
},
/* Overrides _createJtParamsForLoading method to add sorging parameters to jtParams object.
*************************************************************************/
_createJtParamsForLoading: function () {
var jtParams = base._createJtParamsForLoading.apply(this, arguments);
if (this.options.sorting && this._lastSorting.length) {
var sorting = [];
$.each(this._lastSorting, function (idx, value) {
sorting.push(value.fieldName + ' ' + value.sortOrder);
});
jtParams.jtSorting = sorting.join(",");
}
return jtParams;
}
});
})(jQuery);
Can anybody please help me understand?

I think you should go through this once.
Listaction jtable for Pagination and sorting table
It would require jQuery.Deferred to return data.
Handle it as
listAction: function (postData, jtParams) {
return $.Deferred(function ($dfd) {
$.ajax({
url: '/Employee_Controller/EmployeeList_method?jtStartIndex=' + jtParams.jtStartIndex + '&jtPageSize=' + jtParams.jtPageSize + '&jtSorting=' + jtParams.jtSorting,
type: 'POST',
dataType: 'json',
data: postData,
success: function (data) {
$dfd.resolve(data);
},
error: function () {
$dfd.reject();
}
});
});
}
Manually post values for it. I hope this maybe helpful.

the options will be received in $_GET object
like:
$jtStartIndex=$_GET['jtStartIndex'];
$jtPageSize=$_GET['jtPageSize'];
$jtSorting=$_GET['jtSorting'];
example:
$query="select * FROM products ORDER BY $jtSorting LIMIT $jtStartIndex, $jtPageSize;";
and in jtable settings:
paging: true, //Enable paging
pageSize: 10, //Set page size (default: 10)
sorting: true, //Enable sorting
defaultSorting: 'name ASC' ,
actions: {
listAction: 'data/products.php'//Set default sorting
},
...

Related

How to add data from database into object in php for temporary using while loading

I am new in php . I have the following code to retrieve categorytype data from database?. I want to add them into php object for temporary using while loading page. First, I want to load all predefined data, then i will use it when i click function. Could you enlighten me how to create it
categoryDao.php
namespace category;
use Exception;
use PDO;
class categoryDao{
public function categorytype(PDO $connection){
$conn = $connection;
try {
$conn = $connection;
$sql="SELECT * FROM `tb_category` WHERE id != parent_id;";
$categorytype = $conn->prepare($sql);
$categorytype->execute();
$data1 = array();
while (
$result = $categorytype->fetch(PDO::FETCH_ASSOC)) {
$data1[] = $result['id'];
$data1[] = $result['c_name'];
}
return $data1;
} catch (Exception $e) {
echo $e;
throw $e;
}
}
}
categoryservice.php
use category\categoryDao;
require '../dao/categoryDao.php';
require 'Dao.php';
class categoryService{
public function categorytype(){
$dao = new Dao();
$conn= $dao->connect();
$conn->beginTransaction();
$categoryDao = new categoryDao();
//$data1 = array();
$data1=$categoryDao->categorytype($conn);
return $data1;
$dao->disconnect($conn);
}
}
categorytypecontroller.php
<?php
require '../service/categoryService.php';
require '../service/categoryService.php';
$categoryname = #trim(stripslashes($_POST['category']));
$category = new categoryService();
//$ctype = array();
$ctype = $category->categorytype();
$return["json"] = json_encode($ctype);
echo $return["json"];
Head.php
function categorytype() {
//var hosname =window.location.protocol + "//" + window.location.hostname + window.location.pathname;
var hosname1 = window.location.protocol + "//" + window.location.hostname+ "/servicegateway/sgw/modules/controller/categorytypecontroller.php";
alert (hosname1);
//var ur = hosname + "/modules/controller/categorycontroller.php";
$.ajax({
url:hosname1 , //the page containing php script
type: "POST", //request type,
dataType: 'json',
data: '',
success:function(data1){
alert(data1);
var obj =data1;
// var leng = Object.keys(obj).length;
var areaOption = "<option value=''>Select Category </option>";
for (var i = 0; i < obj.length; i++) {
areaOption += '<option value="' + obj[i] + '">' + obj[i] + '</option>'
}
$("#c_type").html(areaOption);
}
});
}
A couple of things. If you want the data to be an array of records, you'll probably want to change this part:
while ($result = $categorytype->fetch(PDO::FETCH_ASSOC)) {
$data1[] = $result['id'];
$data1[] = $result['c_name'];
}
as that is putting all the fields, one after the other, into a normal array.
while ($result = $categorytype->fetch(PDO::FETCH_ASSOC)) {
$data1[] = array(
'id' => $result['id'],
'c_name' => $result['c_name']
);
}
That will create a small associative array of the id and name fields and put it into another array, with the other records. PHP associative arrays will turn into Javascript objects when sent via ajax.
Then, in Javascript, you'll want to make use of those objects to create your options, so:
areaOption += '<option value="' + obj[i].id + '">' + obj[i].c_name + '</option>'

Posting data without refresh + calling another jquery function

My code, basically, on a click of a button, runs an ajax function in order to write stuff to my database.
What I want to do next is call another function which will fetch data from the database and print it.
Here is my code below, but the second function does not show that it works. I don't know where I went wrong.
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function loaddata() {
$.ajax({
type: "POST",
url: "includes/fetchupdatedimages.php",
data: $("#editad_form").serialize(),
success: function (response) {
alert(response);
}
});
});
</script>
Second function:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$("#deleteimgs").click(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "includes/deleteimages.php",
data: $("#editad_form").serialize()
});
$("input[type=checkbox]:checked").parent().remove();
loaddata();
});
});
</script>
fetchupdatedimages.php
<?php
include_once "functions.php";
ini_set("display_errors", 1);
ini_set("display_startup_errors", 1);
error_reporting(-1);
error_reporting(E_ALL);
$id = $_POST["id"];
if ($stmt = $mysqli->prepare("SELECT images FROM db WHERE id = ? LIMIT 1")) {
$stmt->bind_param("s", $id);
$stmt->execute();
$stmt->store_result();
// get variables from result.
$stmt->bind_result($images);
$stmt->fetch();
}
echo "<p>" . $images . "</p>";
?>
It seems that loaddata() does not get called or it does not return any data to me back. Any help?
Have you tried sending the data from your PHP file using JSON over to your jQuery code instead?
For example:
PHP
<?php
header("Content-Type: application/json");
include 'connect.php';
$sql = "SELECT * FROM reviews, customers WHERE review_user = customer_id";
$datas = "";
$x = 0;
$result = $con->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$datas[$x] = array("fname" => $row["customer_name"], "lname" => $row["customer_surname"], "email" => $row["customer_email"], "gender" => $row["customer_gender"], "title" => $row["review_title"], "content" => $row["review_content"], "rating" => $row["review_rating"]);
$x++;
}
}
$con->close();
echo json_encode($datas);
?>
jQuery
$(document).ready(function() {
$.getJSON('controls/getReviews.php', function(jsondata) {
console.log("Returned data: " + jsondata);
if (jsondata !== "") {
for (var i = 0; i < jsondata.length; i++) {
var data = jsondata[i];
var fname = data["fname"];
var lname = data["lname"];
var email = data["email"];
var gender = data["gender"];
var title = data["title"];
var msg = data["content"];
var rating = data["rating"];
$('.reviews').append('<div class="panel panel-default"><div class="panel-heading"><h3 class="panel-title">' + title + '</h3></div><div class="panel-body"><table class="table table-striped"><tr><td>Name:</td><td>' + fname + ' ' + lname + '</td></tr><tr><td>Gender:</td><td>' + gender + '</td></tr><tr><td>Rating:</td><td>' + rating + '/5</td></tr><tr><td>Message:</td><td>' + msg + '</td></tr></table></div></div>');
}
}
});
});

Simple JSON code doesn't work

This code tries to populate a dropdown list in a form with values. I have tested the PHP separately and the query is ok (small wonder !). I have a similar form whith 3 connected dropdown lists and they work flawlessly. Debugging this in Mozilla, I notice that the success function of JSON is not executed. I cannot understand why.
JavaScript
$(document).ready(function()
{
$.getJSON("/scripts/033A_GetJudet.php", success = function(data)
{
var str_options = "";
for (var i=0; i < data.length; i++)
{
str_options += "<option value='" + data[i] + "'>" + data[i] + "</option>";
}
$("#selJudet").append(str_options);
// var selOption = document.getElementById("selJudet");
// selOption.selectedIndex = localStorage.getItem("selJudIndex") || 0;
// document.getElementById("selJudet").selectedIndex = selOption.selectedIndex;
$("#selJudet").change();
});
$("#selJudet").change(function()
{
var selText = document.getElementById("selText");
// selText.value = selText.defaultValue;
selText.value = "Abcgcfkjsdhfsjkdh";
// $("#selText").change();
});
});
PHP (I skipped the database connection code)
$query = '(SELECT 1 AS sc, nume_judet FROM sa_Judet ';
$query .= 'WHERE nume_judet <> "N/A" ) UNION ';
$query .= '(SELECT 2 AS sc, "N/A" FROM sa_Judet) ';
$query .= 'ORDER BY sc, nume_judet';
//print $query;
$result = mysqli_query($db_conn, $query);
$judet = array();
if ($result == FALSE)
{
array_push($judet, 'QUERY_ERROR');
goto _adr1;
}
$rows = mysqli_num_rows($result);
if ($rows == 0)
{
array_push($judet, 'TBD_');
goto _adr1;
}
while ($row = mysqli_fetch_array($result))
{
array_push($judet, $row['nume_judet']);
}
_adr1:
print json_encode($judet);
mysqli_free_result($result);
mysqli_close($db_conn);
?>
Ajax variant of my original Javascript
$(document).ready(function()
{
$.ajax({
url: "/scripts/033A_GetJudet.php",
dataType: 'json',
success: function(data)
{console.log('SUCCESS: ', data);},
error: function(data)
{console.log('ERROR: ', data);}
var str_options = "";
for (var i=0; i < data.length; i++)
{
str_options += "<option value='" + data[i] + "'>" + data[i] + "</option>";
}
$("#selJudet").append(str_options);
var selOption = document.getElementById("selJudet");
selOption.selectedIndex = localStorage.getItem("selJudIndex") || 0;
document.getElementById("selJudet").selectedIndex = selOption.selectedIndex;
$("#selJudet").change();
});
$("#selJudet").change(function()
{
var selText = document.getElementById("selText");
selText.value = selText.defaultValue;
// $("#selText").change();
});
});
It is possibly an error in parsing the data received. HTTP 304 is the same as HTTP 200, only the contents is pulled from cache, not serverside.
$.ajax({
url: url,
data: data,
success: function(response, textStatus, jsqxhr) {
var obj; try { obj = eval(response); } catch(e) { console.error(e); }
// -- do something with obj --
},
fail: function(jqxhr, textStatus, error) {
console.log( "error", textStatus, error);
}
});
Use this function instead and look closer at the data. If data is returned through success, we try to evaluate the json string into an object. Should it fail, an exception is thrown (possibly SyntaxError) and log should show this.
Replace this line
$.getJSON("/scripts/033A_GetJudet.php", success = function(data)
with this one
$.getJSON("/scripts/033A_GetJudet.php", function(data)

How can I add php variables to this Javascript?

I'm trying to build a simple news page with ajax filters depending on what category the user wants to see. The javascript below connects to a php file and outputs HTML with data from the mysql database. I need to know how to tell the JS to put the data from the "heading" column into a php variable so that it wraps it in the correct href link.
This is the php that creates the heading and the link
$data_fields = '`id`, `heading`, `date`, `copy`, `summary`, `article`, `press_release`, `video`';
$from = '`media`';
$news_result = $db->selectByStrings($data_fields, $from, $where_conditions, $order_by);
$news = $db->getAllRows($news_result);
foreach ($news as $new) {
echo '<h2 class="news"><a class="news" href="'.$base_href.$new['id'].'">'.$new['heading'].'</a></h2>';
}
I somehow need to include this is the separate JS file, making sure it is only applied to data from the heading column.
Javascript
function makeTable(data) {
var tbl_body = "";
$.each(data, function () {
var tbl_row = "";
$.each(this, function (k, v) {
tbl_row += "<div class='row'><div class='col-md-8 col-md-offset-2'>" + v + " </div></div>";
});
tbl_body += "<div class='non-white'>" + tbl_row + "</div>";
});
return tbl_body;
}
function getEmployeeFilterOptions() {
var opts = [];
$checkboxes.each(function () {
if (this.checked) {
opts.push(this.name);
}
});
return opts;
}
function updateEmployees(opts) {
$.ajax({
type: "POST",
url: "filter3.php",
dataType: 'json',
cache: false,
data: {filterOpts: opts},
success: function (records) {
$('#employees div').html(makeTable(records));
}
});
}
var $checkboxes = $("input:checkbox");
$checkboxes.on("change", function () {
var opts = getEmployeeFilterOptions();
updateEmployees(opts);
});
updateEmployees();
The php file the above connects to:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=xxx', 'xxx', 'xxx');
$select = 'SELECT heading, summary, created_date';
$from = ' FROM media';
$where = ' WHERE TRUE';
$opts = isset($_POST['filterOpts']) ? $_POST['filterOpts'] : array('');
if (in_array("article", $opts)) {
$where .= " AND article = 1";
}
if (in_array("press_release", $opts)) {
$where .= " AND press_release = 1";
}
if (in_array("video", $opts)) {
$where .= " AND video = 1";
}
$sql = $select.$from.$where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
?>
I think you are looking for something like this :
var base_href = 'http://www.stackoverflow.com/';
function makeTable(data) {
var tbl_body = "";
$.each(data, function (index, row) {
var tbl_row = "";
$.each(row, function (k, v) {
if(k == 'heading' && 'id' in row) {
v = '<a class="news" href="' + base_href + row.id +'">' + v + '</a>';
}
tbl_row += "<div class='row'><div class='col-md-8 col-md-offset-2'>"
+ v + " </div></div>";
});
tbl_body += "<div class='non-white'>" + tbl_row + "</div>";
});
return tbl_body;
}

How to convert data from mysql into jquery array for autocomplete?

Below is snippet of jquery for autocomplete:
var columns = [{
name: 'Color',
minWidth: '100px'},
{
name: 'Hex',
minWidth: '70px'},
{
name: 'Testy',
minWidth: '70px'}],
colors = [['White', '#fff','test1'], ['Black', '#000','test2'], ['Red', '#f00','test3'], ['Green', '#0f0','test4'], ['Blue', '#00f']];
$("#search").mcautocomplete({
showHeader: true,
columns: columns,
source: colors,
select: function(event, ui) {
// Set the input box's value
this.value = (ui.item ? ui.item[1] : '');
// Set the output div's value
$('#outputDiv') && $('#outputDiv').text(ui.item ? ('You have selected ' + ui.item[1]) : 'Select a color');
return false;
}
});
This will output something like this for the autocomplete:
ANd when highlighted item chosen , the second item in the array will be selected in the textbox:
Its because I've set here to choose the second item in the array via this code:ui.item[1]
But I would like to replace the jquery array with value from database:
Say I fetch data from database to be filled in the colors array:
<?php
$sql="SELECT item1,item2,item3 FROM loc_coordinate";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error());
$test=array();
if($result)
{
while($row=mysqli_fetch_array($result))
{
//how do I convert this 3 items into this jquery array(`colors = [['White', '#fff','test1'], ['Black', '#000','test2'], ['Red', '#f00','test3'], ['Green', '#0f0','test4'], ['Blue', '#00f']];`)
echo $row['item1'].">".$row['item2'].>".$row['item3']." \n";
}
}
?>
[1]: http://i.stack.imgur.com/G4JFs.png
[2]: http://i.stack.imgur.com/ys9Ey.png
Assuming all retreived db rows have item1,item2 and item3 values, then this should do it :
...
if($result)
{
echo 'var colors = [';
while($row=mysqli_fetch_array($result))
{
echo '[';
echo '\''.$row['item1'].'\',';
echo '\''.$row['item2'].'\',';
echo '\''.$row['item3'].'\',';
echo '],';
}
echo '];';
}
...
It will output something like :
var colors = [['row_01','row_02','row_03',],['row_01','row_02','row_03',],['row_01','row_02','row_03',],];
where row_0x is the retreived value, make this be outputted inside the <script></script> tags and when generated from server to the client side JavaScript will use it.
A cleaner solution is to use the PHP built in json_encode() function like :
if($result)
{
$output = 'var colors = ';
$all_rows = [] ;
while($row=mysqli_fetch_array($result))
{
$all_rows[]=[$row['item1'],$row['item2'],$row['item3']];
}
$output.= json_encode($all_rows).';';
echo $output;
}
This will output something like :
var colors = [["1","2","3"],["1","2","3"],["1","2","3"],["1","2","3"]];
(thanks #MikeBrant for the comment)
You may also consider a different approach by separating your html and PHP files. The PHP file will output encoded Json results wile the HTML file may use Ajax within jQuery to retrieve them. There is many good tutorials out there. Here is one of them.
This worked for me..I retrieved data from ajax in json format.
<script>
/*
* jQuery UI Multicolumn Autocomplete Widget Plugin 2.2
* Copyright (c) 2012-2015 Mark Harmon
*
* Depends:
* - jQuery UI Autocomplete widget
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
$.widget('custom.mcautocomplete', $.ui.autocomplete, {
_create: function() {
this._super();
this.widget().menu( "option", "items", "> :not(.ui-widget-header)" );
},
_renderMenu: function(ul, items) {
var self = this, thead;
if (this.options.showHeader) {
table=$('<div class="ui-widget-header" style="width:100%"></div>');
// Column headers
$.each(this.options.columns, function(index, item) {
//hide the header
//table.append('<span style="float:left;min-width:' + item.minWidth + ';"> ' + item.name + '</span>');
});
table.append('<div style="clear: both;"></div>');
ul.append(table);
}
// List items
$.each(items, function(index, item) {
self._renderItem(ul, item);
});
},
_renderItem: function(ul, item) {
var t = '',
result = '';
$.each(this.options.columns, function(index, column) {
t += '<span style="float:left;min-width:' + column.minWidth + ';">' + item[column.valueField ? column.valueField : index] + '</span>'
});
result = $('<li></li>')
.data('ui-autocomplete-item', item)
.append('<a class="mcacAnchor">' + t + '<div style="clear: both;"></div></a>')
.appendTo(ul);
return result;
}
});
//ajax starts
$("document").ready(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "GET",
dataType: "json",
url: "store2.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
//$("#showPlace").html("<br />JSON: " + data );
// alert("Form submitted successfully.\nReturned json: " + data["json"]);
// alert(data);
// console.log(data);
var columns = [{
name: 'level',
minWidth: '200px'},
{
name: 'subject',
minWidth: '70px'},
{
name: 'catid',
minWidth: '70px'}
],
colors = data;
var selectThis=$("#search").attr("class");//textbox class determines which item in array to select
var valueV=$("#search").attr("value");
$("#search").mcautocomplete({
showHeader: true,
columns: columns,
source: colors,
select: function(event, ui) {
// Set the input box's value
this.value = (ui.item ? ui.item[selectThis] : '');
//search for nearest value
// Set the output div's value
$('#outputDiv') && $('#outputDiv').text(ui.item ? ('You have selected ' + ui.item[selectThis]) : 'Select a color');
return false;
}
});
}
});
});
</script>

Categories