Hello everyone I need some help with this:
I´m a total noob in php and javascript and I´m facing a little problem here , I´m working with a website that displays a list on the left side and then when I do a click on an element it shows a subelement then when I do a click on the subelement it displays a table that contains info stored in a mysql database, it works flawlessly but the data shown sometimes displays like 5000 rows so it's annoying to be scrolling all the way down 5000 rows, so I decided to paginate the results to be able to just show like 100 elements per page.
Now when I click on the link to show the next 100 rows it takes me to another page and my menu on the left disappears!
I´m using something like this to navigate through the results:
$centerPages = "";
$sub1 = $pn - 1;
$sub2 = $pn - 2;
$add1 = $pn + 1;
$add2 = $pn + 2;
if ($pn == 1) {
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' ' . $add1 . ' ';
}
else if ($pn == $lastPage) {
$centerPages .= ' ' . $sub1 . ' ';
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
}
else if ($pn > 2 && $pn < ($lastPage - 1)) {
$centerPages .= ' ' . $sub2 . ' ';
$centerPages .= ' ' . $sub1 . ' ';
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' ' . $add1 . ' ';
$centerPages .= ' ' . $add2 . ' ';
}
else if ($pn > 1 && $pn < $lastPage) {
$centerPages .= ' ' . $sub1 . ' ';
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' ' . $add1 . ' ';
}
My guess is that because the next and back links are an <a href> tags it loads a new page showing the next 100 rows.
How can I prevent that??
I tried to use a jquery adding a preventDefault(); to those <a href="' . $_SERVER['PHP_SELF'] tags, it worked but now nothing happend on those links xD.
Help me please.
Thanks in advance.
I hope that this example helps you. Its not refreshing the url. So your menu link be opened
you can create pagination link like this
$results = mysqli_query($connecDB,"SELECT COUNT(*) FROM paginate");
$get_total_rows = mysqli_fetch_array($results); //total records
//break total records into pages
$pages = ceil($get_total_rows[0]/$item_per_page);
//create pagination
$pagination = '';
if($pages > 1)
{
$pagination .= '<ul class="paginate">';
for($i = 1; $i<$pages; $i++)
{
$pagination .= '<li>'.$i.'</li>';
}
$pagination .= '</ul>';
}
?>
and here is script for pagination
$(document).ready(function() {
$("#results").load("fetch_pages.php", {'page':0}, function() {$("#1-page").addClass('active');}); //initial page number to load
$(".paginate_click").click(function (e) {
$("#results").prepend('<div class="loading-indication"><img src="ajax-loader.gif" /> Loading...</div>');
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]); //clicked_id[0] holds the page number we need
$('.paginate_click').removeClass('active'); //remove any active class
//post page number and load returned data into result element
//notice (page_num-1), subtract 1 to get actual starting point
$("#results").load("fetch_pages.php", {'page': (page_num-1)}, function(){
});
$(this).addClass('active'); //add active class to currently clicked element
return false; //prevent going to herf link
});
});
and here fetching Pages
<?php
include("config.inc.php"); //include config file
//sanitize post value
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
//validate page number is really numaric
if(!is_numeric($page_number)){die('Invalid page number!');}
//get current starting point of records
$position = ($page_number * $item_per_page);
//Limit our results within a specified range.
$results = mysqli_query($connecDB,"SELECT id,name,message FROM paginate ORDER BY id DESC LIMIT $position, $item_per_page");
//output results from database
echo '<ul class="page_result">';
while($row = mysqli_fetch_array($results))
{
echo '<li id="item_'.$row["id"].'">'.$row["id"].' <span class="page_name">'.$row["name"].'</span><span class="page_message">'.$row["message"].'</span></li>';
}
echo '</ul>';
?>
Related
I want to separate a list of 30 articles, into chunks of 5.
For this purpose, I wrote the following code:
private static function makeChunk($array = array(), $howMany = 5) {
$shortChunked = array_chunk($array, $howMany);
$count = count($shortChunked);
$html = '';
$i = 0;
foreach ($shortChunked as $key => $chunk) :
$class = '';
if ($key == 0)
$class = ' first active';
if ($key == ($count - 1) && $count>1)
$class = ' last';
$html .= '<div class="my-chunk chunk'.$class.'">';
foreach($chunk as $article) {
if ($i == 0) {
$img = '<img class="img-responsive" src="' . $article['image'] . '" alt="' . $article['imageAlt'] . '" />';
} else {
$img = '<img class="img-tab-ll img-responsive" src="' . get_template_directory_uri() . '/img/imageLoading.gif" data-src="' . $article['image'] . '" alt="' . $article['imageAlt'] . '" />';
}
}
$html .= '</div>';
$i++;
endforeach;
return $html;
}
This is working just fine, but Im considering also lazy loading the first chunk.
I noticed that if I also lazy load the first chunk, images are not showing up, unless I press the button to load the next series (next chunk), so it seems to me that Im missing something related to ajax/lazyload.
Any advises?
I want to put select2 function in my code but don't know where to put that .select2() function
i have this .append($(<?php echo json_encode($property_address1); ?>))
my model `
function property_address1()
{
$query = $this->db->query('SELECT host,price,city,property_thumbnail, apartments_type, contactnumber, contactperson,photographlinks,emailid, propertyaddress FROM tbl_contacts')->result();
$output = '<select id="neww" class="property_add_ form-control">';
foreach ($query as $row)
{
//echo $row->location;
$output .= "<option value='". $row->propertyaddress ."'";
$output .= " data-propertyaddress='" . $row->propertyaddress ."'" ;
$output .= " data-host_name='" . $row->host ."'" ;
$output .= " data-apartments_type ='" . $row->apartments_type."'" ;
$output .= " data-city ='" . $row->city."'" ;
$output .= " data-property_thumbnail='" . $row->property_thumbnail."'" ;
$output .= " data-price='" . $row->price."'" ;
$output .= " data-contactperson='" . $row->contactperson ."'" ;
// $output. = $row->pincode.", ".$row->city.", ".$row->location;
$output .= " data-photographlinks='" . $row->photographlinks ."'" ;
$output .= " data-emailid='" . $row->emailid ."'" ;
$output .= " data-contactnumber='". $row->contactnumber . "'>" ;
$output .= $row->host . ' , '.$row->propertyaddress . ' ,'.$row->price. ' ,'.$row->apartments_type. ' , '. $row->contactperson . ' , ' . $row->contactnumber. "</option>";
}
$output .= '</select>';
//var_dump($output);
return $output;
}`
my controller
public function test($id = null)
{
$this->layout->set(
array(
'property_address1' => $this->mdl_quotes->property_address1()
)
);
$this->load->model('mdl_quotes');
$this->layout->buffer('content', 'quotes/test');
$this->layout->render();
}
Dhaval Panchal check this updated screenshot
This is screenshot for better understanding.. please have a look Thanks
Insert CSS & JS file in your page then after JS file insert this code in your page.
<script type="text/javascript">
$(document).ready(function() {
$('#neww').select2();
});
</script>
To update options, see below code.
var option = new Option("text", "id");
$("#neww").append(option);
$("#neww").trigger("change");
I have a script below to pull some data from sql:
<?php
require 'admin-db.php';
// Define and perform the SQL query
$sql = "SELECT `id`, `first_name`, `last_name`, `status_time` "
. "FROM `staffs` ORDER BY `id` DESC";
$result = $DB_CON->query($sql);
// If the SQL query is succesfully performed ($result not false)
if($result !== false) {
$data_row = '<table class="table table-striped tablesorter">'
. '<thead>'
. '<tr>'
. '<th>ID</th>'
. '<th>Fist Name</th>'
. '<th>Last Name</th>'
. '<th>Status Time</th>'
. '</tr>'
. '<tbody>';
foreach($result as $row) {
$data_row .= '<tr>'
. '<td scope="row" class="text-center">'.$row['id'].'</td>'
. '<td>' .$row['first_name'].'</td>'
. '<td>' .$row['last_name'].'</td>'
. '<td><div class="status">' .$row['status_time']. '</div><span class="fa fa-times-circle"></span></td>';
}
}
$data_row .= '</tbody>'
. '</table>';
echo $data_row;
How would I change my script (see below) to compare between the $row['status_time'] and NOW() to indicate if the time different is more than 30 seconds it return 0 and if less than 30 seconds it return a 1 as text in the div class="status"?
<script>
$('.status:contains(">30 seconds") = $this.text(0) else $this.text(1);
</script>
This can be what are you looking for.
// foreach tr row
$.each($('tr .status'), function(i, v) {
// get seconds from date
var seconds = (Date.now() - Date.parse($(v).text()))/1000;
if(seconds) {
(seconds < 30) ? $(this).text('1') : $(this).text('0');
}
});
JSFIDDLE DEMO
I have a webpage which displays rows from a database inside text boxes. I have made buttons one of which when clicked dynamically creates a row with input boxes. So this onClick function written with javascript to create these boxes is not being triggered. The error thrown out by the concole is addInput() not defined.
<?php
include('adodb/adodb.inc.php');
echo ' <h1>\n' .
' Revenue Management Solution\n' .
' </h1>\n';
echo ' <img alt = "mxpresso logo"\n' .
' src = "http://mxpresso.com/images/logo.png"\n' .
' style = "width : 171px; height : 108px;">\n\n';
echo ' <h2>\n' .
' 1. To See existing records\n' .
' </h2>\n';
$db = NewADOConnection( 'mysql' );
$db -> Connect( "127.0.0.1",
"vcc",
"abcd4",
"vcc" );
$sql = "SELECT * FROM rev";
$result = $db->Execute( $sql );
if ( $result === false )
die( "failed2" );
$records = array();
$count = $result -> RecordCount();
echo "Total Records Found :".$count."<br>";
if ( $count > 0 )
{
while ( !$result -> EOF )
{
$offerId = $result -> fields[ 0 ];
$affId = $result -> fields[ 1 ];
$status = $result -> fields[ 2 ];
$deduction = $result -> fields[ 3 ];
echo ' <form action = "updatecopy.php"\n' .
' method = "get"\n' .
' target = "_blank">\n' .
' <div id = "dynamicInput">\n' .
' <table id = "dataTable"\n' .
' class = "form">\n' .
' <tbody>\n' .
' <tr>\n' .
' <td>\n' .
' <input checked = "checked"\n' .
' required = "required"\n' .
' name = "chk[]"\n' .
' type = "checkbox">\n' .
' </td>\n\n';
echo ' <td>\n' .
' <h4>\n' .
' OfferID\n' .
' </h4>\n\n';
echo ' <input name = "update_for_offerid"\n' .
' type = "text"\n' .
' value = ' .
$offerId .
'>\n' .
' </td>\n\n';
echo ' <td>\n' .
' <h4>\n' .
' AffId\n' .
' </h4>\n\n';
echo ' <input name = "update_for_affid"\n' .
' type = "text"\n' .
' value = ' .
$affId .
'>\n' .
' </td>\n\n';
echo ' <td>\n' .
' <h4>\n' .
' deduction :\n' .
' </h4>\n\n';
echo ' <input name = "deduct"\n' .
' type = "text"
' value = ' .
$deduction .
'>\n' .
' </td>\n\n';
echo ' <td>\n' .
' <h4>\n' .
' Status\n' .
' </h4>\n\n';
echo ' <input name = "status"\n' .
' type = "text" ' .
' value = ' .
$status .
'>\n' .
' </td>\n' .
' </tr>\n' .
' </tbody>\n' .
' </table>\n\n';
echo ' <input type = "submit"\n' .
' value = "Update Entry">\n' .
' </div>\n' .
' </form>\n\n';
$rec = array( "offerId" => $offerId,
"affiliate_id" => $affId,
"status" => $status,
"deduction" => $deduction );
array_push( $records,
$rec );
$result->MoveNext();
}
}
echo ' <input type = "button"\n' .
' onClick = "addInput(\'dynamicInput\')"\n' .
' value = "Add another text input">\n\n';
echo ' <script language = "Javascript"\n' .
' type = "javascript">\n' .
' var counter = 1;\n' .
' var limit = 3;\n\n';
echo ' function addInput( divName )\n' .
' {\n' .
' if ( counter == limit )\n' .
' {\n' .
' alert( "You have reached the limit of adding " + counter + " inputs" );\n' .
' }\n' .
' else\n' .
' {\n' .
' var newtable = document.createElement( "dataTable1" );\n' .
' var td1 = document.createElement(\'td\');\n' .
' var td2 = document.createElement(\'td\');\n' .
' var td3 = document.createElement(\'td\');\n'
' var tr = document.createElement( \'tr\' );\n\n';
echo ' td1.innerHTML = \'<h4>Entry</h4>\' + \'<br><input name = "myI" type = "text">\';\n\n';
echo ' td2.innerHTML = \'<h4>Entry</h4>\' + \'<br><input name = "myI" type = "text">\';\n\n';
echo ' td3.innerHTML = \'<h4>Entry</h4> \' + \'<br><input name = "myIn" type = "text">\';\n\n';
echo ' tr.appendChild( td1 );\n' .
' tr.appendChild( td2 );\n' .
' tr.appendChild( td3 );\n\n';
echo ' newtable.appendChild( tr );\n\n';
echo ' document.getElementById( divName ).appendChild( newtable );\n\n';
echo ' counter++;\n' .
' }\n' .
' </script>\n';
?>
I'm too noob to comment, and while this isn't a complete answer, I believe it will send you along your way well enough. If you were to get this page delivered to you in a browser, then "inspect" using the debug tool of your favorite browser, you would likely find that the javascript isn't registered with the browser as a "script" source, but rather just text inside the element that's not displaying cause DOM rules. This of course makes it non-executable, as you would be able to tell since the event isn't firing. addInput() not defined since it's inside a script that's not registered.
This is kind of tricky layering it like this. FWIW, my solution to this kind of thing was to declare a JS script in the caller -> that had a function that created a new page (using JS of course), >that .append 'ed all the elements to the defined script, the "source" of the script being a separate JS file. This also allows me to use the IDE to maintain the script in a separate file.
There are several ways to "post" the script as an element, but it needs to be posted to DOM.
You are missing a >:
echo '<html
javascript is case sensive, it should be onclick not onClick.
I din't really got deeper in your code, but if this doesn't solve it then tell me
So I am making Text based browser game. I have made map where you can move around without refreshing page and updating it with javascript. I have added that it randomly generates bots from database which you can attack, but can't find a way to make it update when you move around the map.
This is the PHP I made to load the bots from database and make then randomly generate.
$sql3 = "SELECT * FROM monsters WHERE botworld='$world'";
$result3 = mysqli_query($conn,$sql3);
$row3=mysqli_fetch_array($result3,MYSQLI_ASSOC);
$rowsbot = array();
while ($rowbot = mysqli_fetch_assoc($result3)) {
$rowsbot[] = $rowbot;
}
for($i=0;$i<count($rowsbot);$i++) {
$a = rand(0,10);
if($a > 5) {
echo "<div class='botres$i'>";
echo "<div class='panel panel-default bot$i'><div class='panel-body bot1$i'>";
echo $i . ". " . $rowsbot[$i]['name'];
echo "<div class='pull-right'><button class='btn btn-default' botid='" . $rowsbot[$i]['id'] ."' botnr='" . $i . "'>Attack</button></div>";
echo "</div></div>";
echo "</div>";
}
}
I added then it automaticly updates the div block when you attack bot. But I want to make bots update when you move around.
I have got the array with data, but don't know how to use it.
var myArray = jQuery.parseJSON('<?php print json_encode($row3); ?>');
console.log(myArray)
Done
var rowsbot = <?php echo json_encode($rowsbot) ?>;
for(i=0; i<rowsbot.length; i++) {
var a = Math.floor((Math.random() * 10) + 1);
if(a>5) {
$(".monsters").append("<div class='botres" + i + "'><div class='panel panel-default bot" + i + "'><div class='panel-body bot1 " + i + "'>" + i + ". " + rowsbot[i].name + "<div class='pull-right'><button class='btn btn-default' botid='" + rowsbot[i].id + "' botnr='" + i + "'>Attack</button></div></div></div></div>");
}
}