Converting PHP pagination to jQuery? - php

Hey, I have been trying to get this pagination class that I am using to be more ajaxy - meaning when I click on the page number like page [2] the data loads, but I want to load in the data without going to a different page (HTTP request in the background, with no page reloads).
Being new to both php and jquery, I am a little unsure on how to achieve this result, especially while using a php class.
This is what the main page looks like by the way:
<?php
$categoryId=$_GET['category'];
echo $categoryId;
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery_page.js"></script>
<?php
//Include the PS_Pagination class
include('ps_pagination.php');
//Connect to mysql db
$conn = mysql_connect('localhost', 'root', 'root');
mysql_select_db('ajax_demo',$conn);
$sql = "select * from explore where category='$categoryId'";
//Create a PS_Pagination object
$pager = new PS_Pagination($conn, $sql, 3, 11, 'param1=value1&param2=value2');
//The paginate() function returns a mysql
//result set for the current page
$rs = $pager->paginate();
//Loop through the result set
echo "<table width='800px'>";
while($row = mysql_fetch_assoc($rs)) {
echo "<tr>";
echo"<td>";
echo $row['id'];
echo"</td>";
echo"<td>";
echo $row['site_description'];
echo"</td>";
echo"<td>";
echo $row['site_price'];
echo"</td>";
echo "</tr>";
}
echo "</table>";
echo "<ul id='pagination'>";
echo "<li>";
//Display the navigation
echo $pager->renderFullNav();
echo "</li>";
echo "</ul>";
?>
<div id="loading" ></div>
<div id="content" ></div>
Would I need to do something with this part of the class?, as seen above:
$pager = new PS_Pagination($conn, $sql, 3, 11, 'param1=value1&param2=value2');
Or this?:
echo $pager->renderFullNav();
I don't no much about jquery,but i guess I would start it like:
$("#pagination li").click(function() {
Then load something maybe...
I don't no. Any help on this would be great. Thanks.

Im not sure how to go about it using that class, it seems it would be a bit tricky, as the script you make the ajax call to, to retrieve the data, will need to have access to the current PS_pagination instance.
Without the class though, it wouldnt be too tricky.
You would need a php script to actually return the data, which takes in the number of records per page, and the current page number. In this script, rather than returning the data, i return the html. So i take the data from the database, then generate the table. This means that all i have to do on success of ajax is replace what is in the able currently, with the new html that i get from this script. Heres an example..
//Current Page Number
$page_num = isset($_GET['page_number']) ? mysql_real_escape_string($_GET['page_number']) : 1;
//Number of records to show on each page
$num_records = isset($_GET['num_records_pp']) ? mysql_real_escape_string($_GET['num_records_pp']) : 10;
//Row to start collecting data from
$start_row = $num_records * ($page_num - 1);
//String to store html to return
$return_html = '';
//SQL Query
$sql = mysql_query("SELECT * FROM my_table LIMIT $start_row, $num_records");
//Query success
if($sql) {
//Construct html for table
$return_html = "<table width='800px'>";
while($row = mysql_fetch_array($sql) {
$return_html .= "<tr>";
$return_html .= "<td>" . $row['id'] . "</td>";
$return_html .= "<td>" . $row['site_description'] . "</td>";
$return_html .= "<td>" . $row['site_price'] . "</td>";
$return_html .= "</tr>";
}
$return_html .= "</table>";
//Query Failed
} else {
$return_html = "<p class='error'>Error Fetching Data</p>";
}
return $return_html;
Then you just make a get request via ajax and pass the page number, and the number of rows you want.
$.get("get_data.php", { page_number: 1, num_records_pp: 20 },
function(data){
$('div#my_table').html(data);
});
So, this query assumses that you have a div with an id of "my_table" which contains your table, it will then replace this with a new table consistion of just the data you requested.
This code was just to give you the jist, so i may have some errors in there, but hope it helps.

Related

Data not required is being displayed

I have a form where the user enters data e.g. AXZAA QS1QS. This data is Posted to my PHP script. The PHP Script connects to a MYSQL database which contains at the moment 2 records.
The idea is that the PHP script will take the input and compare it to the records in the database. If the records exist they are displayed in a table on a web page otherwise, an error message is displayed.
I am having a number of problems with my PHP script and have modified my script a number of times. However, the thing I am having the biggest problem with is this:
When the form appears for the first time, the message record doesn't exist appears twice, this is before the user has entered any data and is seeing the form for the first time. See picture below.
After entering data (when the PHP script was partially working correctly), if there is a match i.e. records existed, along with the records in the table I would receive an error message telling me that records were not found. To see if I could resolve the problem I added code to tell me what records could not be found, the records that couldn't be found were the ones that were found and the other records from the database which I wasn't looking for. I know the SQL query in my PHP script tells the script to get everything from the database however, I would have thought the if statement would have fixed the problem.
Sorry about writing such a long problem and I hope it's not confusing.
enter code here
<?php
//Connect to the database connection file
require 'databaseconnection.php';
$searchBar=(isset($_POST['searchBar']) ? $_POST['searchBar'] :null);
$userdata = trim($searchBar);
$cleaned_data = preg_split('/[\s]+/', $userdata);
$sql = "SELECT DISTINCT * FROM atable_2";
$result = mysqli_query($database_connection, $sql);
echo "<table border>
<tr>
<th>Allocation</th>
<th>Codes</th>
<th>Names</th>
</tr>";
while($putdatabaseanswer_intoarray = mysqli_fetch_array($result)) {
$allocation_id = $putdatabaseanswer_intoarray["allocation"];
$codes_id = $putdatabaseanswer_intoarray["codes"];
$names_id = $putdatabaseanswer_intoarray["names"];
foreach($cleaned_data as $value) {
if($value==$codes_id) {
echo "<tr>";
echo "<td>" . $allocation_id. "</td>";
echo "<td>" . $codes_id . "</td>";
echo "<td>" . $names_id . "</td>";
echo "</tr>";
}
else
{
echo "<br />";
echo "One or more of the records have not been found: $codes_id";
echo"<br />";
}
}
}
echo "</table>";
?>
Wouldn't it be better to assign $searchbar after an if statement like
`<?php
//Connect to the database connection file
require 'databaseconnection.php';
if(isset($_POST['searchBar']))
{
$searchbar = $_POST['searchBar'];
$userdata = trim($searchBar);
$cleaned_data = preg_split('/[\s]+/', $userdata);
$sql = "SELECT DISTINCT * FROM atable_2";
$result = mysqli_query($database_connection, $sql);
echo "<table border>
<tr>
<th>Allocation</th>
<th>Codes</th>
<th>Names</th>
</tr>";
while($putdatabaseanswer_intoarray = mysqli_fetch_array($result)) {
$allocation_id = $putdatabaseanswer_intoarray["allocation"];
$codes_id = $putdatabaseanswer_intoarray["codes"];
$names_id = $putdatabaseanswer_intoarray["names"];
foreach($cleaned_data as $value) {
if($value==$codes_id) {
echo "<tr>";
echo "<td>" . $allocation_id. "</td>";
echo "<td>" . $codes_id . "</td>";
echo "<td>" . $names_id . "</td>";
echo "</tr>";
}
else
{
echo "<br />";
echo "One or more of the records have not been found: $codes_id";
echo"<br />";
}
}
}
echo "</table>";
}
else{
echo "<p>Please enter a search term</p>";
}
?>
You could then execute the MySQL query within that "if" statement rather than having it execute assuming there is a value

How would I create and bring in a variable from another PHP page

I have a table that is created in
php. I have called this page events. I have used an include function within my user page to display the table so that a user can use the events to book an event. The thing is, I now need to create a page that will run once a user has clicked on the book now button. This page will update the booking table in my database. I am completely lost here and don't know how to go about creating this page as I think I need a variable that is brought in from the events table, perhaps via the button. The booking table in the database has these columns. Booking_ID, User_ID, Event_ID, Payment_Type and Date_Booked. I know I am using mysql but I will get the newer versions after I have this all working. I just don't know where to start on the creation of the booking PHP and inserting the values from the events table into the database. Any help will be greatly appreciated.
This is the events table that is displayed on the user page to book an event
<?php
$con = mysql_connect("localhost","root","");
if(!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("flexiflash", $con);
// Creating the foundations for the table headings //
echo "<thead>";
echo "<tr>";
echo "<th>ID</th>";
echo "<th>Venue</th>";
echo "<th>Event</th>";
echo "<th>Date</th>";
echo "<th>Time</th>";
echo "<th></th>";
echo "</tr>";
echo "</thead>";
// Running a JavaScript function to check for the user's payment type before submitting the form to book_event.php //
echo '<script>
function check() {
if (document.getElementById("checkbox").checked && document.getElementById("card").checked)
{
alert("Pay by card with 20% off");
return true;
}
else if (document.getElementById("checkbox").checked && document.getElementById("paypal").checked)
{
alert("Pay via PayPal with 20% off");
return true;
}
else if (document.getElementById("card").checked)
{
alert("Pay by card without a voucher!");
return true;
}
else if (document.getElementById("paypal").checked)
{
alert("Pay via PayPal without a voucher!");
return true;
}
else
{
alert("Nothing was checked. Please select your payment type");
return false;
}
}
</script>';
$result = mysql_query("SELECT * FROM events");
while($row = mysql_fetch_array($result))
{
// Outputting the data from the $result variable into a formatted table //
echo "<tbody>";
echo "<form class='table-form' action='book_event.php' method='post' onsubmit='return check()'>";
echo "<tr>";
echo "<td>" . $row['Event_ID'] . "</td>";
echo "<td>" . $row['Event_Venue'] . "</td>";
echo "<td>" . $row['Event_Name'] . "</td>";
echo "<td>" . $row['Event_Date'] . "</td>";
echo "<td>" . $row['Event_Time'] . "</td>";
echo "<td><input type='submit' class='sub_btn' value='Book now'></td>";
echo "</tr>";
echo "</form>";
echo "</tbody>";
}
mysql_close($con);
?>
If you need any more code or any other information please feel free to ask.
I know my code is not great and I am using Javascript inside my PHP but I am still learning PHP. Only been doing this for about 2 months, so I know its not the best.
If the page you are sending your data to is on the same host then SESSION might be what youre looking for. You can also use the form to POST data, via a form action to another page to process the data. If the data isnt sensitive then you can pass vars between pages with GET or even cookies, but it seems that passing the data isn't your main concern here.
One option to look at is creating a separate page to handle the form processing and insert the data, this can be called in the form action tag
It sounds like you are new to this and it might over complicate things but it is worth looking at MVC to separate concerns.

How can AJAX handling be incorporated into a PHP/MySQL While Loop (for asynchronous editing)?

SCROLL TO FIND WORKING CODE
I am working on a AJAX editing platform, and I am having trouble with setting up the text field for editing.
My code so far:
The Javascript below handles the initial submission:
<head>
<script type="text/javascript">
if(window.ActiveXObject) var ajax = new ActiveXObject('Microsoft.XMLHTTP');
else var ajax = new XMLHttpRequest();
function edit()
{
var doc_id = document.getElementById("doc_id").value;
ajax.open('GET', 'ajax.php?doc_id='+doc_id, true);
ajax.onreadystatechange = function()
{
if(ajax.readyState == 4)
{
document.getElementById('content').innerHTML = ajax.responseText;
}
}
ajax.send(null);
}
</script>
</head>
The SQL below handles the initial select query and display of that information:
$query = 'SELECT pp.`physician_id`, pp.`physician_first_name`, pp.`physician_last_name`, pp.`featured`, ';
$query.= 'FROM `primary_physicians` AS pp ';
$query.= 'ORDER BY pp.`physician_id` ';
<body>
<div id="container">
<?php
$result = mysql_unbuffered_query( $query );
echo "<table border='1'>";
while ($row = mysql_fetch_assoc($result))
{
echo "<tr>";
$physician_id = $row['physician_id'];
echo "<td>" . $row['physician_id'] . "</td>";
echo "<td><div id='content'><input id='doc_id' type='hidden' value='$physician_id' />" . $row['physician_first_name'] . "<br /><input type='button' value='Edit' onclick='edit();'></div></td>";
echo "<td>" . $row['physician_last_name'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
</div>
</body>
</html>
And the 'ajax.php' file handles the request when the user clicks the 'Edit' button within the 'content' div.
$client_id = $_GET['doc_id'];
$client_query = 'SELECT pp.`physician_id`, pp.`physician_first_name`, pp.`physician_last_name`, pp.`featured` ';
$client_query.= 'FROM `primary_physicians` AS pp WHERE pp.`physician_id`=' . $client_id . '';
$client_result = mysql_unbuffered_query( $client_query );
while ($client_row = mysql_fetch_assoc($client_result))
{
echo "<input type='text' value='$client_row[physician_first_name]' />";
}
What shows is below:
Initial page load:
Pressing the 'edit' button (any of the available buttons, not just the one associated with the client/ID):
Pressing any edit button shows client ID #2 within client ID #1's table row (not in the row with client ID #2):
I'm guessing I have to set up something within the content div and somehow associate it with the 'edit()' function, however I can't figure out how to do that without setting the script within the while loop (which I really don't want to do).
WORKING CODE BELOW
Javascript (initial submission and display):
<head>
<script type="text/javascript">
if(window.ActiveXObject) var ajax = new ActiveXObject('Microsoft.XMLHTTP');
else var ajax = new XMLHttpRequest();
function hello(e)
{
/* this was once document.getElementById("doc_id").value;*/
var doc_id = e.currentTarget.id;
ajax.open('GET', 'ajax.php?doc_id='+doc_id, true);
ajax.onreadystatechange = function()
{
if(ajax.readyState == 4)
{
/*this was without the '+doc_id' document.getElementById('content').innerHTML = ajax.responseText; */
document.getElementById('content'+doc_id).innerHTML = ajax.responseText;
}
}
ajax.send(null);
}
</script>
</head>
PHP/MySQL:
<body>
<div id="container">
<?php
$result = mysql_unbuffered_query( $query );
echo "<table border='1'>";
while ($row = mysql_fetch_assoc($result))
{
echo "<tr>";
$physician_id = $row['physician_id'];
echo "<td>" . $row['physician_id'] . "</td>";
//note change to the 'content' div (addition of $physician_id to make it truly unique; this ties into the javascript above.
echo "<td><div id='content$physician_id'>";
//note changes to input id and button id, as well as the 'onclick' function.
echo "<input id='doc_id_$physician_id' type='hidden' value='$physician_id' />" . $row['physician_first_name'] . "<br /><input type='button' id='$physician_id' value='Edit' onclick='hello(event);'></div></td>";
echo "<td>" . $row['physician_last_name'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
</div>
</body>
No changes to or initial MySQL query or to ajax.php
There is a problem with the elements' ids. Remeber that the id attribute should be unique inside a document. You are using the same id for numerous elements:
td><div id='content'><input id='doc_id' type='hidden' ...
inside a loop.
Then you use the Javascript document.getElementById('doc_id'). JS supposes there is only one element with this id on the page so it will always return the first element it finds.
EDIT:
You will have to also change your JS function to retrieve the proper value:
for the edit buttons use: onclick="edit(event)"
And then in the JS:
function edit(e) {
buttonId = e.currentTarget.id;
//use the button id to find the proper value
}
Of course you will have to set the id on the "edit" buttons and have it correspond with id of you inputs. E.g. use $i for the button id and doc_id_$i for the input id.
I also recommend having a look at jQuery, as it will help facilitate many of the things you're trying to achieve here.

Place php code inside floating css container(s)?

i have a question in regards to php and css layers.
i have the following php code:
session_start();
// Retrieve all the data from the table
$SQL = "SELECT * FROM Exodus_planets WHERE login_id = $user[login_id] LIMIT 10";
$result = mysql_query($SQL);
//while ($db_field = mysql_fetch_assoc($result)) {
//print $db_field['planet_name'] . "<BR>";
//print $db_field['location'] . "<BR>";
while($row = mysql_fetch_array( $result )){
echo " Planet, ".$row['planet_name'];
echo " is located at System ".$row['location'];
echo "<br> ";
}
which correctly displays a word [Planet name] and a number [System] in sequence.
The above code displays the information in rows such as;
Planet Sun is located in system 35.
Planet Saturn is located in system 30.
i'm just trying to make this information display a look a little nicer. in a way so planet name shows up in the right of a background image container and system in another corner possibly colored.
....
How do i place the above code inside floating css container(s)?
Thank you.
As it seems to be a list of planets, I would use an HTML list. You can edit the css to have it look the way you want after.
echo ' <ul class="planetList"> ';
while($row = mysql_fetch_array( $result )){
echo '<li>';
echo " Planet, ".$row['planet_name'];
echo " is located at System ".$row['location'];
echo '</li> ';
}
echo '</ul>';
In CSS
ul.planetList {
display:block;
float:right;
background-image:url('yourBackground.jpg');
background-position:left;
background-repeat:repeat-y;
/* CSS 3 Only */
background-size:{length of your text}px 100%;
}
You could also use a table instead of the list. This way, you could get a background for the planet column, and another one for the located at sytem one.
echo ' <table> ';
echo ' <tr><th>Planet</th><th>System</th></tr>';
while($row = mysql_fetch_array( $result )){
echo '<tr>';
echo '<td class="planet">' . $row['planet_name'] . '</td>';
echo '<td class="system">' . $row['location'] . '</td>';
echo '</tr> ';
}
echo '</table>';
CSS :
table>tr.planet {
background-image:url('yourBackground.jpg');
background-position:left;
}
table>tr.system {
background-color:#CCFF00;
}
Php code should be inside tags. You can always close these tags and put some htmls tags
Example:
<div class="bla"><?php
my code
?></div>
Obviusly you can do everything in php
<?php
echo '<div class="bla">';
....phpcode....
echo '</div>';
?>
Hopefully this helps
You can do something like this to keep your code clean
<?php
session_start();
// Retrieve all the data from the table
$SQL = "SELECT * FROM Exodus_planets WHERE login_id = $user[login_id] LIMIT 10";
$result = mysql_query($SQL);
$planets = array();
while($row = mysql_fetch_array( $result )){
$planets[] = $row;
}
foreach($planets as $planet): ?>
<div class="prettyFloatyDiv">
Planet, <?php echo $planet['planet_name']?>
is located at System <?php echo $planet['location']?>
<br/>
</div>
<?php endforeach; ?>
If you have short tags enabled, you can replace every <?php echo with <?=

How to make sql query dynamic?

I am using this pagination class and was looking for a way to make the sql query more dynamic instead of having it hardcoded.
I have a 3 <li> elements that I want to be filter buttons, meaning when a user clicks on one of these elements I want It to send the id so I can use it in a sql query.
So for the $sql = "select * from explore where category='marketing'"; (as seen below). When the user clicks on the 'automotive' button it will change the category above to automotive.
Any help on this would be highly appreciated, Thanks.
This is what my main page looks like:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery_page.js"></script>
<?php
//Include the PS_Pagination class
include('ps_pagination.php');
//Connect to mysql db
$conn = mysql_connect('localhost', 'root', 'root');
mysql_select_db('ajax_demo',$conn);
$sql = "select * from explore where category='marketing'";
//Create a PS_Pagination object
$pager = new PS_Pagination($conn, $sql, 3, 11, 'param1=valu1&param2=value2');
//The paginate() function returns a mysql
//result set for the current page
$rs = $pager->paginate();
//Loop through the result set
while($row = mysql_fetch_assoc($rs)) {
echo "<table width='800px'>";
echo "<tr>";
echo"<td>";
echo $row['id'];
echo"</td>";
echo"<td>";
echo $row['site_description'];
echo"</td>";
echo"<td>";
echo $row['site_price'];
echo"</td>";
echo "</tr>";
echo "</table>";
}
echo "<ul id='pagination'>";
echo "<li>";
//Display the navigation
echo $pager->renderFullNav();
echo "</li>";
echo "</ul>";
echo "<ul id='filter'>";
echo "<li id='marketing'>";
echo "Marketing";
echo "</li>";
echo "<li id='automotive'>";
echo "Automotive";
echo "</li>";
echo "<li id='sports'>";
echo "Sports";
echo "</li>";
echo "</ul>";
?>
looks like this line
$pager = new PS_Pagination($conn, $sql, 8, 3, 'param1=valu1&param2=value2');
should be edited to carry variables to be tested before the sql query is run.... something maybe like:
$pager = new PS_Pagination($conn, $sql, 8, 3, 'param1=automotive&param2=sports');
then try this
if($_POST["param1"]=="automotive")
{
$sql = "select * from explore where category='automotive'";
}
and work around with it to see if you can get your desired results. I've never used the class before, but it looks like you'll have to play with these params to get your desired result

Categories