PHP/Ajax page navigation url change - php

Ik want to build a ajax/jquery page navigation so when the user clicks on a page, the url changes to so that there are no problems with browser's back button. I found a lot of answers for this but not what I searched for. I saw this code below on a tutorial site and I want to customize it so that the url moves to. Do I have to build that in the ajax script of on the PHP side? How can I achieve this?
My index.php
<html>
<head>
<title>Webslesson Tutorial | Make Pagination using Jquery, PHP, Ajax and MySQL</title>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
</head>
<body>
<br /><br />
<div class="container">
<h3 align="center">Make Pagination using Jquery, PHP, Ajax and MySQL</h3><br />
<div class="table-responsive" id="pagination_data">
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
load_data();
function load_data(page)
{
$.ajax({
url:"pagina.php",
method:"POST",
data:{page:page},
success:function(data){
$('#pagination_data').html(data);
history.pushState({ foo: 'bar' }, '', '/bank'); // I tried this line but it don't work
}
})
}
$(document).on('click', '.pagination_link', function(){
var page = $(this).attr("id");
load_data(page);
});
});
</script>
And my pagina.php
<?PHP
$connect = mysqli_connect("hidden", "hidden", "hidden","publiek2") or die("Connection failed: " . mysqli_connect_error());
$record_per_page = 50;
$page = '';
$output = '';
if(isset($_POST["page"]))
{
$page = $_POST["page"];
}
else
{
$page = 1;
}
$start_from = ($page - 1)*$record_per_page;
$query = "SELECT * FROM voertuigen WHERE merk='Chevrolet' AND voorpagina='1' ORDER BY model ASC LIMIT $start_from, $record_per_page";
$result = mysqli_query($connect, $query);
$output .= "
<table class='table table-bordered'>
<tr>
<th width='50%'>Name</th>
<th width='50%'>Phone</th>
</tr>
";
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["merk"].'</td>
<td>'.$row["model"].'</td>
</tr>
';
}
$output .= '</table><br /><div align="center">';
$page_query = "SELECT * FROM voertuigen WHERE merk='Chevrolet' AND voorpagina='1' ORDER BY model ASC";
$page_result = mysqli_query($connect, $page_query);
$total_records = mysqli_num_rows($page_result);
$total_pages = ceil($total_records/$record_per_page);
for($i=1; $i<=$total_pages; $i++)
{
$output .= "<span class='pagination_link' style='cursor:pointer; padding:6px; border:1px solid #ccc;' id='".$i."'>".$i."</span>";
}
$output .= '</div><br /><br />';
echo $output;
?>
Thanks in advance.
I've tried to customize the ajax script.

As a javascript and PHP developer I don't understand much about Jquery but I think the code describes that there is a div called.pagination_link takes id as page number eg: 1. And makes an HTTP POST request to the PHP side. You can simply do this with a sample example in Javascript.
HTML
<div id="1" classname="pagination_link">1</div>
Javascript
const id = document.querySelector('.pagination_link').getAttribute('id');
fetch('pagina.php', {
method : 'POST',
body : id
})
If you want to send data.

I added a hidden text value with the page number as value and called the id 'idd' and recalled that id on the ajax page. It works good now but if I want to go back with browser button, the url moves to the previous page but the results on the page stays te same. How can I resolve that?
My new index.php JS code
<script>
$(document).ready(function(){
var idd;
load_data();
function load_data(page)
{
$.ajax({
url:"pagina.php",
method:"GET",
data:{page:page},
success:function(data){
$('#pagination_data').html(data);
if (idd === undefined) {
alert("ja");
idd = 1;
alert(idd);
history.pushState({}, '', 'http://localhost:4612/pagina/1');
}
else {
idd = $("#idd").val();
history.pushState({}, '', 'http://localhost:4612/pagina/'+idd);
}
}
})
}
$(document).on('click', '.pagination_link', function(){
var page = $(this).attr("id");
load_data(page);
});
});
</script>
and my altered pagina.php
<?PHP
$connect = mysqli_connect("hidden", "hidden", "hidden","publiek2") or die("Connection failed: " . mysqli_connect_error());
$record_per_page = 50;
$page = '';
$output = '';
if(isset($_GET["page"]))
{
$page = $_GET["page"];
echo "<input type='hidden' id='idd' value='".$_GET['page']."'>";
}
else
{
$page = 1;
$idd = 1;
}
$start_from = ($page - 1)*$record_per_page;
$query = "SELECT * FROM voertuigen WHERE merk='Chevrolet' AND voorpagina='1' ORDER BY model ASC LIMIT $start_from, $record_per_page";
$result = mysqli_query($connect, $query);
$output .= "
<table class='table table-bordered'>
<tr>
<th width='50%'>Name</th>
<th width='50%'>Phone</th>
</tr>
";
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["merk"].'</td>
<td>'.$row["model"].'</td>
</tr>
';
}
$output .= '</table><br /><div align="center">';
$page_query = "SELECT * FROM voertuigen WHERE merk='Chevrolet' AND voorpagina='1' ORDER BY model ASC";
$page_result = mysqli_query($connect, $page_query);
$total_records = mysqli_num_rows($page_result);
$total_pages = ceil($total_records/$record_per_page);
for($i=1; $i<=$total_pages; $i++)
{
$output .= "<span class='pagination_link' style='cursor:pointer; padding:6px; border:1px solid #ccc;' id='".$i."'>".$i."</span>";
}
$output .= '</div><br /><br />';
echo $output;
?>

Related

jQuery load() not displaying echo table from php | wordpress

I'm using Wordpress and I want to display a table, which contains pictures and buttons. This table should get loaded with a jquery load() method and put the result into a div.
I get the result, which I want, but it doesn't display in the div. Just here:
here.
When I just put, for example, a H2 with text and without any php into the php file, then it gets displayed.
Script
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
jQuery(document).ready(function(){
var $id = GetURLParameter('id');
var urlGetItem = "getItems.php/?id=" + $id;
jQuery('#load_surveys').load(urlGetItem);
});
</script>
HTML
<div id="load_surveys"></div>
PHP
<?php
include_once 'db.php';
require ('../wp-blog-header.php');
global $wpdb;
global $current_user;
get_currentuserinfo();
$userId = $current_user->ID;
$id = $_GET['id'];
$result = mysqli_query($conn,"SELECT * FROM f5_users JOIN COMPARISONFOLDER ON COMPARISONFOLDER.USER_ID = f5_users.ID JOIN ITEM ON ITEM.COMPARISONFOLDER_ID LIKE COMPARISONFOLDER.COMPARISONFOLDER_ID WHERE COMPARISONFOLDER.COMPARISONFOLDER_ID LIKE $id AND f5_users.ID LIKE $userId");
echo "<table border='1'>
<tr>
<th>Item</th>
<th>Delete</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo '<td><img src="data:image/jpeg;base64,'.base64_encode($row['ITEM']).'" width="500" height="auto"/></td>';
echo "<td><button type='button' onclick='deleteItem(".$row['ITEM_ID'].", $id)'>Testing Script</button></td>";
echo "</tr>";
}
echo "</table>";
?>
What do you get if you make console.log('id',$id) and console.log('url,urlGetItem)
jQuery(document).ready(function(){
var $id = GetURLParameter('id');
console.log('id',$id);
var urlGetItem = "getItems.php/?id=" + $id;
console.log('url,urlGetItem);
jQuery('#load_surveys').load(urlGetItem);
});
PHP
$markup = "<table border='1'>
<tr>
<th>Item</th>
<th>Delete</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
$markup .= "<tr>";
$markup .='<td><img src="data:image/jpeg;base64,'.base64_encode($row['ITEM']).'" width="500" height="auto"/></td>';
e "<td><button type='button' onclick='deleteItem(".$row['ITEM_ID'].", $id)'>Testing Script</button></td>";
$markup .= "</tr>";
}
$markup .= "</table>";
echo $markup;

pagination using PHP ,MYSql and Ajax is not working properly

I have one table fetching data from database and displaying on page using PHP. i have created pagination using Ajax,PHP and MySQL. but when i am clicking on the page numbers, some time it is working and some time the table is displaying records on the first page irrespective of the page i clicked.please help me to solve this issue, i am trying since long time to resolve the issue and i could not. My main page is as follows.....
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Load Data without page refresh</title>
<!--<link rel="stylesheet" href="style/css/bootstrap.min.css">-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<!--<script src="scripts/js/bootstrap.min.js"></script>-->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<!--<script src="scripts/js/jquery.min.js"></script>-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<br /><br />
<div class="container">
<h3 align="center">Pagintation without page refresh</h3>
<div class="table-responsive" id="pagination_data">
</div>
</div>
</body>
</html>
<script>
$(document).ready(function() {
load_data();
function load_data(page) {
$.ajax({
url: "pagination.php",
method: "POST",
data: {
page: page
},
success: function(data) {
$('#pagination_data').html(data);
}
})
}
$(document).on('click', '.pagination_link', function() {
var page = $(this).attr("id");
//alert(page);
load_data(page);
});
});
</script>
pagination.php
<?php
//pagination.php
$connect = mysqli_connect("localhost", "root", "", "testing");
$record_per_page = 5;
$page = '';
$output = '';
if(isset($_POST["page"]))
{
$page = $_POST["page"];
}
else
{
$page = 1;
}
$start_from = ($page - 1)*$record_per_page;
$query = "SELECT * FROM tbl_student ORDER BY student_id DESC LIMIT $start_from, $record_per_page";
$result = mysqli_query($connect, $query);
$output .= "
<table class='table table-bordered'>
<tr>
<th width='50%'>Name</th>
<th width='50%'>Phone</th>
</tr>
";
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["student_name"].'</td>
<td>'.$row["student_phone"].'</td>
</tr>
';
}
$output .= '</table><br /><div align="center">';
$page_query = "SELECT * FROM tbl_student ORDER BY student_id DESC";
$page_result = mysqli_query($connect, $page_query);
$total_records = mysqli_num_rows($page_result);
$total_pages = ceil($total_records/$record_per_page);
for($i=1; $i<=$total_pages; $i++)
{
$output .= "<span class='pagination_link' style='cursor:pointer; padding:6px; border:1px solid #ccc;' id='".$i."'>".$i."</span>";
}
$output .= '</div><br /><br />';
echo $output;
?>

How to load an editable table with AJAX

My site uses AJAX to load menus without having to refresh the page. For future reference, the main php file that contains all the menus is the index.php file. One of these menus has an editable table, which uses AJAX, jQuery and Datatable plugin. All the menus seem to load correctly, but the table doesn't load upon the first click, and then after it does load, it acts wrong; I try to add a single record, but it adds a random number of the record instead (for example, like 16 records). Also, for some reason, the appearance of the table changes; it's normal if the script source (the script being the Datatable script) is a cdn link, however it's messed up a bit if the source is a file (even though the file has the same code, except for the names of buttons and etc shown being in Hungarian, instead of English). None of the listed problems happen if the table's menu is loaded normally, without AJAX, but loading it with AJAX just messes it up, and I have no clue why.
Table after the first click on the Autok button
This is how the table looks by default
Table after adding only one record
As you can see, even though I added just one record (the one with test1), it got inserted 6 times... also, everything on the site just doubled; double search bars, buttons, etc... before I added the test1 record, there really were only 9 entries, so it appears, the 9 entries text remained from before the record was added, and above that the new, 15 entries text was loaded. So, my question is: how do I make it, so that only that one records I actually inserted gets inserted (and not with a random number of copies)? Also, how do I get rid of the double search bars and such after insertion, and how do I make it, so that the table properly displays even after the first click on the Autok button on the left?
I tried using a newer jQuery and Database sourcecode, but it didn't do anything. I also tried to remove the $(document).ready(function()... parts of the code, either only from the index.php file, or from the autok.php file, but neither worked. As I mentioned before, if the table's menu is loaded without AJAX, everything works like a charm (the table itself still operates with AJAX), but I need it to load with AJAX, so I want to fix this. As for the database (MySQL), everything refreshes and works as it should, though for some reason I can't seem to delete the records that were wrongly inserted multiple times, because even if I click on delete (within phpmyadmin, it just... stays there.
This makes the table's menu (autok, which gets its content from autok.php) load without refreshing any pages, by clicking on its button (button's ID is autok), and then loading the table in a large div (which has the cell-content ID).
This is the code responsible for loading the Autok menu, it's found in my index.php file (just ignore the "belépés" and "regisztráció" parts, those work differently, not with AJAX):
<div id="menuk" class='belso bal'>
<?php
if(empty($_SESSION["username"]))
{
echo"<a href='?p=belep' >Belépés</a>";
}
else
{
echo"<a href='autok.php' id='autok'>Autók</a>";
echo"<a href='alkalmazottak.php' id='alkalmazottak'>Alkalmazottak</a>";
echo"<a href='vevok.php' id='vevok' >Vevők</a>";
}
echo"<a href='?p=reg'>Regisztráció</a>";
?>
</div>
<div id="cell-content" class='belso jobb' >
<script>
$(document).ready(function(){
$("#autok").click(function(){
$("#cell-content").load('autok.php');
return false;
});
});
$(document).ready(function(){
$("#alkalmazottak").click(function(){
$("#cell-content").load('alkalmazottak.php');
return false;
});
});
$(document).ready(function(){
$("#vevok").click(function(){
$("#cell-content").load('vevok.php');
return false;
});
});
</script>
This is the Autok menu's php (autok.php):
<html>
<head>
<title>Autószalon</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>
<style>
#user_data {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
}
#user_data td, #user_data th {
border: 1px solid #ddd;
padding: 8px;
}
#user_data tr:nth-child(even){background-color: #f2f2f2;}
#user_data tr:hover {background-color: #ddd;}
#user_data th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #4CAF50;
color: white;
}
</style>
</head>
<body>
<h1 align="center">Autószalon</h1>
<br />
<div class="table-responsive">
<br />
<div align="right">
<button type="button" name="add" id="add" class="btn btn-info">Hozzáad</button>
</div>
<br />
<div id="alert_message"></div>
<table id="user_data" class="table table-bordered table-striped">
<thead>
<tr>
<th>Autó</th>
<th>Ár</th>
<th>Alkalmazott</th>
<th></th>
</tr>
</thead>
</table>
</div>
</div>
</body>
</html>
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
fetch_data();
function fetch_data()
{
var dataTable = $('#user_data').DataTable({
"processing" : true,
"serverSide" : true,
"order" : [],
"ajax" : {
url:"fetch.php",
type:"POST"
}
});
}
function update_data(id, column_name, value)
{
$.ajax({
url:"update.php",
method:"POST",
data:{id:id, column_name:column_name, value:value},
success:function(data)
{
$('#alert_message').html('<div class="alert alert-success">'+data+'</div>');
$('#user_data').DataTable().destroy();
fetch_data();
}
});
setInterval(function(){
$('#alert_message').html('');
}, 5000);
}
$(document).on('blur', '.update', function(){
var id = $(this).data("id");
var column_name = $(this).data("column");
var value = $(this).text();
update_data(id, column_name, value);
});
$('#add').click(function(){
var html = '<tr>';
html += '<td contenteditable id="data1"></td>';
html += '<td contenteditable id="data2"></td>'
html += '<td contenteditable id="data3"></td>';
html += '<td><button type="button" name="insert" id="insert" class="btn btn-success btn-xs">Beszúrás</button></td>';
html += '</tr>';
$('#user_data tbody').prepend(html);
});
$(document).on('click', '#insert', function(){
var auto = $('#data1').text();
var ar = $('#data2').text();
var alkalmazott = $('#data3').text();
if(auto != '' && ar != '' && alkalmazott !='')
{
$.ajax({
url:"insert.php",
method:"POST",
data:{auto:auto, ar:ar, alkalmazott:alkalmazott},
success:function(data)
{
$('#alert_message').html('<div class="alert alert-success">'+data+'</div>');
$('#user_data').DataTable().destroy();
fetch_data();
}
});
setInterval(function(){
$('#alert_message').html('');
}, 5000);
}
else
{
alert("Egy mezot kihagyott!");
}
});
$(document).on('click', '.delete', function(){
var id = $(this).attr("id");
if(confirm("Biztosan torolni szeretne?"))
{
$.ajax({
url:"delete.php",
method:"POST",
data:{id:id},
success:function(data){
$('#alert_message').html('<div class="alert alert-success">'+data+'</div>');
$('#user_data').DataTable().destroy();
fetch_data();
}
});
setInterval(function(){
$('#alert_message').html('');
}, 5000);
}
});
});
</script>
As for the referenced PHPs, here is my fetch.php code:
<?php
//fetch.php
$connect = mysqli_connect("localhost", "root", "", "autoszalon");
if (!mysqli_connect_errno() && mysqli_set_charset($connect, "utf8"))
{
$columns = array('ID', 'Auto', 'Ar', 'Alkalmazott');
$query = "SELECT * FROM automenu ";
if(isset($_POST["search"]["value"]))
{
$query .= '
WHERE auto LIKE "%'.$_POST["search"]["value"].'%"
OR alkalmazott LIKE "%'.$_POST["search"]["value"].'%"
';
}
if(isset($_POST["order"]))
{
$query .= 'ORDER BY '.$columns[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].'
';
}
else
{
$query .= 'ORDER BY id DESC ';
}
$query1 = '';
if($_POST["length"] != -1)
{
$query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$number_filter_row = mysqli_num_rows(mysqli_query($connect, $query));
$result = mysqli_query($connect, $query . $query1);
$data = array();
while($row = mysqli_fetch_array($result))
{
$sub_array = array();
$sub_array[] = '<div contenteditable class="update" data-id="'.$row["id"].'" data-column="Auto">' . $row["Auto"] . '</div>';
$sub_array[] = '<div contenteditable class="update" data-id="'.$row["id"].'" data-column="Ar">' . $row["Ar"] . '</div>';
$sub_array[] = '<div contenteditable class="update" data-id="'.$row["id"].'" data-column="Alkalmazott">' . $row["Alkalmazott"] . '</div>';
$sub_array[] = '<button type="button" name="delete" class="btn btn-danger btn-xs delete" id="'.$row["id"].'">Törlés</button>';
$data[] = $sub_array;
}
function get_all_data($connect)
{
$query = "SELECT * FROM automenu";
$result = mysqli_query($connect, $query);
return mysqli_num_rows($result);
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => get_all_data($connect),
"recordsFiltered" => $number_filter_row,
"data" => $data
);
echo json_encode($output);
}
?>
Here is the update.php:
<?php
$connect = mysqli_connect("localhost", "root", "", "autoszalon");
if (!mysqli_connect_errno() && mysqli_set_charset($connect, "utf8"))
{
if(isset($_POST["id"]))
{
$value = mysqli_real_escape_string($connect, $_POST["value"]);
$query = "UPDATE automenu SET ".$_POST["column_name"]."='".$value."' WHERE id = '".$_POST["id"]."'";
if(mysqli_query($connect, $query))
{
echo 'Adat Frissitve';
}
}
}
?>
Here is the insert.php:
<?php
$connect = mysqli_connect("localhost", "root", "", "autoszalon");
if (!mysqli_connect_errno() && mysqli_set_charset($connect, "utf8"))
{
if(isset($_POST["auto"], $_POST["ar"], $_POST["alkalmazott"]))
{
$auto = mysqli_real_escape_string($connect, $_POST["auto"]);
$ar = mysqli_real_escape_string($connect, $_POST["ar"]);
$alkalmazott = mysqli_real_escape_string($connect, $_POST["alkalmazott"]);
$query = "INSERT INTO automenu(auto, ar, alkalmazott) VALUES('$auto', '$ar', '$alkalmazott')";
if(mysqli_query($connect, $query))
{
echo 'Adat Elmentve';
}
}
}
?>
And here is the delete.php code:
<?php
$connect = mysqli_connect("localhost", "root", "", "autoszalon");
if(isset($_POST["id"]))
{
$query = "DELETE FROM automenu WHERE id = '".$_POST["id"]."'";
if(mysqli_query($connect, $query))
{
echo 'Adat Torolve';
}
}
?>

How to add a "href" link in a td of data table to open a PHP page

I have this server side table that works fine, except it has modals, but I need to open another PHP edit page(not as modal), linked to the row-id selected.
</div>
<div class="table-responsive">
<table id="users_data" class="table table-bordered table-striped">
<thead>
<tr>
<th data-column-id="id" data-type="numeric">No</th>
<th data-column-id="idno">Id No</th>
<th data-column-id="surname">Surname</th>
<th data-column-id="firstname">Firstname</th>
<th data-column-id="category_name">Category</th>
<th data-column-id="age">Age</th>
<th data-column-id="commands" data-formatter="commands" data-sortable="false">Commands</th>
</tr>
</thead>
</table>
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
$('#add_button').click(function(){
$('#users_form')[0].reset();
$('.modal-title').text("Add New Users");
$('#action').val("Add");
$('#operation').val("Add");
});
var usersTable = $('#users_data').bootgrid({
ajax: true,
rowSelect: true,
post: function()
{
return{
id: "b0df282a-0d67-40e5-8558-c9e93b7befed"
};
},
url: "fetch.php",
formatters: {
"commands": function(column, row)
{
return "<button type='button' class='btn btn-warning btn-xs update' data-row-id='"+row.id+"'>Edit</button>" +
" <button type='button' class='btn btn-danger btn-xs delete' data-row-id='"+row.id+"'>Delete</button>";
}
}
});
Where the buttons are, I need something like this:
<td><span class="glyphicon glyphicon-pencil" aria-hidden="true" </span><b><font size="3" color="red"</font> Edit<b></td>
Currently it uses this modal info:
$(document).on("loaded.rs.jquery.bootgrid", function()
{
usersTable.find(".update").on("click", function(event)
{
var id = $(this).data("row-id");
$.ajax({
//url:"update2.php",
url:"fetch_single_entries.php",
method:"POST",
data:{id:id},
dataType:"json",
success:function(data)
{
$('#usersModal').modal('show');
$('#categories').val(data.categories);
$('#idno').val(data.idno);
$('#surname').val(data.surname);
$('#firstname').val(data.firstname);
$('#age').val(data.age);
$('.modal-title').text("Edit User");
$('#id').val(id);
$('#action').val("Edit");
$('#operation').val("Edit");
}
});
});
});
The fetch.php for the table data looks like this:
<?php
//fetch.php
include("connection.php");
$query = '';
$data = array();
$records_per_page = 10;
$start_from = 0;
$current_page_number = 0;
if(isset($_POST["rowCount"]))
{
$records_per_page = $_POST["rowCount"];
}
else
{
$records_per_page = 10;
}
if(isset($_POST["current"]))
{
$current_page_number = $_POST["current"];
}
else
{
$current_page_number = 1;
}
$start_from = ($current_page_number - 1) * $records_per_page;
$query .= "
SELECT
users.id,
tblcategories.category_name,
users.idno,users.surname,users.firstname,
users.age FROM users
INNER JOIN tblcategories
ON tblcategories.category_id = users.category_id ";
if(!empty($_POST["searchPhrase"]))
{
$query .= 'WHERE (users.id LIKE "%'.$_POST["searchPhrase"].'%" ';
$query .= 'OR tblcategories.category_name LIKE "%'.$_POST["searchPhrase"].'%" ';
$query .= 'OR users.idno LIKE "%'.$_POST["searchPhrase"].'%" ';
$query .= 'OR users.surname LIKE "%'.$_POST["searchPhrase"].'%" ';
$query .= 'OR users.firstname LIKE "%'.$_POST["searchPhrase"].'%" ';
$query .= 'OR users.age LIKE "%'.$_POST["searchPhrase"].'%" ) ';
}
$order_by = '';
if(isset($_POST["sort"]) && is_array($_POST["sort"]))
{
foreach($_POST["sort"] as $key => $value)
{
$order_by .= " $key $value, ";
}
}
else
{
$query .= 'ORDER BY users.id DESC ';
}
if($order_by != '')
{
$query .= ' ORDER BY ' . substr($order_by, 0, -2);
}
if($records_per_page != -1)
{
$query .= " LIMIT " . $start_from . ", " . $records_per_page;
}
//echo $query;
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result))
{
$data[] = $row;
}
$query1 = "SELECT * FROM users";
$result1 = mysqli_query($connection, $query1);
$total_records = mysqli_num_rows($result1);
$output = array(
'current' => intval($_POST["current"]),
'rowCount' => 10,
'total' => intval($total_records),
'rows' => $data
);
echo json_encode($output);
?>
Please assist this novice programmer about how to adjust the code.
Sounds like you just want to convert an jquery ajax edit thing on a modal dialogue into an actual HTML edit page. Replace all of that jquery with just a link to a new page you create, and on that page just have a form with the stuff in it. The first thing you'll want is to check if it's a GET or a POST request - if GET, query from the database for the values and display the standard HTML form. If it's a POST, update the database with the new values (after optionally doing some processing).
Hopefully that's the question you're asking? If so, sorry the answer is so broad, but the question is kind of broad too. Feel free to clarify further if there's a specific problem you're encountering trying to get the above to work.
Here is how to add the links:
return "<button type=\"button\" class=\"btn btn-xs btn-warning\" data-row-id=\"" + row.id + "\"><span class=\"glyphicon glyphicon-pencil\"></span></button> " +
"<button type=\"button\" class=\"btn btn-xs btn-danger\" data-row-id=\"" + row.id + "\"><span class=\"glyphicon glyphicon-trash\"></span></button>";

Where do I edit to change the search results design?

I have created a simple search engine who gets data from a PHP table and post the results. But as of right now it posts the results in a single line and nothing to show that they're in fact 4 different columns. What I'm looking for is a way to create a table so it looks more presentable. I have the search engine divided into 2 .php files.
1st file:
<?php
error_reporting(1);
include('system_admin.inc.php');
$title = 'Leonard';
make_header($title,array('enable_ajax' => true));
?>
<html>
<head>
<title>Leonard</title>
<script type=text/javascript src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type=text/javascript ">
function searchq() {
var searchTxt = $("input[name='search']").val();
$.post("testsearch.php", {searchVal: searchTxt}, function(output) {
$("#output") .html(output);
});
}
</script>
</head>
<body>
<h1>Search</h1>
<form class="odd" action="leonard.php" method="post">
<input type="text" name="search" placeholder="Search" onkeyup="searchq();" />
<div id="output">
</div>
</form>
</body>
</html>
2nd file:
mysql_connect ("localhost","root","xxxxxx") or die ("Connectionissues");
mysql_select_db ("xxxxxx") or die("Can't find DB");
$output = '';
if(isset($_POST['searchVal'])) {
$searchq = $_POST['searchVal'];
$searchq = preg_replace ("#^0-9#"," ",$searchq);
$query = mysql_query("SELECT * FROM ds_OrderItem WHERE idProduct LIKE '%$searchq%' LIMIT 100") or die("Search invalid!");
$count = mysql_num_rows ($query);
if($count == 0){
$output = 'Order have never been made before';
}else{
while($row = mysql_fetch_array($query)) {
$idproduct = $row['idProduct'];
$idorder = $row['idOrder'];
$title = $row['title'];
$qty = $row['qty'];
$output .= '<div> '.$idproduct.' '.$idorder.' '.$title.' '.$qty.' </div>';
}
if($_POST['searchVal'] == NULL) {
$output = "";
}
}
}
I want these four columns to be displayed in a presentable manner:
$idproduct = $row['idProduct'];
$idorder = $row['idOrder'];
$title = $row['title'];
$qty = $row['qty'];
Can anyone help me with this? :-)
Thanks in advance for reading and any advice given!
Change this portion
while($row = mysql_fetch_array($query)) {
$idproduct = $row['idProduct'];
$idorder = $row['idOrder'];
$title = $row['title'];
$qty = $row['qty'];
$output .= '<div> '.$idproduct.' '.$idorder.' '.$title.' '.$qty.' </div>';
}
to
$output .='<table>';
while($row = mysql_fetch_array($query)) {
$output .= '<tr><td>'.$row['idProduct'].'</td><td>'.$row['idOrder'].'</td><td>'.$row['title'].'</td><td>'.$row['qty'].'</td></tr>';
}
$output .='</table>';

Categories