A way to merge td's in a table - javascript

So I'm trying to create a weekly calendar.
I coded a loop in javascript creating the empty table and then afterwards modified the innerHTML of the appropriate td's from values taken from an SQL table using php and javascript.
My problem is that when I set the rowspan of the specific td instead of merging with the next td's it is moving them to the end of my table. If I have 2 more reputation points i will post pictures to show my problem.
Here is my code if you want to take a look at it
// Declare usefull information about the database and host
$mysql_host = "-host info-";
$mysql_database = "-database info-";
$mysql_user = "user";
$mysql_password = "pass";
// open the connection
$link = mysql_connect($mysql_host,$mysql_user, $mysql_password, $mysql_database);
// connect to the database
mysql_select_db($mysql_database, $link) or die('database not selected'. mysql_error());
// Select * from the table created in the database
$result = mysql_query("SELECT * FROM Appointment;")
or die("Could not query:" . mysql_error());
echo "<script type='text/javascript' > "
. "var hours = new Array('9:00','9:30','10:00','10:30','11:00','11:30', "
. "'12:00','12:30','13:00','13:30','14:00','14:30','15:00','15:30');"
. ""
. "var days = new Array('Mon','Tue','Wed','Thu','Fri','Sat');"
. ""
. "for ( i = 0; i < 14 ; i++ ) "
. "{"
. "document.write('<tr id='+hours[i]+':00'+'>');"
. "document.write('<th>'+ hours[i]+'</th> '); "
." for ( k = 0 ; k < 6; k++)"
."{"
. "document.write('<td id='+days[k] +'> </td>'); "
. "}"
. "document.write('</tr>');"
."}"
. " </script> ";
while( $row = mysql_fetch_array( $result ))
{
$timestamp = strtotime($row['Date']);
$day = date('D', $timestamp);
$from = $row['StartTime'];
$to = $row['EndTime'];
$rowspan = determinRowSpanBetween($from,$to);
echo "<script type='text/javascript'> "
. " var divToAddTo = GetElementInsideContainer('".$from."','".$day."');"
. "divToAddTo.className = 'busy';"
. "divToAddTo.rowspan='".$rowspan."';"
. "divToAddTo.innerHTML='Something to do';"
. "function GetElementInsideContainer(containerID, childID) {"
. " var elm = {};"
. " var elms = document.getElementById(containerID).getElementsByTagName('*');"
. " for (var i = 0; i < elms.length; i++) {"
. " if (elms[i].id === childID) {"
. " elm = elms[i];"
. " break;"
. " }"
. "}"
. "return elm;"
. "}"
. " </script>" ;
}
the function determinRowSpanBetween is created later on in the code.

Having a rowspan > 1 in a td that is only supposed to take up one space (i.e. one that is not merged with other td's) will cause a whole bunch of errors. Make sure you account for every row you add to rowspan.

Related

Check form for URLs before sending (server side)

I have the following code which checks the form before submitting on the server side, what I would like to include (if possible) is to check the message for URLs and if present to prevent the message from being sent.
if (!empty($_POST['name']) && !empty($_POST['fromemail']) && !empty($_POST['message']) && $go == TRUE)
{
//data has been filled
$name = Filter::no_html($_POST['name']);
$from = Filter::no_html($_POST['fromemail']);
$start_dt = Filter::no_html($_POST['start_dt']);
$end_dt = Filter::no_html($_POST['end_dt']);
$comments = Filter::no_html($_POST['message']);
$validate->isEmpty($name, LANG_JAVASCRIPT_PLEASE_ENTER . " " . LANG_YOUR_NAME);
$validate->isEmpty($from, LANG_JAVASCRIPT_PLEASE_ENTER . " " . LANG_YOUR_EMAIL);
$validate->isSingleEmail($from, LANG_JAVASCRIPT_PLEASE_ENTER_EMAIL);
$validate->isEmpty($start_dt, LANG_JAVASCRIPT_PLEASE_ENTER . " " . LANG_START_DATE);
$validate->isEmpty($end_dt, LANG_JAVASCRIPT_PLEASE_ENTER . " " . LANG_END_DATE);
$validate->isEmpty($comments, LANG_JAVASCRIPT_PLEASE_ENTER . " " . LANG_YOUR_MESSAGE);
$modules->call_hook('contact_owner_submit', ''); // Call any module functions
$id = (int) #$_POST['ownerid'];
$vehicle = (int) #$_POST['listingid'];
if ($validate->isError())
{
You could search the message using the stristr method for certain criteria within the string:
$has_url = (stristr($comments, 'http') || stristr($comments, 'www.'));
if($has_url) {
// prevent submit
}
More info on the stristr method here:
https://www.php.net/manual/en/function.strstr.php
So your code could look like this:
if (!empty($_POST['name']) && !empty($_POST['fromemail']) && !empty($_POST['message']) && $go == TRUE) {
$has_url = (stristr($_POST['message'], 'http') || stristr($_POST['message'], 'www.'));
if($has_url) {
// whatever happens if contains url
}
$name = Filter::no_html($_POST['name']);
$from = Filter::no_html($_POST['fromemail']);
$start_dt = Filter::no_html($_POST['start_dt']);
$end_dt = Filter::no_html($_POST['end_dt']);
$comments = Filter::no_html($_POST['message']);
$validate->isEmpty($name, LANG_JAVASCRIPT_PLEASE_ENTER . " " . LANG_YOUR_NAME);
$validate->isEmpty($from, LANG_JAVASCRIPT_PLEASE_ENTER . " " . LANG_YOUR_EMAIL);
$validate->isSingleEmail($from, LANG_JAVASCRIPT_PLEASE_ENTER_EMAIL);
$validate->isEmpty($start_dt, LANG_JAVASCRIPT_PLEASE_ENTER . " " . LANG_START_DATE);
$validate->isEmpty($end_dt, LANG_JAVASCRIPT_PLEASE_ENTER . " " . LANG_END_DATE);
$validate->isEmpty($comments, LANG_JAVASCRIPT_PLEASE_ENTER . " " . LANG_YOUR_MESSAGE);
$modules->call_hook('contact_owner_submit', ''); // Call any module functions
$id = (int) #$_POST['ownerid'];
$vehicle = (int) #$_POST['listingid'];
if ($validate->isError())
// whatever goes here
{
}

Can not get JQuery auto calculation to work with PHP

I'm trying to achive an auto calculation in JQuery, basicly there are two input fields qty times by unitPrice and the
result should display at dealPrice
input box, the problem I'm facing is the inputs are in a while loop I need to differentiate each of it's ID's so I'm
using ". $row1['prid'] . " in all three classes. There are NO errors but somehow I can NOT get it to work.
$prid = array();
while ($row1 = mysql_fetch_array($result1,MYSQL_ASSOC){
$prid[] = $row1['prid'];
echo "<tr>
<td>".$row1["prdesc"]."</td>
<td><input type='text' class='qty". $row1['prid'] . "' name='epid_qty_". $row1['prid'] ."' value='". $row1['qty'] . "'></td>
<td><input type='text' class='unitPrice". $row1['prid'] . "' name='epid_unitprice_". $row1['unitprice'] ."' value='". $row1['unitprice'] . "'></td>
<td><input type='text' class='dealPrice". $row1['prid'] . "' name='epid_drp_". $row1['prid'] . "' value='". $row1['deal_reg_price'] . "'> </td>";
}
$(document).ready(function(){
var arr = <?php echo '["' . implode('", "', $prid) . '"]' ?>;
var pid = [];
for (var i = 0; i < arr.length; i++) {
pid[i] = arr[i];
}
console.log(pid);
$('input[class="unitPrice'+ pid +'"]').keyup(function()
{
var a = $('input[class="qty'+ pid +'"]').val();
var b = $(this).val();
$('input[class="dealPrice'+ pid +'"]').val(parseInt( a * b));
});
});
Console output of pid;
{["27", "20", "19", ...]}
Your main issue here is that you are setting the pid variable as an array and then trying to use it as if it is not.
To make your code logical, you need to put a for loop around the part of the code where you specify the key-up function. Like this:
for(var i = 0; i < pid.length; i++) {
var pidNo = pid[i];
$('input[class="unitPrice'+ pidNo +'"]').keyup(function(){
var a = $('input[class="qty'+ pidNo +'"]');
var b = $(this).val();
$('input[class="dealPrice'+ pidNo +'"]').val(parseInt( a.val() * b));
});
}

php | Defend move_upload_file or delete files from input[type="file"] using jQuery

I have an input[type="file"] had multiple option. I made it preview function so that user can delete the image by clicking the button before submit. The images are deleted well on browser by remove() function however the problem is the values of input including the deleted images are posted when i submit. I don't know how to delete real value of input.
I've tried to figure it out to delete in the server side.
This is the part of html code.
<div class="col-xs-4 vcenter from-group">
<span class="glyphicon glyphicon-asterisk" style="color:red;"></span><label for="inputScreenshots">스크린샷</label>
<p style="display:inline; padding-left:270px; color:red; font-size: 12px">* 이미지 사이즈 : 800 X 450</p>
<input type="file" id="inputScreenshots" name="inputScreenshots[]" class="form-control" accept="image/*" multiple>
<div id="filenameList" style="width : 400px">
<div id="insertScreenshots" style="margin : 30px; position :relative;">
<input type="hidden" name="screenshots_filename[]" value="<?=$screenshot_urls?>">
</div>
</div>
This is the php code where im trying to defend uploading images.
$ss_upload="false";
if (isset($_POST["del_screenshots"])){
// del_screenshots are images that deleted from client.
$ds_count = $_POST["del_screenshots"];
foreach($ds_count as $del) {
echo "<br/> del_screenshots : ".$del;
}
}
$ss_count = sizeof($_FILES['inputScreenshots']['tmp_name']);
// ss_count is the size of all images including deleted images from input field.
echo "<br/>ss_cout : ". $ss_count;
for ($i = 0; $i < $ss_count; $i++) {
$tmpFilePath = $_FILES['inputScreenshots']['tmp_name'][$i];
$tmp_filename = $_FILES['inputScreenshots']['name'][$i];
// tmp_filename is the posted real file name.
echo "<br/> tmp_filename".$i. " : " .$tmp_filename;
//=========================================================================
for ($j = 0; $j < sizeof($ds_count); $j++) {
// Compare all images name and deleted images name
if (strcmp($ds_count[$j] , $tmp_filename) == 0) {
echo "<br/>".$ds_count[$j] . " == " . $tmp_filename . "==> " ."true";
// The $tmp_filename has to be deleted. not to be uploaded to server.
// $tmp_filename = null;
}else {
echo "<br/>".$ds_count[$j] . " == " . $tmp_filename . "==> " ."false";
// This files are okay to be uploaded to server.
}
}
//=========================================================================
$ext = pathinfo($tmp_filename, PATHINFO_EXTENSION);
// $ext = pathinfo($_FILES['inputScreenshots']['name'][$i], PATHINFO_EXTENSION);
echo "<br/>". $i . " ext (pathinfo) : ". $ext;
if ($ext == "") {
continue;
$ss_upload="false";
}
$newFilePath = uniqid().".".$ext;
if ($screenshots != "") {
$screenshots .= "+";
}
$screenshots .= $newFilePath;
// $screenshots has be uploaded to DB except the deleted images. (ex : uniqFileName.png + uniqFileName.png + .. )
echo "<br/> 1) screenshots : ". $screenshots;
move_uploaded_file($tmpFilePath, $SS_PATH."/".$newFilePath);
$ss_upload="true";
}
I want to defend uploading the deleted images but it is no matter to use unlink() in somewhere. The point is how cant i make the string except the deleted images.
=========================================================================
I suppose there is another way to do in jQuery but i have no idea.
I'll put the code below.
$("#inputScreenshots").change(function(){
$("#filenameList div.notyet").remove();
for(var i = 0, len = this.files.length; i < len; i++){
var file = this.files[i];
var fr = new FileReader();
fr.onload = screenshots_processFile(file);
fr.readAsDataURL(file);
}
});
var screenshots_processFile = function screenshots_processFile(file) {
return (function(file) {
return function(e) {
var div = document.createElement("div");
$(div).addClass("notyet").css({
margin: "30px",
position: "relative"
});
var html = [,'<img src="" width="100%" id="tmp_screenshots">'
,'<button type="button" class="close img-close" aria-label="Close"><span aria-hidden="true">×</span></button>'
].join("");
$(div).append(html);
$(div).find("button").click(function() {
alert("remove");
//=========================================================== * TODO : remove the files in server!
var targetDom = document.getElementById( "filenameList" );
var targetInput = document.createElement("input");
targetInput.setAttribute("name", "del_screenshots[]" );
targetInput.setAttribute("type","hidden");
targetDom.appendChild(targetInput);
alert(file.name);
targetInput.setAttribute("value", file.name);
//===========================================================
$(this).parent().remove();
});
$(div).find("img").attr("src", e.target.result);
$("#filenameList").append(div);
}
})(file)
};
How can i do this? Does anyone have an idea?
-----------------------------------------------------------------------------------------------------------
I solved it like this. I know my code is so dirty :-/
$ss_upload="false";
if (isset($_POST["del_screenshots"])){
$ds_count = $_POST["del_screenshots"];
foreach($ds_count as $del) {
echo "<br/> del_screenshots : ".$del;
}
//echo "<br/> << TEST >>"."<br/>ds_count[0] : " . $ds_count[0] . "<br/>ds_count[1] : " . $ds_count[1] ;
}
$ss_count = sizeof($_FILES['inputScreenshots']['tmp_name']);
echo "<br/>ss_cout : ". $ss_count;
for ($i = 0; $i < $ss_count; $i++) {
$tmpFilePath = $_FILES['inputScreenshots']['tmp_name'][$i];
$tmp_filename = $_FILES['inputScreenshots']['name'][$i];
echo "<br/> tmp_filename".$i. " : " .$tmp_filename;
$ss_del_mode="false";
//=========================================================================
if (isset($_POST["del_screenshots"])) {
for ($j = 0; $j < sizeof($ds_count); $j++) {
if (strcmp($ds_count[$j] , $tmp_filename) == 0) {
echo "<br/>".$ds_count[$j] . " == " . $tmp_filename . "==> " ."true";
$ss_del_mode = "true";
}
}
}
//=========================================================================
$ext = pathinfo($tmp_filename, PATHINFO_EXTENSION);
// $ext = pathinfo($_FILES['inputScreenshots']['name'][$i], PATHINFO_EXTENSION);
echo "<br/>". $i . " ext (pathinfo) : ". $ext;
if ($ext == "") {
continue;
$ss_upload="false";
}
if ($ss_del_mode == "true") {
echo "<br/> ss_del_mode [[[[ " . $ss_del_mode. " ]]]]";
$newFilePath = "";
} else {
$newFilePath = uniqid().".".$ext;
echo "<br/> ss_del_mode [[[[ " . $ss_del_mode. " ]]]]";
}
if ($screenshots != "") {
if ($ss_del_mode != "true"){
echo "<br/> ss_del_mode [[[[ " . $ss_del_mode. " ]]]]". " --> screenshots";
$screenshots .= "+";
}
}
$screenshots .= $newFilePath;
echo "<br/> 1) screenshots (newFilePath) : ". $screenshots;
if ($newFilePath != "") {
move_uploaded_file($tmpFilePath, $SS_PATH."/".$newFilePath);
}
$ss_upload="true";
}

Loading tables of different dimensions in infinite scroll page while minimizing empty space between tables

I have a website where users contribute with content. The content takes form of tables, where every td element is of equal height and width. The different pieces of content have different number of rows and columns. I want to stack these elements in an infinite-scroll webpage. ATM I'm doing this: I construct a table, in it a tr. I load element by element inside tds and count their number of columns. When a certain threshold has been reached, i break the tr and start a new tr. This makes the content elements border eachother sideways, leaving no room between each. However I also want to load the elements in such a way that there is minimal room between elements vertically. How can I do this?
Here is my code. I DO NOT expect to have it rewritten or have new code written for me. This is only to make it clearer to you what I am currently doing.
<?php
$row = 0;
$column = 0;
$maxColumns = 124;
echo "<table><tr>";
$listHandle = fopen('pieces/piecesList', 'r');
while (!feof($listHandle)) {
echo "<td>";
$filename = trim(fgets($listHandle));
$templateHandle = fopen("pieces/" . $filename, 'r');
$thisLine = fgets($templateHandle);
list($lowestX, $highestX, $lowestY, $highestY) = sscanf($thisLine, '%d %d %d %d');
//echo $lowestX . $highestX . $lowestY . $highestY;
$templateTable = "<table id=\"" . $filename . "\" title =\"" . $filename . "\">" . PHP_EOL;
$greenCells = array();
$fileLength = 0;
while (!feof($templateHandle)) {
$thisLine = fgets($templateHandle);
list($thisX, $thisY) = sscanf($thisLine, '%d %d');
$carrier = $thisX . " " . $thisY;
array_push($greenCells, $carrier);
$fileLength++;
}
for ($y = $lowestY; $y <= $highestY; $y++) {
// echo "inside for loop Y \n";
$templateTable = $templateTable . "<tr>" . PHP_EOL;
for ($x = $lowestX; $x <= $highestX; $x++) {
// echo $y . $x;
$templateTable = $templateTable . "<td";
$coordinateExists = FALSE;
for ($i = 0; $i < $fileLength; $i++) {
if ($greenCells[$i] == $x . " " . $y) {
$coordinateExists = TRUE;
break;
}
}
if ($coordinateExists) {
$templateTable = $templateTable . " class=\"green";
if ($x == 0 && $y == 0) {
$templateTable = $templateTable . " markerdot";
}
$templateTable = $templateTable . "\"";
} else if ($x == 0 && $y == 0) {
$templateTable = $templateTable . " class=\"markerdot\"";
}
$templateTable = $templateTable . " x='" . $x . "' y='" . $y . "'>";
$templateTable = $templateTable . "</td>" . PHP_EOL;
}
$templateTable = $templateTable . "</tr>" . PHP_EOL;
}
$templateTable = $templateTable . "</table> </td>";
if ($column == 0) {
$tallestTemplateHeight = $highestY - $lowestY;
} else if (($highestY - $lowestY) > $tallestTemplateHeight) {
$tallestTemplateHeight = $highestY - $lowestY;
}
echo $templateTable;
$column += $highestX - $lowestX;
if ($column >= $maxColumns) {
$row += $tallestTemplateHeight;
echo "</tr></table><table><tr>";
}
}
fclose($listHandle);
?>
</div>
PS: I am open to discarding my current setup entirely.
I'll throw this out as an idea - FIDDLE
It uses divs instead of a table, and by playing with the loops, width, etc, you can adjust it as you see fit.
Everything fits together edge to edge.
JS
var counter = 0;
var numdivs = 8;
$('#clickme').click(function(){
for(var i=1; i < 50; ++i)
{
$("<div class='standarddiv'>X</div>").appendTo('.holder');
counter = counter + 1;
if(counter==numdivs)
{
$("<div class='clearboth'></div>").appendTo('.holder');
counter = 0;
}
}
});

Can't retrieve data from localhost tith ajax request and php script

I cannot retrieve the <p> elements that i echo in my php script. I'd like a solution / correction similar to mine because next to the data retrieve i have to style the <p> nodes with a javascript function. I'll be glad if my page doesn't refresh.
PHP:
<?php
$username = "root" ;
$database = "leaderboard" ;
$host = "localhost" ;
$connection = mysql_connect ( $host, $username ) or die ( "Impossibile stabilire connessione con il database della classifica!" .mysql_error() ) ;
mysql_select_db( $database ) or die ( "Impossibile trova il database!" .mysql_error() ) ;
if ( mysql_select_db( $database ) )
{
$SQL = "SELECT name, point FROM records ORDER BY point LIMIT 10"
$result = mysql_query($SQL);
$i = 0 ;
while ( $db_field = mysql_fetch_assoc($result) )
{
echo '<p id="echo"' + $i '>' + db_field[ 'name' ] ; + '. . . . ' + db_field[ 'punti' ] + '</p>' ;
$i = $i + 1 ;
}
}
else
{
print "Database NOT Found ";
}
mysql_close( $connection );
?>
Ajax request(i cannot use jQuery)
function leaderboard( oggetto )
{
alert ( " PROVO A LANCIARE LA RICHIESTA PER LA CLASSIFICA " ) ;
// Ajax sinc.
var http_request = new XMLHttpRequest() ;
http_request.open( "GET" , "./PhpScript/read_from_db.php?", false ) ;
http_request.send( null ) ;
// Here will come the style settings later
alert( document.getElementById( "echo0" ) ) ;
return ;
}
I'll be glad to recive a solution with no refreshing page, or an alternative way to solve the problem, both without jquery because of the project specs.
The quoting in your echo statement is wrong:
echo '<p id="echo"' + $i '>' + db_field[ 'name' ] ; + '. . . . ' + db_field[ 'punti' ] + '</p>' ;
should be:
echo '<p id="echo' . $i '">' . db_field[ 'name' ] ; . '. . . . ' . db_field[ 'punti' ] + '</p>' ;
$i has to be inside the quotes around the ID. And the concatenation operator in PHP is ., not +.

Categories