How to display the page with ajax? - php

I have a pagination that works correctly even I have added a filter to paginate more rows on the same page is to say that through the filter I can show 10 or 50 rows.
The small defect that I have in my code is that the page is reloaded, changing how many rows show and the same happens in the buttons of the pagination.
This is my code, everything is working on the same page index2.php.
<div id="wrapper">
<div class="container">
<div id="news-header" class="bootgrid-header container-fluid">
<div class="row">
<div class="col-sm-12 actionBar">
<div class="search-bar">
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="What are you looking for?">
</div>
<div class="actions btn-group">
<?php
$select_quantity = '';
if (isset($_POST['amount_show'])) :
$select_quantity = $_POST['amount_show'];
endif;
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<select id="amount_show" name="amount_show" onchange="this.form.submit()">
<option value="10" <?php if ($select_quantity==10) echo "selected"; ?>>10</option>
<option value="25" <?php if ($select_quantity==25) echo "selected"; ?>>25</option>
<option value="50" <?php if ($select_quantity==50) echo "selected"; ?>>50</option>
<option value="100" <?php if ($select_quantity==100) echo "selected"; ?>>100</option>
</select>
</form>
</div>
</div>
</div>
</div>
<?php
if (isset($_GET['page'])) :
$page = $_GET['page'] ?: '';
else :
$page = 1;
endif;
if (isset($_POST['amount_show'])) :
$records_by_page = $_POST['amount_show'];
else :
$records_by_page = 10;
endif;
$localization_sql = ($page-1) * $records_by_page;
$sql = "SELECT id,title,description
FROM news
ORDER BY id DESC LIMIT $localization_sql, $records_by_page";
$stmt = $con->prepare($sql);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows>0) :
echo '<table id="myTable" class="table table-condensed table-hover table-striped bootgrid-table">
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Description</th>
<th>Action</th>
</tr>
</thead>
<tbody>';
$stmt->bind_result($id,$title,$description);
while ($stmt->fetch()) :
echo '<tr>
<td>'.$id.'</td>
<td>'.$title.'</td>
<td>'.$description.'</td>
<td>Edit</td>
</tr>';
endwhile;
echo '</tbody>';
echo '</table>';
$stmt->close();
$sql = "SELECT * FROM news";
$stmt = $con->prepare($sql);
$stmt->execute();
$stmt->store_result();
$BD_records = $stmt->num_rows;
$stmt->close();
$con->close();
$total_page = ceil($BD_records / $records_by_page);
$prev = $page - 1;
$next = $page + 1;
echo '<div class=pagination>
<ul class="pagination">';
if ($prev > 0) :
echo "<li><a href='index2.php?page=1'><i class='icon-angle-double-arrow'></i></a></li>";
echo "<li><a href='index2.php?page=$prev'><i class='icon-angle-left'></i></a></li>";
endif;
for ($i=1; $i<=$total_page; $i++) :
if ($page==$i) :
echo "<li><a class=active>". $page . "</a></li>";
else :
echo "<li><a href='index2.php?page=$i'>$i</a></li>";
endif;
endfor;
if ($page < $total_page ) :
echo "<li><a href='index2.php?page=$next'><i class='icon-angle-right'></i></a></li>";
echo "<li><a href='index2.php?page=$total_page'><i class='icon-angle-double-right'></i></a></li>";
endif;
echo '</ul></div>';
else :
$stmt->close();
endif;
?>
</div>
</div>
While searching the web I found an ajax code, but sincerely, I did not manage the use ajax or javascript / jquery code.
You can explain how to implement this ajax code or how to avoid the small defect of reloading the page.
<script type="text/javascript">
$(document).ready(function() {
$('.pagination li a').on('click', function(){
/*$('.items').html('<div class="loading"><img src="images/loading.gif" width="70px" height="70px"/><br/>Loading...</div>');*/
$('.items').html('<div class="loading">Loading...</div>');
var page = $(this).attr('data');
var dataString = 'page='+page;
$.ajax({
type: "GET",
url: "ajax.php",
data: dataString,
success: function(data) {
$('.items').fadeIn(2000).html(data);
$('.pagination li').removeClass('active');
$('.pagination li a[data="'+page+'"]').parent().addClass('active');
}
});
return false;
});
});
</script>
This is how my code works, as shown in the following image:

Ajax is going to update information on your page without reloading your page. We want to separate the data from the HTML so we can change which data we're seeing. We can't do that if PHP is the tool writing the data into the HTML. So I recommend separating index2.php into several files. This example uses JSON.
Collect the data
ajax.php
<?php
$data_rows = array();
for ($i = 0; $i < 1000; $i++) {
$data_rows[] = array(
"id" => "id_$i",
"title" => "title_$i",
"description" => "description_$i",
);
}
echo json_encode($data_rows, JSON_PRETTY_PRINT);
This is an example of some junk data, I don't know what data you need. The important thing here is to make an associative array of all the information you want, json_encode() the array, and then echo it. It's important that this is the only thing that gets echoed or printed! This won't work if you have anything else printing in this script.
Edit:
ajax.php
if (isset($_GET['page'])) :
$page = $_GET['page'] ?: '';
else :
$page = 1;
endif;
if (isset($_POST['amount_show'])) :
$records_by_page = $_POST['amount_show'];
else :
$records_by_page = 10;
endif;
$sql = "SELECT id, title, description
FROM news
ORDER BY id DESC LIMIT $localization_sql, $records_by_page";
$result = $con->query($sql);
$data_rows = array();
while ($row = $result->fetch_assoc()) {
$data_rows = $row;
}
echo json_encode($data_rows, JSON_PRETTY_PRINT);
Your original code includes this mysqli connection, this is data that I don't have access to so I can't test the efficacy of this script. However, this should present all of the data that you're asking about.
Ajax with jQuery
script.js
$(document).ready(function() {
$.ajax({
type: "GET",
url: "ajax.php",
dataType: "json",
success: function(data) {
tableRows = '';
for (let i = 0; i < data.length; i++) {
tableRows += `
<tr>
<td>${data[i].id}</td>
<td>${data[i].title}</td>
<td>${data[i].description}</td>
<td>Edit<td>
</tr>`;
}
$("#tbody-insert").html(tableRows);
}
});
});
Set the url parameter of your ajax call to the name of the php file that's delivering the data. In the example I'm using JSON, it's important to set dataType: "json". jQuery will automatically parse this for you. You can see in the success parameter, data is the name of the php array we've created. I used a simple for loop to create a bunch of table rows, then inserted them into a table body that I've labeled with id="tbody-insert".
Present the data
index.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<table id="myTable" class="table table-condensed table-hover table-striped bootgrid-table">
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Description</th>
<th>Action</th>
</tr>
</thead>
<tbody id="tbody-insert">
</tbody>
</table>
I've taken all the PHP out of your index page, it's not very flexible and it requires reloading the entire page before updating the information. The important points to note are the script tags, you need to include jQuery and you need to include the script.js. You also need to have an id for the table body that we're inserting information into. You can wrap your ajax in a function that gets called every time you want to paginate, and query ajax.php for different pages. I don't know the structure of your data so I can't help any further with that.

Let's start with the reason that causes your page to reload: The default browser actions. Several html elements cause the browser to navigate away from the current page. The ones we are concerned in this case are:
#amount_show form submission (the onchange function) that sends the new value via POST request.
The paginator itself (with a links) that tells the php script which records to retrieve via GET request.
Both values should be passed to the php script for it to be able to return the correct records, otherwise the amount parameter would be the default in the php script even if we have a different value selected. To be able to do that, we have to change the passing of the amount variable to a GET request.
Also, when changing the amount value we'll default to the first page to avoid recalculating the page number.
Since the pagination links can therefore change dinamically, I'm not going to handle them in javascript but in php instead, since we already have a template and the calculations. This will make things easier to change down the line.
Let's tackle the javascript first:
$(document).ready(function() {
// When we change the value of the select...
// evt contains the information about the event:
// element receiving the action, the action itself, etc.
$('#amount_show').change(function(evt) {
// Cancel the default browser action
evt.preventDefault()
// Get the target url of the form (our php script)
url = $(this).parent().attr('action')
// Call the funtion that will be doing the request
ajaxLoad(url)
});
// When we click a pagination link... (Explanation below)
$('.items').on('click', '.pagination li a', function(evt) {
evt.preventDefault()
url = $(this).attr('href')
ajaxLoad(url)
});
// Do the actual request
function ajaxLoad(url) {
// How many records do we want to show ?
query_params = {
amount_show: $('#amount_show').val()
};
// Show an indication that we are working
$('.items').html('<div class="loading">Loading...</div>')
$.ajax({
type: "GET",
url: url, // Call php, it will default to page 1 if there's no parameter set
// When calling a link with a page parameter this will be smart
// enough to append the variable to the query string correctly
data: $.param(query_params),
// Handle the data return. In a perfect world, this is always successful
success: function(data) {
// Insert the data in the document.
$('.items').fadeOut('1000', function() { $(this).html(data) }).fadeIn('1000')
}
});
}
});
The line $('.items').on('click', '.pagination li a', function(evt) { attaches a delegate event listener to the .items element that will respond to the click events received by .pagination li a. The reason to do this instead of attaching directly to the element itself is two-fold:
Reduce the number of elements that we have to loop and attach a listener to.
Handle dynamic insertion of elements. When switching content, we are deleting the elements from the document, and their listeners with them. We would have to attach them again on every page load, otherwise with no listeners attached they would go back to the default action. But since this element doesn't change we won't have to do it.
Now for the php. Since you are interested in using a single file, I'm just going to move things around but it will (mostly) be what you have now.
Note: I may have misunderstood what you mean by having all in a single page. If this is a partial template that you are including from your main index, you'll have to change the link targets and action for the form to point to it, adjust some javascript selectors and you could skip the whole ajax request checking.
Main changes:
Remove your onchange function call.
Change POST parameter to GET parameter.
Add a .items span to insert the elements in since it doesn't exist.
Determine if a page load is an ajax load or a regular one using X-Requested-With header. An alternative to this is returning a full response anyway and filtering it with jQuery.
<?php
if (isset($_GET['page'])) :
$page = $_GET['page'] ?: '';
else :
$page = 1;
endif;
if (isset($_GET['amount_show'])) :
$records_by_page = $_GET['amount_show'];
else :
$records_by_page = 10;
endif;
$localization_sql = ($page-1) * $records_by_page;
$sql = "SELECT id,title,description
FROM news
ORDER BY id DESC LIMIT $localization_sql, $records_by_page";
$stmt = $con->prepare($sql);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows>0) :
// Start capturing the output
ob_start();
?>
<table id="myTable" class="table table-condensed table-hover table-striped bootgrid-table">
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Description</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$stmt->bind_result($id,$title,$description);
while ($stmt->fetch()) :
echo '<tr>
<td>'.$id.'</td>
<td>'.$title.'</td>
<td>'.$description.'</td>
<td>Edit</td>
</tr>';
endwhile;
$stmt->close();
?>
</tbody>
</table>
<div class=pagination>
<ul class="pagination">
<?php
// When requesting an out-of-bounds page, this won't execute resulting in
// a blank page with no paginator
$sql = "SELECT * FROM news";
$stmt = $con->prepare($sql);
$stmt->execute();
$stmt->store_result();
$BD_records = $stmt->num_rows;
$stmt->close();
$con->close();
$total_page = ceil($BD_records / $records_by_page);
$prev = $page - 1;
$next = $page + 1;
if ($prev > 0) :
echo "<li><a href='" . $_SERVER['PHP_SELF'] . "?page=1'><i class='icon-angle-double-arrow'></i></a></li>";
echo "<li><a href='" . $_SERVER['PHP_SELF'] . "?page=$prev'><i class='icon-angle-left'></i></a></li>";
endif;
for ($i=1; $i<=$total_page; $i++) :
if ($page==$i) :
echo "<li><a class='page-link active' >". $page . "</a></li>";
else :
echo "<li><a class='page-link' href='" . $_SERVER['PHP_SELF'] . "?page=$i'>$i</a></li>";
endif;
endfor;
if ($page < $total_page ) :
echo "<li><a class='page-link' href='index2.php?page=$next'><i class='icon-angle-right'></i></a></li>";
echo "<li><a class='page-link' href='index2.php?page=$total_page'><i class='icon-angle-double-right'></i></a></li>";
endif;
echo '</ul></div>';
// Get the output into a variable
$results_table = ob_get_clean();
else :
$results_table = "<div>No results found</div>";
$stmt->close();
endif;
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) :
// If is an ajax request, output just the result table and exit
echo $results_table;
die;
endif;
// Print the whole page if its not an ajax request
?>
<script type='text/javascript' src='//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js'/>
<script src='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.min.js' />
<link rel='stylesheet' href='https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css' type='text/css' />
<div id='wrapper'>
<div class='container'>
<div id='news-header' class='bootgrid-header container-fluid'>
<div class='row'>
<div class='col-sm-12 actionBar'>
<div class='search-bar'>
<input type='text' id='myInput' placeholder='What are you looking for?'>
</div>
<div class='actions btn-group'>
<form action=<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>'>
<select id='amount_show' name='amount_show'>
</select>
</form>
</div>
</div>
</div>
</div>
<span class='items'>
<?php echo $results_table; ?>
</span>
</div>
</div>
For completeness, the alternative method without separating the responses with php, is to filter the response with jQuery by doing the following in the ajax success callback (fades omitted):
results_table = $(data).find('.items').html()
$('.items').html(results_table)
This converts the response from the server into a jQuery object and allows to apply filtering functions as normal. We extract the content we are interested in (content of items: result table and pagination), then we just append it to the items container on our existing page.
UPDATE: I've posted a simplified example without database-related code here. I think there's something weird going on when copy&paste'ng code from/to the editor.
References
DOM events
jQuery ajax and helper functions
PHP output buffering
Not receiving X_REQUESTED_WITH request header
Fade effects in ajax callback

There's no point to start playing with jquery and async calls if even pure html is bit over the limit. In initial code you are mixing POST and GET, use just one.
<div id="wrapper">
<div class="container">
<div id="news-header" class="bootgrid-header container-fluid">
<div class="row">
<div class="col-sm-12 actionBar">
<div class="search-bar">
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="What are you looking for?">
</div>
<div class="actions btn-group">
<?php
//getting both - page and record_by_page from GET
$records_by_page = isset($_GET['amount_show'])?$_GET['amount_show']:10;
$page = isset($_GET['page'])?$_GET['page']:1;
//put page value into form to send it together with amount_show
?>
<form method="get" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<select id="amount_show" name="amount_show" onchange="this.form.submit()">
<option value="10" <?php if ($records_by_page==10) echo "selected"; ?>>10</option>
<option value="25" <?php if ($records_by_page==25) echo "selected"; ?>>25</option>
<option value="50" <?php if ($records_by_page==50) echo "selected"; ?>>50</option>
<option value="100" <?php if ($records_by_page==100) echo "selected"; ?>>100</option>
</select>
<input type="hidden" id="page" name="page" value="<?php echo $page; ?>"></input>
</form>
</div>
</div>
</div>
</div>
<?php
$localization_sql = ($page-1) * $records_by_page;
$sql = "SELECT id,title,description
FROM news
ORDER BY id DESC LIMIT $localization_sql, $records_by_page";
$stmt = $con->prepare($sql);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows>0) :
echo '<table id="myTable" class="table table-condensed table-hover table-striped bootgrid-table">
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Description</th>
<th>Action</th>
</tr>
</thead>
<tbody>';
$stmt->bind_result($id,$title,$description);
while ($stmt->fetch()) :
echo '<tr>
<td>'.$id.'</td>
<td>'.$title.'</td>
<td>'.$description.'</td>
<td>Edit</td>
</tr>';
endwhile;
echo '</tbody>';
echo '</table>';
$stmt->close();
$sql = "SELECT * FROM news";
$stmt = $con->prepare($sql);
$stmt->execute();
$stmt->store_result();
$BD_records = $stmt->num_rows;
$stmt->close();
$con->close();
$total_page = ceil($BD_records / $records_by_page);
$prev = $page - 1;
$next = $page + 1;
echo '<div class=pagination>
<ul class="pagination">';
//add amount_show to each request
if ($prev > 0) :
echo "<li><a href='pagination.php?page=1&amount_show=$records_by_page'><i class='icon-angle-double-arrow'></i></a></li>";
echo "<li><a href='pagination.php?page=$prev&amount_show=$records_by_page'><i class='icon-angle-left'></i></a></li>";
endif;
for ($i=1; $i<=$total_page; $i++) :
if ($page==$i) :
echo "<li><a class=active>". $page . "</a></li>";
else :
echo "<li><a href='pagination.php?page=$i&amount_show=$records_by_page'>$i</a></li>";
endif;
endfor;
if ($page < $total_page ) :
echo "<li><a href='pagination.php?page=$next&amount_show=$records_by_page'><i class='icon-angle-right'></i></a></li>";
echo "<li><a href='pagination.php?page=$total_page&amount_show=$records_by_page'><i class='icon-angle-double-right'></i></a></li>";
endif;
echo '</ul></div>';
else :
$stmt->close();
endif;
?>
</div>
</div>

Related

How do I populate a second table based on the rowID from the first table in a modal on the same page?

I have two tables in a SQLite DB. The second table contains information about the first.
The first table is loaded in a modal table with buttons to a second modal table in which I would like to load information from the second SQlite table based on the rowID from the first.
I have attempted several things but none of them worked, I assume because JS only gets executed when loading the page, but I can't figure out a way to work around this.
I left comments about the things I tried in the code.
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
<button type="button" class="btn btn-info" data-toggle="modal" data-target="#modal1">View</button>
<!-- begin modal1 -->
<div class="modal" id="modal1">
<div class="modal-dialog">
<div class="modal-content">
<table class="table table-bordered table-striped">
<thead>
<tr class="btn-primary">
<th>id.</th>
<th>text1</th>
</tr>
</thead>
<tbody>
<?php
$db = new PDO('sqlite:db.sqlite'); // I know this is unsafe, but it works and it's for a local page.
$qry1 = $db->prepare("SELECT * FROM table1");
$qry1->execute();
$i = 1;
while ($row = $qry1->fetch(PDO::FETCH_ASSOC)) {
$Query1ID[$i] = $row['id']; //If I know what row I'm selecting I could use it to find the correct variable in the next query, but I can only find this with JS and don't know how to combine these.
?>
<tr>
<td onclick="clicked(<?php echo $i; ?>)"><button type="button" class="btn btn-primary mybutton" data-toggle="modal" data-target="#modal2" data-row-val="<?php echo $row['id']; ?>"><?php echo $row['id']; ?></button></td>
<!-- with onclick I can find out what row I clicked and in combination with $Query1ID[$i] I should be able to get the correct variable in the new query. But I don't know how to combine them. -->
<td><?php echo $row['table1_text']; ?></td>
<?php
$i++;
}
?>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<!-- end modal1 -->
<!-- begin modal2 -->
<div class="modal" id="modal2">
<div class="modal-dialog">
<div class="modal-content">
<table class="table table-bordered table-striped">
<thead>
<tr class="btn-primary">
<th>id.</th>
<th>Entries for <span id="rowvarfromJS">empty</span></th> <!-- I can call the variable but can not use it in the query. -->
</tr>
</thead>
<tbody>
<?php
$db = new PDO('sqlite:db.sqlite');
//function if clicked = 3 newID = $Query1ID[3] //something like this would solve my problem
$newID="$Query1ID[10]";
echo $newID;
echo "<script>var javascriptVar = '199';</script>";
echo "<script>if (nr == 2){alert('execute php?')}</script>";
$phpVar = "<script>document.writeln(javascriptVar);</script>";
echo "phpvar=$phpVar";
//$qry2 = $db->prepare("SELECT * FROM table2 WHERE fortable1ID = $newID"); //This works, if only I could use the JS var from the clicked function to find the correct variable.
//$qry2 = $db->prepare("SELECT * FROM table2 WHERE fortable1ID = $phpVar"); //This does not work even though $phphvar contains the correct value.
$qry2 = $db->prepare("SELECT * FROM table2 WHERE fortable1ID = '199'");
// I need this static 199 to be $row['id']; from the previous query.
// I have attempted using rowvarfromJS for that but that doesn't work.
// I can use AJAX and complete the query on another page, but I do not know how to use JS reply to generate a new table.
$qry2->execute();
$i2 = 1;
while ($row = $qry2->fetch(PDO::FETCH_ASSOC)) {
?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['table2text']; ?></td>
<td><?php echo "$Query1ID[4]"; ?></td> <!-- I can use this variable in a query, but I do not know how to select the correct one.-->
</tr>
<?php
$i2++;
}
?>
</tbody>
</table>
</div>
</div>
</div>
<!-- end modal2 -->
<!-- javascript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
//This was an attempt to get the rowID with JS. It works, but I can't use the variable in the query.
$(function () {
$(".mybutton").click(function () {
var my_row_value = $(this).attr('data-row-val');
$("#modal2").attr('data-row-value',my_row_value );
alert('My Row Value '+my_row_value ); //If I could only use this value in the query.
let rowvarfromJS = my_row_value;
document.getElementById("rowvarfromJS").innerHTML = rowvarfromJS;
})
});
//Gets clicked row number. If I know the clicked row number then I should be able to find the correct php variable for the next query, but I don't know how to do this.
function clicked (nr) {
let rcfromJS = nr;
console.log('Clicked from row: ' + rcfromJS);
}
//I have also attempted using AJAX to pass the JS variable to another PHP and get the result back, which works, but the result is in JS and I don't know how to create a table from that.
</script>
</body>
</html>
Most attempts are written as comments in the code. Aside from those I also tried using Ajax, but the problem with that is that I am using a JS variable to get a JS variable and I don't know how to use that to populate the modal table.
var data = {
'var1': "199",
'var2': "test."
};
$.ajax({
type: 'post',
url: 'executesecondquery.php',
data: data,
timeout: 50000
}).done(function(response) {
console.log(response); //can I use this response to populate the second table?
}).fail(function(error) {
// uh-oh.
});
executesecondquery.php
<?php
$db = new PDO('sqlite:db.sqlite');
$qry2 = $db->prepare("SELECT table2text FROM table2 WHERE fortable1ID = '$var1'");
$qry2->execute();
$i2 = 1;
while ($row = $qry2->fetch(PDO::FETCH_ASSOC)) {
echo $row['table2text'];
$i2++;
}
?>

AJAX: sending xmlhttp request in PHP loop but result is not dynamic

I have a table that is given based on the option selected in a . This table generates list of students based on class selected. I want a dynamic modals popup each time the SMS button on a student row is clicked it is suppose to show the related parent's name dynamically. It's actually doing this but the issue is it is not dynamic one i refresh the page the data for the first student button clicked is what shows as response for every other one. until i refresh again. I select another and it shows thesame for every other student
Though when i used develop tool(network) in browser the xmlrequest was sent sucessfully and the interesting thing is the passed "id" param for the selected student is correct. but it just showing the same one that's selected first in the modal popup after refresh
the code looks like this
`
function smsmodal(id){
var data= {"id" : id};
jQuery.ajax({
url : '/sms/include/smsmodal.php',
method : "post",
data : data,
success: function(data){
jQuery('body').append(data);
jQuery('#sms-modal').modal('toggle');
},
error: function(){
alert("Something went wrong")
}
});
}
`
And for the loop:
<?php
require_once '../../service/mysqlcon.php';
$parentID = $_POST['parentID'];
$selected = sanitize($_POST['selected']);
$studentquery = $conn->query("SELECT * FROM students WHERE class = '$parentID' ORDER BY lastname");
$count = mysqli_num_rows($studentquery);
$i = 1;
ob_start(); ?>
<?php
if($count < 1){
?>
<br><br>
<h4 class="text-warning text-center bg-warning" style="padding:20px">No student has been registered in this class.</h4>
<?php
}else{
?> ...... other html..
<div class="table-responsive">
<table class="table table-hover">
<thead><th><input type="checkbox"> Roll</th><th>Photo</th><th>Student Name</th><th>Address</th><th>Actions</th></thead>
<tbody>
<?php while($s = mysqli_fetch_assoc($studentquery)) :?>
<tr>
<td><input type="checkbox"> <?=$i;?></td>
<td> <img src="<?=$s['photo'];?>" alt="photo" class="img-responsive" id="photo"></td>
<td><?php echo $s['lastname'].' '.$s['firstname'];?></td>
<td><?=$s['address'];?></td>
<td><button class="btn btn-success btn-xs" type="button" onclick="smsmodal(<?=$s['id']; ?>)" style="width:80px"><span class="fa fa-mobile"></span> SMS</button> </td>
</tr>
<?php $i++;?>
<?php endwhile; ?>
</tbody>
</table>
</div>
<?php } ?>
<?php echo ob_get_clean(); ?>

Getting #hashtag tweet count in PHP while loop

I am creating the web application of twitter #hashtag search where I want to integrating the following code.
https://github.com/henrahmagix/tweetCount/blob/master/total_tweets.html
(Note : Just copy/paste above code for getting demo)
The above link contains the code for getting the number of tweets for any search (Useful for hashtag trending).
And following is my code:
<table width="100%">
<tr>
<th>#Hashtag</th>
<th>Description</th>
<th>Tags</th>
<th>Participants</th>
</tr>
<?php
$i = 1;
$j = 1;
while ($row = mysqli_fetch_array($result)):
?>
<tr>
<td class="hashtd"><?php echo "#" . $row['hashtag']; ?></td>
<td class="hashtd"><?php echo $row['description']; ?></td>
<td class="hashtd">Show</td>
<td class="hashtd">
<script type="text/javascript">
submitTerms("<?php echo $row['hashtag']; ?>","1","0");
</script>
<div id="totalTweets">Total tweets: <span></span></div>
<div id="loading">Loading!</div>
<div id="pagesDone">Pages done: <span></span></div>
</td>
</tr>
<?php
$i++;
$j++;
endwhile;
?>
</table>
Here I am using tweetCount script for this :
<td class="hashtd">
<script type="text/javascript">
submitTerms("<?php echo $row['hashtag']; ?>","1","0");
</script>
<div id="totalTweets">Total tweets: <span></span></div>
<div id="loading">Loading!</div>
<div id="pagesDone">Pages done: <span></span></div>
</td>
In the tweetCount script they are using form and searching for one keyword after submitting the form and getting the tweetcount result from http://search.twitter.com/search.json?q=
But I want to call that on page load thats why I am calling the submitTerms() function for getting the real time tweet count. Because of I am calling script in while loop I cannot use "id" for totalTweet, loading and pagesDone div tag. I tried by adding "class" there but it's resulting same tweet count finally for all hashtag which is not correct.
Hope you get this. Need Help.
I recommend you to fork the total_tweets.html ans do some modifications to the JS code. This way you can pass a param to specify the #id div you want to target.
// total_tweets function
function getTweets(search, page, pageTotal, **hashtag**) {
$.getJSON( url + search + '&page=' + page + '&callback=?',
function(data) {
if( data.results.length != 0 && page != pageTotal ) {
$('#pagesDone'** + hashtag + **' span').html(page);
getData(data);
}
else {
showTotal(**hashtag**);
}
}
);
}
function showTotal(**hashtag**) {
$('#totalTweets'** + hashtag + **' span').html(beforeCounter + totalTweets + afterCounter);
$('#pagesDone'** + hashtag + **' span').html('0');
totalTweets = 0;
loading = false;
}
function submitTerms(**hashtag**) {
$('#totalTweets'** + hashtag + **' span').html('');
$('#pagesDone'** + hashtag + **' span').html('0');
search = encodeURIComponent($('#query').prop('value'));
page = $('#startPage').prop('value');
pageTotal = $('#pageTotal').prop('value');
if( search == '' ) {
alert('Please enter search query');
return;
}
if( page == 0 ) {
alert('0 not allowed as start page');
return;
}
loading = true;
getTweets(search, page, pageTotal, **hashtag**);
}
Then in your php file you would call it:
<td class="hashtd">
<script type="text/javascript">
**submitTerms("<?php echo $row['hashtag']; ?>");**
</script>
<div id="totalTweets<?php echo $row['hashtag'];">Total tweets: <span></span></div>
<div id="loading<?php echo $row['hashtag'];">Loading!</div>
<div id="pagesDone<?php echo $row['hashtag'];">Pages done: <span></span></div>
</td>

pass jquery variable to php page and receive calculated variable to first page

I have a generated table which i need when press button on 6th column to get 1st cell value in the row and send it to an overlay page, the overlay page will do some calculations which will take some time and show a score, i want to replace the 6th column button with that score.
I cant get page2.php to show in the over lay while processing (i use popup from here)
here is what i reached so far
<tbody>
<?php foreach ($rows as $row_number => $columns): ?>
<?php
$row_class = 'row-' . ($row_number + 1);
if ($row_number == 0) {
$row_class .= ' row-first';
}
if (count($rows) == ($row_number + 1)) {
$row_class .= ' row-last';
}
?>
<tr class="<?php print $row_class; ?>">
<?php foreach ($columns as $column_number => $item): ?>
<td class="<?php print 'col-'. ($column_number + 1); ?>" >
<?php print $item; ?>
</td>
<?php endforeach; ?>
<td>
<?php print $dnsearch; ?>
</td>
<td>
<button id="my-button">Get Score</button>
<div id="element_to_pop_up">
<a class="bClose">x<a/>
here should page2.php receive the variable from script and do the processing and return data (score) to replace the clicked button
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<script type="text/javascript">
$(":button").click(function (e) {
e.preventDefault();
$('#element_to_pop_up').bPopup();
$.post("page2.php", {val: $(this).closest('tr').find('td:eq(0)').text()}, function(returned_data){
// alert(returned_data);
$(e.target).closest("td").text(returned_data); // to replace button with score
});
});
</script>
on click of the button send the value of the first row to jquery and make a ajax call to second page and do the required calculations when ever by response of second page replace the button with result look for examples.
http://api.jquery.com/jQuery.ajax/
put your button in a span like this
<span id="result">
<button id="my-button">Get Score</button></span>
then in your response handling jquery put this
$("#result").html(you calculation result jquery variable);

How to apply sorting and filtering using Ajax Json PHP & MySQL

Hi i am a beginner i am working on software site. i have built all the pages and layout for the site that was the easy part done using HTML CSS AND JAVASCRIPT alone, only thing left is to make main categories pages for different software which is tough for me.
i want to to add sorting option on category pages like this (See Here)
where user shall be able to sort software according to date, name, date added etc. and also be able to control max number of software to display like 20, 30, 100 etc.
On my HTML Page i have these div's in which i want to display data (different softwares)
from MySQL database "security_software" (it is a testing database) from table "internet_security" (it is a testing table)
HTML Div's
<div class="category-container">
<div class="category-image"></div>
<div class="category-desc">#<p>text</p></div>
<div class="rating5" >Editors' rating: </div>
<div class="category-download-btn">Download</div>
<div class="category-buy-btn">Buy</div>
</div>
After Some research i have got a solution to use JSON AJAX PHP &MySQL
JAVASCRIPT Code i have
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$.ajax({
url: 'ajax.php',
dataType: 'json',
success: function(response){
data = '';
$.each(response,function(i,val){
data = '<div class="category-image">'+val.image+'</div>'+
'<div class="category-link">'+val.id+'</div>'+
'<div class="category-desc"><p>'+val.description+'</p> </div>'+
'<div class="rating5" >'+val.rating+'</div>'+
'<div class="category-download-btn">Download</div>'+
'<div class="category-buy-btn">Buy</div>';
$('<div>').attr('id',i).html(data).appendTo('#response');
});
}
});
</script>
</head>
<body>
<div id='response'></div>
</body>
PHP Code i have
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'root', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("security_software", $con);
$sql="SELECT * FROM internet_security ORDER by `".$q."` DESC" ;
$result = mysql_query($sql);
$response = array();
$i=0;
while($row = mysql_fetch_array($result))
{
$response[$i]['id'] =$row['id'];
$response[$i]['title'] = $row['title'];
$response[$i]['image'] = $row['image'];
$response[$i]['description'] = $row['description'];
$response[$i]['rating'] = $row['rating'];
$response[$i]['download'] = $row['download'];
$response[$i]['buy'] = $row['buy'];
$i++;
}
mysql_close($con);
echo json_encode($response);
?>
Now it is not working at all as i dont have any place to attach these codes for (categories drop down) in javascript i have.
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="id">id</option>
<option value="title">title</option>
<option value="image">image</option>
<option value="description">description</option>
<option value="description">rating</option>
<option value="download">download</option>
<option value="buy">buy</option>
</select>
</form>
Please help me guys where can i attach these code and how to get it working, i am totally confused.
First thing worth noting is, if you are going to display tabular data... Use a table! It will make things a lot easier for you.
Secondly. Build your code and table as if Ajax did not exist. Initially populate the data using PHP on the page your displaying the data. Then, hook up the column header's so they link to your page, but passing which column you want to sort by and also which direction.
i.e.
<?
$column = (isset($_GET["column"]) ? $_GET["column"] : 'id');
$direction = (isset($_GET['direction']) ? $_GET['direction'] : 'asc');
$con = mysql_connect('localhost', 'root', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("security_software", $con);
$sql="SELECT * FROM internet_security ORDER by '".$column."' " . $direction;
$result = mysql_query($sql);
$response = array();
$i=0;
while($row = mysql_fetch_array($result))
{
$response[$i]['id'] =$row['id'];
$response[$i]['title'] = $row['title'];
$response[$i]['image'] = $row['image'];
$response[$i]['description'] = $row['description'];
$response[$i]['rating'] = $row['rating'];
$response[$i]['download'] = $row['download'];
$response[$i]['buy'] = $row['buy'];
$i++;
}
mysql_close($con);
?>
<div id="content">
<table>
<thead>
<tr>
<td>ID</td>
<td>Title</td>
<td>Rating</td>
<td>Download</td>
</tr>
</thead>
<tbody>
<? foreach($response as $i => $row) : ?>
<tr>
<td><?= $row['id']; ?></td>
<td><?= $row['title']; ?></td>
<td><?= $row['rating']; ?></td>
<td><?= $row['download']; ?></td>
</tr>
<? endforeach; ?>
</tbody>
</table>
</div>
The above code would go inside a single PHP file, without any other HTML etc. Then, on the page you want to display this table, you simply <? include('path-to-file.php'); ?> include it.
Finally... At the top of the page you are displaying the table on, you would put:
<?
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
include('path-to-file.php');
die();
}
?>
The above code would then detect an Ajax request and serve only the table with the data in the new order.
You would then need to use Javascript to replace the table with the new HTML via
$('#content table thead a').live('click', function(e)
{
e.preventDefault();
$.ajax(
{
url : $(this).attr('href'),
success : function(resp)
{
$('#content').html($(resp).html());
},
error : function()
{
alert('There was a problem sorting your table...');
}
});
});
where resp is the variable that contains your Ajax response.
Note: This is just a very simple and crude (oh, and untested) way to handle the situation. You would need to improve it your self to prevent any security related issues such as SQL Injection.

Categories