Neither tablesorter nor dataTables working with ajax - php

I have tried both, tablesorter and datatables in order to get sorting functionalities. With both, I'm able to see the sorting arrows (and filter box, pages... with dataTables; although they don't work neither), and they change, but the data are not sorted.
Here is the ajax (with dataTables it's the same but using 'dataTable' instead of 'tablesorter'.
$.ajax({
type: "GET",
url: "search.php",
data: {data : encrypted.data, salt: enc_salt},
success: function(enc_response){
var response = decrypt_cryptojs(enc_response, encrypted.salt);
var data = JSON.parse(response);
$("#search_result").html(data);
// Initialise tablesorter
$('#search_table').tablesorter();
}
});
I create the table with php:
if (mysqli_num_rows($result) > 0) {
$message .= "<table id='search_table' class='tablesorter'>
<thead><tr>
<th id='search_user'>Usuario</th>
<th id='search_name'>Nombre</th>
<th id='search_surnames'>Apelidos</th>
<th id='search_email'>Correo</th>
<th id='search_role'>Rol</th>
<th id='search_access'>Acceso</th>
<th id='search_center'>Centro</th>
<th id='search_edit'></th>
<th id='search_delete'></th>
</tr></thead>";
while ($row = mysqli_fetch_row($result)) {
// Define $id
$id = $row[7];
// Replace space(" ") whith "&#32" to avoid errors inside functions
$user = str_replace(" ", "&#32", $row[0]);
$name = str_replace(" ", "&#32", $row[1]);
$surnames = str_replace(" ", "&#32", $row[2]);
$center = str_replace(" ", "&#32", $row[6]);
$message .= "<tbody><tr>
<td>" . $row[0] . "</td>" .
"<td>" . $row[1] . "</td>" .
"<td>" . $row[2] . "</td>" .
"<td>" . $row[3] . "</td>" .
"<td>" . $row[4] . "</td>" .
"<td>" . $row[5] . "</td>" .
"<td>" . $row[6] . "</td>" .
"<td>" .
"<input type='image' src='../resources/edit.png' id='edit_" . $row[0] . "' class='edit' onclick=edit_user(\"$user\",\"$name\",\"$surnames\",'$row[3]','$row[4]','$row[5]',\"$center\",'$id') title='Editar'></button>" .
"</td>" .
"<td>" .
"<input type='image' src='../resources/delete.png' id='delete_" . $row[0] . "' class='delete' onclick=delete_user('$user','$row[4]') title='Eliminar'></button>" .
"</td>
</tr>";
}
$message .= "</tbody></table>";
$message .= "<div id='modify_panel'></div>";
}
And after that:
// Encode the message using json
$response = json_encode($message);
// Encrypt the response and send it.
$enc_response = encrypt_cryptojs($response, $salt);
echo $enc_response;
With datatables I can see message saying that I have an invalid json response.
"#search_result" is in a php file that is included into another php file.
What I'm doing wrong?
Thank you.
EDIT: I've found the stupid mistake, I was generating several tbodys. If I move the tag outside the while, it works. Sorry.

It looks like the problem is likely in the encoding and processing of the JSON.
JSON cannot be merely a string. It needs to be wrapped in an array or object, so when you use php json_encode make sure it's getting an array
// Encode the message using json
$response = json_encode(array($message));
Note: I don't know php that well, so this example might be wrong.
Now in the javascript, make sure to get the data from the first element of the array
var data = JSON.parse(response)[0];
Now the data should be ready to be added as HTML.
$("#search_result").html(data);

Related

PHP SQL Returning only one result

Im trying to migrate my website from my local wamp project to my live server for testing, everything is working fine on my local site but on my live site the following code only returns one result. There are definitely multiple SQL entries that meet the sql query criteria. Any suggestions?
$opentickets = $db->query("SELECT tID, id, date, userid, category, department FROM ticket WHERE userid = '$_SESSION[id]' AND status='Open'");
if(count($opentickets) > 0) {
echo "<h2>Your open tickets:</h2>";
echo "<table class='table table-striped'>
<tr>
<th>Ticket</th>
<th>Date Submitted</th>
<th>Category</th>
<th>Department</th></tr>";
$o = $opentickets->fetch(PDO::FETCH_ASSOC);
echo "<tr><td><a href='ticket.php?id=" . $o['tID'] . "'>" . $o['tID'] . </td>";
echo "<td>" . $o['date'] . "</td>";
echo "<td>" . $o['category'] . "</td>";
echo "<td>" . $o['department'] . "</td></tr>";
echo "</table>";
}
else
{
echo "<h2>You have no open tickets</h2>";
}
You are not itterating over the results of your query, you are just fetching the first row...
Please reference to the examples on the PHP Website on how to do this.
I have just changed your code below, please check for the manuals for more information
while($o = $opentickets->fetch(PDO::FETCH_ASSOC)){
echo "<tr><td><a href='ticket.php?id=" . $o['tID'] . "'>" .$o['tID'] . </td>";
echo "<td>" . $o['date'] . "</td>";
echo "<td>" . $o['category'] . "</td>";
echo "<td>" . $o['department'] . "</td></tr>";
}

Displaying Image From URL Stored in SQL Databse Using PHP

I'm trying to display images from a SQL Database (using an URL in the DB) in a table.
I'm still pretty new to this type of implementation so I've been giving it my best shot and trying to do research but haven't found much on using URLs (opposed to using BLOBs or directly adding images to the Database). I definitely WANT to keep my images on a file system. Currently my code only displays the URL (obviously) but I have tried a few things..
I have tried:
-Passing $row["card_image"] to a PHP variable $image and using $image->load()
-Using "<img src="$row["card_image"]">" (I imagined since I was getting a link output still this could work...)
-I have also tried a few other solutions that I've found on Stack Overflow but I believe these have mostly been for use with BLOB data types and so they also failed to produce the output I desire (I.E.
"<img src="data:image/jpeg;base64,'.base64_encode($image->load())'" />"
Here is my current code:
SQL (I have condensed the fields to save space)
CREATE TABLE cards (
card_image VARCHAR(999)
);
insert into cards (card_image)
values ('http://localhost/dbztc/wp-content/uploads/2016/04/1.jpg');
PHP
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
if(!$conn)
{
die("connection failed");
}
//Table
echo "
<table cellpadding=\"0\" cellspacing=\"2\" border=\"0\" width=\"100%\">
<tr bgcolor=\"#666666\">
<td colspan=\"5\" align=\"center\"><b><font color=\"#FFFFFF\">" . $table[0] . "</font></td>
</tr>
<tr>
<td>Image</td>
<td>Card Number</td>
<td>Card Rarity</td>
<td>Card Name</td>
<td>Card Type</td>
<td>Card Style</td>
<td>Card Text</td>
</tr>";
$sqlquery = "SELECT card_image, card_number, card_rarity, card_title, card_type, card_style, card_text FROM cards";
$result = mysqli_query($conn, $sqlquery);
//$image = $row["card_image"];
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<td>" . $row["card_image"] . "</td>" . "<td>" . $row["card_number"]. "</td>" . "<td>" . $row["card_rarity"] . "</td>" . "<td>" . $row["card_title"] . "<td>" . $row["card_type"] . "</td>" . "<td>" . $row["card_style"] . "</td>" . "<td>" . $row["card_text"] . "</td></tr>";
}
} else {
echo "0 results";
}
echo "</table>";
mysqli_close($conn);
Instead of:
<td>" . $row["card_image"] . "</td>
Try:
$image = $row["card_image"]; // the image url
<td><img src='". $image . "'></td>
For anyone who stumbles upon this and may be having this same problem:
For starters, I took the entire URL out of the database entry and replaced it with the Filename only.
Afterwards, I edited my code like this:
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<td>" . "<img src ='../images/" . $row["card_image"] . "'>" . "</td>" . "<td>" . $row["card_number"]. "</td>" . "<td>" . $row["card_rarity"] . "</td>" . "<td>" . $row["card_title"] . "<td>" . $row["card_type"] . "</td>" . "<td>" . $row["card_style"] . "</td>" . "<td>" . $row["card_text"] . "</td></tr>";
echo "<br />";
It now displays perfectly. Just as a note, this was done on a live server opposed to local so that could maybe also have an impact? Not sure, but hopefully this can help someone!

Use Buttons In Table - PHP

I'm following through a tutorial from a book I have but want to add some extra columns to a table. I have added the columns, buy and sell, and in each of those I want to display a button. I am unsure of how to do this, is it possible?
Here's my code from the page with the table:
<?php // Example 21-9: members.php
include_once 'header.php';
if (!$loggedin) die();
echo "<div class='main'>";
$con=mysqli_connect("localhost","root","usbw","stocktrading");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM stocks");
echo "<table border='1 '>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
<th>Buy</th>
<th>Sell</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['price'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['price'] . "</td>";
echo "<td><input type='radio' name='buysell' value='buy'></td>";
echo "<td><input type='radio' name='buysell' value='sell'></td>";
echo "</tr>";
Something like this will add radio buttons. Use checkboxes or another kind of button if you prefer.
I know that you must be a new programmer, but there's some cool things that you can use for avoid string concatenation. String concatenation sometimes can make your code messy and unreadable, and it's not cool.
You can use HEREDOC for avoid concatenation(please, avoid concatenation). Also, when using HEREDOC or double quotes " you can use {} to access array keys or object attributes.
i.e with HEREDOC:
// Guys, look, it's a HEREDOC, it make the HTML more readable :)
$html = <<<EOF
<tr>
<td>{$row['id']}</td>
<td>{$row['name']}</td>
<td>{$row['price']}</td>
<td><button>Sell</button><td>
<td><button>Buy</button><td>
</tr>
EOF;
i.e with double quotes ":
$html = "<tr>
<td>{$row['id']}</td>
<td>{$row['name']}</td>
<td>{$row['price']}</td>
<td><button>Sell</button><td>
<td><button>Buy</button><td>
</tr>";
But, if i need to call some functions?
sprintf or printf can be the solution
spritnf: returns a string produced according to the formatting string format.
printf: prints a string produced according to the formatting string format.
i.e:
$str = sprintf("My name is <b>%s</b>", ucfirst("i am not procrastinating"));
echo $str;
//OR
printf("My name is <b>%s</b>", ucfirst("i am not procrastinating"));
Or using an template way(may be hard) using str_replace, array_keys and array_values.
$template = "My name is <b>:name:</b>, i'm from :from:.";
$templateVars = array(
":name:" => "I am not procrastinating",
":from:" => "Brazil"
);
echo str_replace(array_keys($templateVars),array_values($templateVars),$template);
Happy Coding.
Sorry for the English, but i'm Brazilian, and we don't speak English, not even Spanish haha.
just add the button inside the td
echo "<tr>".
"<td>" . $row['id'] . "</td>" .
"<td>" . $row['name'] . "</td>" .
"<td>" . $row['price'] . "</td>" .
'<td><button>Sell</button><td>' .
'<td><button>Buy</button><td>' .
"</tr>";

SQL removing data from an array depending on field value

I'm still quite new to this and have come across a problem I have been looking through a lot of tutorials and cannot figure a way to get over the problem.
I have a select query getting data out of my sql database however I need the data to be custom for each user who accesses it, so need to add a further query, I have a cookie read in with the user value '$user' and there is a collumn in the database that isnt put into the table however need to check that if the collumn 'privacy' has a value set as '1' and the $user is not the investigator of that row discard and do not put into the table. however populate with all data that isn't set to privacy='1' or is set to privacy=1 and the investigator='$user'
$sql="SELECT * FROM evidence WHERE $evidencevariable = '".$evidencespecify."'";
$result = mysql_query($sql);
if($result === FALSE) {
die(mysql_error());}
echo "<table class='sortable' border='1' id='table'>
<thead><tr>
<th>Id</th>
<th>Case Id</th>
<th>Investigator</th>
<th>Evidence Type</th>
<th>Created</th>
<th>Modified</th>
<th>LS</th>
<th>PS</th>
<th>Length</th>
<th>Importance</th>
<th>Information</th>
</tr></thead><tbody>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Id'] . "</td>";
echo "<td>" . $row['Case_ID'] . "</td>";
echo "<td>" . $row['Investigator'] . "</td>";
echo "<td>" . $row['Evidence_Type'] . "</td>";
echo "<td>" . $row['Created'] . "</td>";
echo "<td>" . $row['Modified'] . "</td>";
echo "<td>" . $row['LS'] . "</td>";
echo "<td>" . $row['PS'] . "</td>";
echo "<td>" . $row['Length'] . "</td>";
echo "<td>" . $row['Importance'] . "</td>";
echo "<td>" . $row['Information'] . "</td>";
echo "</tr>";
}
echo "</tbody></table>";
How can I get around this problem do I need to add more to the select statement at the beginning or is there a way of querying the array to remove the data before its put into the table?
Any help would be appreciated!
It seems you can easily modify the sql to something like:
$sql="SELECT * FROM user WHERE $evidencevariable='$evidencespecifiy' AND (Privacy=0 or (Privacy=1 AND investigator='$user'))";

PHP data entry (SQL)

I have a form that posts to a PHP page. This is a snippet of the page. The goal is to read out a SQL table and then you click on the text values and they are editable. You then edit them and submit and it updates the SQL table. I basically need a way to strip the letter from the beginning of the id. but the letter is important because it defines in what column the new information goes into. Also if there is a different language or method to do this, I am open to suggestions.
<script type="text/javascript">
function exchange(id){
var ie=document.all&&!window.opera? document.all : 0
var frmObj=ie? ie[id] : document.getElementById(id)
var toObj=ie? ie[id+'b'] : document.getElementById(id+'b')
toObj.style.width=frmObj.offsetWidth+7+'px'
frmObj.style.display='none';
toObj.style.display='inline';
toObj.value=frmObj.innerHTML
}
</script>
<?php
$result = mysqli_query($con,"SELECT * FROM List") or die(mysql_error());
var_dump($_POST);
echo "<table id=list>
<tr id='list_header'>
<th class='list'>ID</th>
<th class='list'>Description</th>
<th class='list'>Winner</th>
</tr><form name='edit' action='inde.php?id=prizes' method='post'>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td class='list'><span id='n" . $row['Number'] . "' onclick='exchange(this.id)'>" . $row['Number'] . "</span><input name='n" . $row['Number'] . "b' id='n" . $row['Number'] . "b' class='replace' type='text' value='" . $row['Number'] . "' style='display:none;'></td>";
echo "<td class='list'><span id='d" . $row['Number'] . "' onclick='exchange(this.id)'>" . $row['Description'] . "</span><input name='d" . $row['Number'] . "b' id='d" . $row['Number'] . "b' class='replace' type='text' value='" . $row['Description'] . "' style='display:none;'></td>";
echo "<td class='list'><span id='w" . $row['Number'] . "' onclick='exchange(this.id)'>" . $row['Winner'] . "</span><input name='w" . $row['Number'] . "b' id='w" . $row['Number'] . "b' class='replace' type='text' value='" . $row['Winner'] . "' style='display:none;'></td>";
echo "<td></td>";
echo "</tr>";
}
echo "</table><input type='submit' value='Save Changes'></form>";
?>`
From what I understand you have a string id and you want to do the following:
if(strlen($id)>1){
$important=substr($id, 0, 1); //that gets the important stuff
$id = ($id, 1, strlen($id)); //that's id without the first char
}
else{
$important=$id;
$id=""; //empty string
}
You may want to try Ajax to send the modified values to the server one by one instead of all together at the end.

Categories