I have a screen like this:
notifications example
And it deletes the row, but only from the screen. Because if I refresh then it appears back again. I am not sure how to delete it from the actual array.
The array is taken out of a csv file- and I know how to add it back in etc. But what I don't know is deleting rows from the array.
Heres what I have:
// Grabs the csv file (and its existing data) and makes it into an array so the new data can be added to it.
$Notifications = array();
$lines = file('data/AdminNotifications.csv', FILE_IGNORE_NEW_LINES);
foreach ($lines as $key => $value)
{
$Notifications[$key] = str_getcsv($value);
}
echo array2table(array_reverse($Notifications));
// FUNCTION ---------------------------------------------------------------------
//This converts an array to a table
function array2table($array, $recursive = false, $null = ' ')
{
// Sanity check
if (empty($array) || !is_array($array)) {
return false;
}
if (!isset($array[0]) || !is_array($array[0])) {
$array = array($array);
}
// Start the table
$table = "<table>\n";
// The header
$table .= "\t<tr>";
// Take the keys from the first row as the headings
foreach (array_keys($array[0]) as $heading) {
}
$table .= "</tr>\n";
// The body
foreach ($array as $row) {
$table .= "\t<tr>" ;
foreach ($row as $cell) {
$table .= '<td>';
/*
if($cell ==0 && $heading==1){
$cell = $cell.": ";
}
*/
$details = $cell;
// Cast objects
if (is_object($cell)) { $cell = (array) $cell; }
if ($recursive === true && is_array($cell) && !empty($cell)) {
// Recursive mode
$table .= "\n" . array2table($cell, true, true) . "\n";
} else {
$table .= (strlen($cell) > 0) ?
htmlspecialchars((string) $cell) :
$null;
}
$table .= '</td>';
}
$table .= '<td>';
$table .= '<input type="submit" value="Delete" onclick="deleteRow(this)" name="delete"/>';
$table .= '</td>';
$table .= "</tr>\n";
}
$table .= '</table>';
return $table;
}
//If the delete button is pressed, then it does this.
if (isset($_POST['delete'])) {
}
?>
//What happens when it is pressed. (This is javascript)
<script>
function deleteRow(btn) {
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
}
</script>
Any help would be greatly appreciated. I am not too sure whether I can delete a row using javascript? Or in php and java...
Thanks
Php being a server side language will execute only on server. When you are pressing delete button here a javascript function is being called which is actually deleting your row just from client side as it's a client side language that means it actually exist yet on server in that file that's why when you refresh it shows again.
Now you can make an ajax call or place that delete button inside a form to post that request to server to actually delete that.
//If the delete button is pressed, then it does this.
if (isset($_POST['delete'])) {
$arr_index = $_POST['delete']; //you need to pass the row number
unset($array[$arr_index]);
}
Related
I tried to show products if it's available ok added to cart else it show me an alert. if the main window is opened without use AJAX it's works fine but when I **
** for Sorting Item when I use sortby(AJAX) if the item available ok it works add to cart link but if the product is not available when I click it stuck which not do anything, I think the problem with the onClick="*****" but I can't solve it.
I tried many times but I can't solve it.
Thanks for help this is my code.
if (isset($q) || isset($p)) {
$sql="SELECT * FROM product WHERE cat='3'".$q.$p;
$output = '';
$result = mysqli_query($conn,$sql);
while ($row = mysqli_fetch_assoc($result)) {
$output .= '<img src="'.get_image($row['pro_image']).'">';
if ($row['product_status']=='1') {
$output .= '<span>Add to Cart</span>';
} else {
$output .= '<a onclick="return alert("Out of stock!")"><span>Add to Carth</span></a>';
}
} // end while
echo $output;
}
I have this code that you add as a list, I want only 3 elements to be shown and make the rest appear by clicking on the * show more * button.
$printstring .= '<ol>';
foreach ($rows as $bid) {
$printstring .= '<li>';
if ($bid->bidder_url != "" && $customcontact = "") {
$printstring .= ''.$bid->bidder_name.'';
} else {
$printstring .= $bid->bidder_name;
}
$printstring .= ' bid '.$currencysymbol.number_format($bid->current_bid_price, 2, '.', ',').' on '.get_date_from_gmt($bid->date);
//if ($bid->bid_type == "auto") $printstring .= ' [auto]';
$printstring .= '</li>';
}
$printstring .= '</ol>';
I found that it can be done with js but I don't see how to join both (php and js).
$(function() {
var numToShow = 3;
var moreLi;
$('ul').children('li').hide().each(function() {
if ($(this).index() < numToShow) {
$(this).show();
}
}).parent('ul').append('<li>More</li>');
$('#showMore').click(function() {
moreLi = $(this).parent('li');
moreLi.siblings().show();
moreLi.remove();
});
});
You have to understand that PHP works in backend (in the webserver) and JS works in frontend (in your web browser). Basically, JS should send a request (you could learn about sending requests with Ajax) to PHP, and PHP should return a response to be printed by JS.
If you are new in this kind of scenario, it might be confusing at first. I encourage you to learn about how to send a request with Javascript and parse the response :)
Make a for($i = 0;$i...... then when $i= 4 echo 'Show more...';break;
It should work
I have currently implemented a live search (search as you type) function on text fields. The flow is something like this.
Call a .js file inside the page.
Set the id of the text field to "client-search".
Inside the .js file it is currently listening for on key up events of the "client-search" text field.
If the on key up event is fired, the .js file calls a PHP file that searches the database and returns the output as a list item in an unordered list underneath the "client-search" text field.
This setup currently works but how do implement it in multiple fields inside a single page, since it works using "id" and obviously I can't have multiple IDs in a single page.
HTML:
<div class="input-group">
<input type="text" id="client-search" class="form-control" placeholder="Search for manager...">
<ul class="livesearch" id="client-result" onclick="clickResult()"></ul>
</div>
JS
/* JS File */
// Start Ready
$j(document).ready(function() {
// Icon Click Focus
$j('div.icon').click(function(){
$j('input#client-search').focus();
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#client-search').val();
$j('b#search-string').text(query_value);
if(query_value !== ''){
$j.ajax({
type: "POST",
url: "clientsearch.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#client-result").html(html);
}
});
}return false;
}
$j("input#client-search").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$j("ul#client-result").fadeOut();
}else{
$j("ul#client-result").fadeIn();
$j(this).data('timer', setTimeout(search, 100));
};
});
});
PHP:
<?php
$serverName = "(local)";
$connectionInfo = array( "Database"=>"CMS");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
} else {
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$html = '';
$html .= '<li value="myLi" class="myLi">';
$html .= '<small>nameString</small>';
$html .= '<small></small>';
$html .= '</li>';
$search_string = $_POST['query'];
//$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
if (strlen($search_string) >= 1 && $search_string !== ' ') {
$sql = "SELECT TOP 10 ClientName FROM Client WHERE ClientName LIKE '%" . $search_string . "%'";
$params = array($search_string);
$stmt = sqlsrv_query( $conn, $sql);
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$results_array[] = $row;
}
if (isset($results_array)) {
foreach ($results_array as $result) {
$display_function = $result['ClientName'];
$display_name = $result['ClientName'];
$output = str_replace('nameString', $display_name, $html);
//$output = str_replace('functionString', $display_function, $output);
echo($output);
}
}else{
$output = str_replace('nameString', '<b>No Results Found.</b>', $html);
$output = str_replace('functionString', 'Sorry :(', $output);
echo($output);
}
}
?>
I have this function which shows all my articles titles from 'Articles' database.
function show()
{
database();
$sql = "SELECT title FROM `Articles`";
$titleSql = mysql_query( $sql ) or die("Could not select articles:");
$html = '<html><body><div class="container"><h2>Basic List Group</h2><ul class="list-group">';
while ($title = mysql_fetch_array($titleSql)) {
$html .= '<li class="list-group-item">'.$title["title"].'</li>';
}
$html .= '</ul></div></body></html>';
echo $html;
// die("Functie terminata cu succes! :)");
// die(json_encode(array("mesaj" => "Entered data successfully ")));
}
This is the function in javascript.
function show()
{
var n = $('#show').val()
$.post("functions.php", {show:n}).done(function(mesaj){
alert(mesaj);
});
}
PROBLEM: because of the alert(mesaj), it shows the string $html into a pop-up, not on my main window, as I wish!
HOW can I modify my functions so the articles list will show on m window?
you have to give a container id to which it will set the data. Bellow i put it in document.
function show()
{
var n = $('#show').val()
$.post("functions.php", {show:n}).done(function(mesaj){
$(document).html(mesaj);
});
}
I tried to find a way to just get a particular rows using PHPExcel. After searching on the internet, I cannot figure it out on my own. What I want to do is to list all the rows that have a "I1/027" as a column content.
For example:
Hours | Place | Name
------|-------|-----------------
3 |I1/027 | example1 //------> Want to add it to my list!!!
6 |I2/025 | example2 //------> Ignore this
7 |I1/030 | example3
2 |I1/027 | example4 //------> Want to add it to my list!!!
Here's the code without the rows filter, it shows all the excel rows:
<?php if(isset($_FILES['file']['name'])) { ?>
<!-- Container progress bar -->
<div id="progress" style="width:500px;border:1px solid #ccc;"></div>
<!-- progress info -->
<div id="information" style="width"></div>
<?php require_once 'reader/Classes/PHPExcel/IOFactory.php';
//Extra functions
function get_cell($cell, $objPHPExcel){
//Cell selection
$objCell = ($objPHPExcel->getActiveSheet()->getCell($cell));
//taking cell value
return $objCell->getvalue();
}
function pp(&$var){
$var = chr(ord($var)+1);
return true;
}
//==========Displaying Code
$name = $_FILES['file']['name'];
$tname = $_FILES['file']['tmp_name'];
$type = $_FILES['file']['type'];
if($type == 'application/vnd.ms-excel')
{ // excel 97 extension
$ext = 'xls';
}
else if($type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
{ // excel 2007 and 2010 extensions
$ext = 'xlsx';
}else
{ // invalid extension
echo -1;
exit();
}
$xlsx = 'Excel2007';
$xls = 'Excel5';
//read creator
$objReader = PHPExcel_IOFactory::createReader($$ext);
//loading
$objPHPExcel = $objReader->load($tname);
$dim = $objPHPExcel->getActiveSheet()->calculateWorksheetDimension();
// put $start and $end array
list($start, $end) = explode(':', $dim);
if(!preg_match('#([A-Z]+)([0-9]+)#', $start, $rslt)){
return false;
}
list($start, $start_h, $start_v) = $rslt;
if(!preg_match('#([A-Z]+)([0-9]+)#', $end, $rslt)){
return false;
}
list($end, $end_h, $end_v) = $rslt;
//starting to read excel doc
$table = "<table class='tabla'>";
for($v=$start_v; $v<=$end_v; $v++){
// calculate progress bar
$percent = intval($v/$end_v * 100)."%";
// progress bar update
echo '<script language="javascript">
document.getElementById("progress").innerHTML="<div style=\"width:'.$percent.';background-color:#ddd;\"> '.$percent.'</div>";
document.getElementById("information").innerHTML="'.$v.' files processades.";</script>';
// buffer flush
echo str_repeat(' ',1024*64);
// send exit to navigator
flush();
sleep(0.25);
//horizontal reading
$table .= "<tr>";
for($h=$start_h; ord($h)<=ord($end_h); pp($h)){
$cellValue = get_cell($h.$v, $objPHPExcel);
$table .= "<td>";
if($cellValue !== null){
$table .= $cellValue;
}
$table .= "</td>";
}
$table .= "</tr>";
}
$table .= "</table>";
// process completed
echo '<script language="javascript">document.getElementById("information").innerHTML="Procés complet"</script><br>';
echo $table;
}?>
</div>
Thanks a lot in advance!!
Solution: Here you just need to use simple logic. Change your horizontal reading code like following:
//horizontal reading
$tempRow= "<tr>";
$contentFound=false;
for($h=$start_h; ord($h)<=ord($end_h); pp($h)){
$cellValue = get_cell($h.$v, $objPHPExcel);
$tempRow.= "<td>";
if($cellValue !== null){
if($cellValue=="I1/027") $contentFound=true;
$tempRow.= $cellValue;
}
$tempRow.= "</td>";
}
$tempRow.= "</tr>";
if($contentFound) $table.=$tempRow;
Logic: I just stored the row in to temp var and compared row's each cell value to desired content. If it matched then I set $contentFound to ture, and added temp row to main table ($table var). In next loop of vertical reading again $tempRow and $contentFound will set to original state, so finally desired rows will be in our output.
Note: As per my knowledge there is no inbuilt search function in PHPExcel.