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

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;

Related

PHP/Ajax page navigation url change

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;
?>

AJAX not functioning

I have been staring at this for literally two hours trying to fix it. Any help would be appreciated. For some reason the table isn't being loaded when the button is clicked.
Here's the relevant part of my head:
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css" />
</head>
This is my table:
<div class="container">
<div class="midtxt">
<div id = "transactions-sav" style="margin-top: 0;">
<h2>Most Recent Transactions</h2>
<table>
<thead>
<tr>
<th>Username</th>
<th>Amount</th>
<th>Time & Date</th>
<th>Account Type</th>
</tr>
</thead>
<tbody>
<div id="trans-div">
</div>
</tbody>
</table>
<hr />
</div>
</div>
<a class="btn light-blue waves-effect waves-light table-end" id="trans-more" style="margin-top: 35px;">Load More Transactions</a>
</div>
This is my Ajax transmitter:
<script>
$(document).ready(function() {
let transCount = 20;
$('#trans-more').on('click', function() {
transCount += 20;
console.log('click');
console.log(transCount);
$('#trans-div').load('includes/loadtranshistajax.inc.php', {transNewCount: transCount,user_id: <?php echo $_SESSION['user_id']; ?>}, function() {
console.log('callback');
});
});
console.log('test1');
});
</script>
This is my PHP script for generating the table. It is worth noting that initialize() starts a session.:
<?php
require_once 'dbc-stu.inc.php';
require_once 'initialize.inc.php';
require_once 'app/transactions/transhist.inc.php';
initialize();
initialize_secure();
//Import the count
$limit = $_POST['transNewCount'];
$userID = $_SESSION['user_id'];
$sql = "SELECT * FROM transactions WHERE trans_targetID ='$userID' ORDER BY trans_time DESC LIMIT $limit";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
while ($row = mysqli_fetch_assoc($result)) {
echo '<tr>';
foreach ($row as $key => $value) {
if ($key === 'trans_time') {
$time = $value;
date_default_timezone_set("America/Los_Angeles");
$time = date("F j, Y, g:i a",$time);
} elseif ($key === 'trans_amount') {
$amnt = $value;
} elseif ($key ==='trans_targetID') {
$username = idToUsername($value);
} elseif ($key === 'trans_accType') {
$accType = $value;
}
}
echo '<td>' . $username . '</td>';
echo '<td>' . $amnt . '</td>';
echo '<td>' . $time . '</td>';
echo '<td>' . $accType . '</td>';
echo '</tr>';
}
Edit, thanks a lot everybody. I'm fairly new to the web development community, so it's cool to see everyone help out!
Remove div tag from tag and add id in tbody attribute as below.
<tbody id="trans-div"></tbody>
Put the php code<?php echo $_SESSION['user_id']; ?> inside a <script> tag into double quote as it's causing the SyntaxError which break` your script code.
That's why you are not able to view XHR into console
Try the following:
$('#trans-div').load('includes/loadtranshistajax.inc.php', {transNewCount: transCount,user_id: "<?php echo $_SESSION['user_id']; ?>"}, function() {
console.log('callback');
});

Asynchronously place data into a dynamically produced div

I have a link that sends a query string to a PHP file that returns data from a Mysql server as JSON. I want to put this JSON data into a DIV that has an ID which matches the query string sent to the PHP file.
Here is my PHP generated Link and DIV
<html>
<head>
<title>BadNoise</title>
</head>
<body>
<form action="Artisttest.php" method="post">
<fieldset>
<p> <input type="submit" value=" Search Our Artists" /> </p>
</fieldset>
</form>
<?php
$con=mysqli_connect("localhost","ee2800","secret","ee2800");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if($_SERVER["REQUEST_METHOD"] == "POST")
$result = mysqli_query($con,"SELECT * FROM artist LIMIT 10");
if($_SERVER["REQUEST_METHOD"] == "POST")
echo " <h2>List of BadNoise Artists</h2>
<table border='0'>
<tr>
<th>Artist Number</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Search Songs</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['ArtistNumber'] . "</td>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo '<td> <a class="dynamic" href="test4.php?name='. urlencode($row['ArtistNumber']).'">Search Songs</a></td>';
echo "<td><div id=" . $row['ArtistNumber'] . "></div></td>";
echo "</tr>";
}
echo "</table>";
$results->close();
mysqli_close($con);
?>
<script type="text/javascript" src="jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="general.js"></script>
</body>
Here is the PHP file that returns the JSON data
<?php
$row = $_GET['name'];
echo $_GET['name'];
$dbs = new mysqli("localhost", "ee2800", "secret", "ee2800");
$results = $dbs->query("SELECT * FROM songs WHERE ArtistNumber = {$_GET['name']};");
$rows = array();
while ($r = mysqli_fetch_array($results))
{
$rows[] = $r;
}
echo json_encode($rows);
?>
And here is my attempt at doing this asynchronously with JS.
$(function() {
$("a.dynamic").click(function(e) {
e.preventDefault();
var destDiv = $(this).closest('tr').find('td').last().find('div[id]');
$.getJSON( this.href, function(obj){
$.each(obj, function(key, value) {
destDiv.append("<p>"+value.Title+"</p>");
});
});
});
});
I think I am on the right path but am having trouble targeting the DIV.
Is this what you meant?
</tr><tr><td>1</td><td>Steve</td><td>Perry</td><td> <a id="dynamic" href="test4.php?name=1">Search Songs</a></td></tr><td><div id=1></div></td>
Since you're adding the content on the same row where the click originated, you may not need the id of the div in order to add the content there. Using the link that was clicked determine the parent tr using .closest() the drill down to the div using .find() and .last().
And since you're likely to have multiple links I would recommend using a class .dynamic instead of an id. <td> <a class="dynamic" href="test4 ....
This should do it:
$(function() {
$("a.dynamic").click(function(e) {
e.preventDefault();
var destDiv = $(this).closest('tr').find('td').last().find('div[id]');
$.getJSON( this.href, function(obj){
$.each(obj, function(key, value) {
destDiv.append("<p>"+value.Title+"</p>");
});
});
});
});
UPDATE
The above code has been edited to include DOM ready.
Concept verification --> with DOM ready clicking a a.dynamic link does not navigate to the link.

Filters from database in PHP

echo 'Qname : <select id ="selector">';
$s = mysql_query('SELECT qid,qname FROM q_table ORDER BY qname');
while($row = mysql_fetch_array($s))
{
$filter = $row['qname'];
$filterid = $row['qid'];
echo '<option value='.$filterid.'>'.$filter.'</option>';
echo '</select>';
echo '<div id='.$filterid.' class="colors" style="display:none;">';
echo '<table>
<tr><th>USERID</th>
<th>QNAME</th>
</tr>';
$publishedqnames = mysql_query('SELECT qid, qname, quserid FROM pub_q');
while($row = mysql_fetch_array($publishedqnames))
{
$qid = $row['qid'];
$qname = $row['qname'];
$quserid = $row['quserid'];
echo '<tr>
<td>'.$quserid.'</td>
<td>'.qname.'</td>
</tr>';
}
echo '</table></div>';
}
when I select qname, the div of that selected filter(filter and qname are same) needs to get displayed
JQUERY FILE
$(function()
{
$('#selector').change(function(){
$('.colors').hide();
$('#' + $(this).val()).show();
});
});
Rightnow Iamn't able to display the correct qid with correct div
Try this
echo 'Qname : <select id ="selector">';
$s = mysql_query('SELECT qid,qname FROM q_table ORDER BY qname');
while($row = mysql_fetch_array($s))
{
$filter = $row['qname'];
$filterid = $row['qid'];
echo '<option value='.$filterid.'>'.$filter.'</option>';
}
echo '</select>';
?>
<script>
$(function()
{
$('#selector').change(function(){
$('.colors').hide();
$('#' + $(this).val()).show();
});
});
</script>
<?php
echo '<table>
<tr><th>USERID</th>
<th>QNAME</th>
</tr>';
$publishedqnames = mysql_query('SELECT qid, qname, quserid FROM pub_q');
while($row = mysql_fetch_array($publishedqnames))
{
$qid = $row['qid'];
$qname = $row['qname'];
$quserid = $row['quserid'];
echo '<div id='.$filterid.' class="colors" style="display:none;">';
echo '<tr>
<td>'.$quserid.'</td>
<td>'.qname.'</td>
</tr>';
echo '</div>';
}
echo '</table>';
please let me know if not working

show my result in a selected div

I have this form:
<FORM id="frmVote" action="../vote_dir/proccess.php" method="post">
<table id="tblMain" align="center">
<tr>
<td class="header"></td>
</tr>
<tr>
<td>
<?php
include "../vote_dir/loadpoll.php";
?>
</td>
</tr>
<tr>
<td>
<input id="votefor" name="votefor" type="hidden"/>
</td>
</tr>
<tr>
<td class="button">
<INPUT class="btnVote" onclick="return confirmSubmit()" type="submit" value="vote"/>
</td>
</tr>
<tr>
<td class="footer"></td>
</tr>
</table>
</FORM>
and this is part of the proccess.php:
<?php
$votefor = $_POST["votefor"];
//Get the IP of the user
$domain = $_SERVER["REMOTE_ADDR"];
$today = date("m/d/Y");
echo "<table id=\"tblResults\" align=\"center\">";
//MORE CODE
// Generate the results table
$doc = new DOMDocument();
$doc->load("../vote_dir/xml/results.xml");
$pollitems = $doc->getElementsByTagName("pollitem");
foreach( $pollitems as $pollitem )
{
$entries = $pollitem->getElementsByTagName("entryname");
$entry = $entries->item(0)->nodeValue;
$votes = $pollitem->getElementsByTagName("votes");
$vote = $votes->item(0)->nodeValue;
$tempWidth = $vote / $maxvotes;
$tempWidth = 300 * $tempWidth;
$votepct = round(($vote / $maxvotes) * 100);
echo "<tr><td width=\"45%\" class=\"polls\">$entry</td>";
echo "<td width=\"35%\" class=\"resultbar\"><div class=\"bar\" style=\"background-color: ";
getRandomColor();
echo "; width: $tempWidth px;\">$votepct%</div></td><td class=\"each_vote\" width=\"20%\">($vote votes)</td></tr>";
}
echo "<tr><td width=\"45%\" class=\"total\" colspan=\"3\">Σύνολο ψήφων: $maxvotes</td>";
echo "</table>";
?>
Like it is now it works fine. but I am trying to make it load my results in a specific div instead of opening the results like
I am trying to use this jquery (that I used in other things), it is working partialy since it opens the results in the div but it seems it doesn't sent the form into the proccess.php since I can see the result page without any change or message e.g "You have already voted".
.delegate('.btnVote', 'click', function(){
var keyValues = {
votefor : $(this).parent().find('input[name="votefor"]').val()
};
$.post('../vote_dir/proccess.php', keyValues, function(rsp){
$('#voting').load('../vote_dir/results.php');
});
return false;
})
this is my loadpoll.php
<?php
// Load the results xml file
$doc = new DOMDocument();
$doc->load("../vote_dir/xml/results.xml");
$root = $doc->getElementsByTagName("results")->item(0);
$question = $root->getAttribute("question");
echo "<table id=\"tblPoll\" align=\"center\"><tr><td class=\"question\">$question</td></tr>";
echo "<tr><td class=\"pollitem\">";
$pollitems = $doc->getElementsByTagName("pollitem");
$id = 1;
// Loop through each item, and create a radio button for each item
foreach( $pollitems as $pollitem )
{
$entries = $pollitem->getElementsByTagName("entryname");
$entry = $entries->item(0)->nodeValue;
$votes = $pollitem->getElementsByTagName("votes");
$vote = $votes->item(0)->nodeValue;
if ($id==1)
echo "<input id=\"entry$id\" class=\"radiobutton\" onclick=\"setVote('$entry')\" type=\"radio\" name=\"poll\" value=\"$entry\">$entry<br>";
else
echo "<input id=\"entry$id\" onclick=\"setVote('$entry')\" type=\"radio\" name=\"poll\" value=\"$entry\">$entry<br>";
$id = $id + 1;
}
echo "</td></tr>";
echo "</table>";
?>
$('.btnVote').live('click', function () {
$.post('../vote_dir/savevote.php', { votefor: $.trim($(this).parents('form').find('input[name="votefor"]').val()) }, function (data) {
$('#voting').html(data);
//Or
//$('#voting').load('../vote_dir/results.php');
});
return false;
});
Try changing the
$(this).parent().find('input[name="votefor"]').val()
to
$('#votefor').val()
I think the "$(this).parent()" leads to the <td>
Try this:
var data = $(this).parent().find('input[name= votefor]').val();
or
$data = $(this).parent().find('input[name= votefor]').val();

Categories