How to delete an item into an array with a button - php

I have a code with an array that saves what i need each time I press a button, so these items saved into an array I showed later with a erase buttons, but I don't know how to delete it, so there is the part of the code that shows what I meant:
echo "<table border=1>";
echo "<tr class='tabPreciosTitles'>";
echo "<td>Nom Activitat</td>
<td>Nom Tipus Activitat</td>
<td>Tipus Tarifa</td>
<td>Temps/km</td>
<td>Preu</td>";
echo "</tr>";
for ($x=0;$x<count($savedArray[4]);$x++){
echo "<tr>";
echo " <td>".$savedArray[0][$x]."</td>";
echo " <td>".$savedArray[1][$x]."</td>";
echo " <td>".$savedArray[2][$x]."</td>";
echo " <td>".$savedArray[3][$x]."</td>";
echo " <td>".$savedArray[4][$x]."</td>";
echo " <td><input type='submit' onclick='eliminar(".$savedArray[0][$x].",".$savedArray[1][$x].",".$savedArray[2][$x].",".$savedArray[3][$x].",".$savedArray[4][$x].")' class='carritoElim' value='elim'></td>";
echo "</tr>";
}
a pic with all the forms:
the other pic that shows the items on the array:
Anyone knows how to delete the selected row that references the item on the array with the delete button? Thanks

In the client side, the following code works.
for ($x=0;$x<count($savedArray[4]);$x++){
echo '<tr id="line' . $x . '">';
echo " <td>".$savedArray[0][$x]."</td>";
echo " <td>".$savedArray[1][$x]."</td>";
echo " <td>".$savedArray[2][$x]."</td>";
echo " <td>".$savedArray[3][$x]."</td>";
echo " <td>".$savedArray[4][$x]."</td>";
echo " <td><input type='submit' onclick='eliminar('line" . $x . "')' class='carritoElim' value='elim'></td>";
echo "</tr>";
}
function eliminar($id) {
var elem = document.getElementById($id);
elem.parentNode.removeChild(elem);
}
However, if you want to delete column in the server side also, the ajax codes should be added.

php is a server side language, what meant once your response is sent out to the client(browser), under most case all your "saved" data/variables will be lost.
I am not a fan of what your language of choice for this task but here is a way to work around.
The trick is to scan the whole table of data when the user clicked the eliminate button, then send all the data back to the sever and recreate the array with the selected row taken out. Then print the whole array back to html format and send it to user again.
The critical part to of this method is that you NEED to print everything you wish to retain in every response, so that you could scan them all back in to your server side program.
I've some sample code for your reference, but I didn't pay much attention when I wrote them so expect bugs and incorrect syntax, this is just for pure demostration purpose to show you the idea.
the sample code to print the table you've shown:
echo "<form action='".$_PHP_SELF."' method='post'>";
echo "<input type='hidden' name='type' value='yourarrayname'/>";
echo "<table border=1>";
echo "<tr class='tabPreciosTitles'>";
echo "<td>Nom Activitat</td>
<td>Nom Tipus Activitat</td>
<td>Tipus Tarifa</td>
<td>Temps/km</td>
<td>Preu</td>";
echo "</tr>";
for ($x=0;$x<count($savedArray[4]);$x++){
if(strcasecmp($savedArray[0][$x],"-999")!=0){
echo "<tr>";
echo "<td><input type='text' name='0_".$x."' value='".$savedArray[0][$x]."'/></td>";
echo "<td><input type='text' name='1_".$x."' value='".$savedArray[1][$x]."'/></td>";
echo "<td><input type='text' name='2_".$x."' value='".$savedArray[2][$x]."'/></td>";
echo "<td><input type='text' name='3_".$x."' value='".$savedArray[3][$x]."'/></td>";
echo "<td><input type='text' name='4_".$x."' value='".$savedArray[4][$x]."'/></td>";
echo "<td><button name='elim' value='e".$x."' type='submit'>elim</button></td>";
echo "</tr>";
}
}
echo "</table>";
echo "</form>";
and here's the sample code to handle the incoming data, put this after you created the array but before the printing code:
if($_POST!=null){
if(strcasecmp($_POST['type'],"yourarrayname")==0){
for ($x=0;$x<count($savedArray[4]);$x++){
if(strcasecmp($_POST['elim'],"e".$x)!=0){
$savedArray[0][$x] = $_POST['0_'.$x];
$savedArray[1][$x] = $_POST['1_'.$x];
$savedArray[2][$x] = $_POST['2_'.$x];
$savedArray[3][$x] = $_POST['3_'.$x];
$savedArray[4][$x] = $_POST['4_'.$x];
}
if(strcasecmp($_POST['elim'],"e".$x)==0){
$savedArray[0][$x] = "-999";
$savedArray[1][$x] = "-999";
$savedArray[2][$x] = "-999";
$savedArray[3][$x] = "-999";
$savedArray[4][$x] = "-999";
}
}
}
}

Related

how can I pass on a post data from one view to another through a controller

I want to load a new page with the hidden id from a table row as a post data when I click on the view <td>.
This is the code from Admin/contracts:
$count = 0;
foreach ($data as $row) {
$id = $row->_id;
++$count;
echo "<tr>
"<input name='contract_id' id='contract_id' value='$id' hidden/>".
"<td class=\"id_td td_content\">".$count."</td>".
"<td class='serial_td td_content'>".$row->_id."</td>".
"<td class='organisation_td td_content'>".$row->organisation."</td>".
"<td class='contract_td td_content'>".$row->title."</td>".
"<td class='lot_no_td td_content'>".$row->serial_no."</td>".
"<td class='pub_date_td td_content'>".substr($row->pub_date, 0, 10)."</td>".
"<td class='view_td'><a href='".site_url('Admin/contract_detail')."'>view</td>";
echo "</tr>";
}
This is the code from the Admin controller:
public function contract_detail(){
$id = $this->input->post('contract_id');
$result['id'] = $id;
$this->load->view('admin/contract_detail', $result);
}
And the code in the admin/contract_detail view:
<?php
echo "id = ". $id;
?>
The problem is $id outputs nothing when echoed.
I need help please;
The problem here is you redirect user to contract_detail vie anchor element
if you want to pass the id to the contract_detail page you have to sent it as form not link
For example
change you foreach to the following
foreach ($data as $row) {
$id = $row->_id;
++$count;
echo "<tr><form action='".site_url('Admin/contract_detail')."' method='post'>
"<input name='contract_id' id='contract_id' value='$id' hidden/>".
"<td class=\"id_td td_content\">".$count."</td>".
"<td class='serial_td td_content'>".$row->_id."</td>".
"<td class='organisation_td td_content'>".$row->organisation."</td>".
"<td class='contract_td td_content'>".$row->title."</td>".
"<td class='lot_no_td td_content'>".$row->serial_no."</td>".
"<td class='pub_date_td td_content'>".substr($row->pub_date, 0, 10)."</td>".
"<td class='view_td'><button type='submit'>view</button></td>";
echo "</form></tr>";
}
"<input name='contract_id' id='contract_id' value='".$id."' hidden/>".
Please try this line of code. I hope this helps.

how to return php variable to Jquery function to be used to multiply values

Trying to have several checkboxes multiply and add where there are multiple products. would it be possible to use a for statement in jquery against the number of rows in a database or have it run without it?
I've reduced the code i had to a compact version to add up checkboxes and multiply against a multiplier that is a POST from a previous page.
now this script won't run for any of the products and wandering what could be used to bridge the problem between client side and server side script.
I'm confused about the method needed to use a php variable in a jquery function. I thought of use an onclick to call function for a checkbox clicked but im trying to run this on DOM ready. If anyone can perhaps tell me in the simplest terms how this may be possible I will happily do more research.
<?php
//CONNECTION, QUERY AND MISC ///
$count = mysqli_num_rows($result);
$i = 1;
while ($row = mysqli_fetch_assoc($result))
{
$kilo1 = $row['kilo1'];
$kilo2 = $row['kilo2'];
$price1 = $row['price1'];
$price2 = $row['price2'];
$price3 = $row['price3'];
$price4 = $row['price4'];
$multiplier = 2;
$qri = "qr"."$i";
$userdaily = "userdaily"."$i";
$usertotal = "usertotal"."$i";
$pricef1 = "price1"."$i";
$pricef2 = "price2"."$i";
echo "<form enctype='multipart/form-data' name='contactform' method='POST' action='something.php'>";
echo "<input type='hidden' name='multiplier' id='multiplier' value='$multiplier'>";
echo "<input type='checkbox' name='checkbox1' id='$qri' value='$price1'>";
echo "<input type='checkbox' name='checkbox2' id='$qri' value='$price2'>";
echo "<input type='checkbox' name='checkbox3' id='$qri' value='$price3'
class='insure'>";
echo "<input type='checkbox' name='checkbox4' id='$qri' value='$price4'
class='insure'>";
echo "<input type='checkbox' name='checkbox5' id='$qri' value='$kilo1'
class='kilo'>";
echo "<input type='checkbox' name='checkbox6' id='$qri' value='$kilo2'
class='kilo'>";
/////TOTALS VISIBLE AND HIDDEN/////
echo "<span id='$userdaily'></span>";
echo "<span id='$usertotal'></span>";
echo "<input type='hidden' name='pricef1' id='$pricef1' value=''>";
echo "<input type='hidden' name='pricef2' id='$pricef2' value=''>";
echo "<input type='submit'>";
if($i%4==0 || $i == $count) echo '<br>';
$i++;
}
?>
<script>
$(function()
{
$("input.kilo").change(function()
{
$("input.kilo").not(this).prop("checked", false);
});
$("input.insure").change(function()
{
$("input.insure").not(this).prop("checked", false);
});
$(document).ready(function()
{
//get the values of the selected options
var counter = parseInt("<?php echo $count;?>");
for (i = 1; i <= counter; i++)
{
let v = $.map($("input[id^='qr+i+']:checked"), function(t)
{
return parseFloat($(t).val());
});
let s = v.reduce((a, b) => a + b);
//sum them up to a daily total
console.log(v);
$("#<?php echo $userdaily;?>").text('R' + s + '/day');
$("#<?php echo $usertotal;?>").text('R' + s *
parseFloat($("#multiplier").val()) + '/day');
$("#<?php echo $pricef1;?>").val(s);
$("#<?php echo $pricef2;?>").val(s * parseFloat($("#multiplier").val()));
}
});
});
</script>
I have a list of product each with a daily total and a total of the number of days, each product has completely different prices. I tried to create this in a fiddle and it works find without the use of variables, I realise that Jquery and php are different in their uses and I'm not sure how to work around this.
As treyBake mentionned, if you need to pass information from PHP to jQuery back to PHP and so forth, use hidden DOM elements and make Ajax requests.
This will also allow you to update your data in real time.
Okay so for instance you can hide your number count in a hidden input
<input type="hidden" value="<?php echo $count;?> " name="countrows" id="countrows">
Now you can retrieve in your jQuery :
var counter = $("#countrows").val();
Get value of checked checkbox with is.checked :
var x = $("#checkbox").is(":checked");

Update from checkbox to wrong ID in php

issue for days now.
I have a form with multiple checkboxes, I will never know how many rows will be in the form, and I am aware that an empty checkbox will not post to the processing page. I have also tried providing a hidden value to the checkbox to no avail...
I know there is a straightforward method to this, please assist:
The following code is on the form:
echo "<td><center><input type='checkbox' checked='checked' name='jce_pnt_id[]' value='$jce_pnt_id' onclick='return false;' /><br>$jce_pnt_id</center></td>";
echo "<td title='Task Complete ?'><center><input type='hidden' name='tr_g[]' value='25'>";
if($jce_ins_complete < '100' || $jce_ins_act_complete == '0')
{
echo "<input type='checkbox' name='tr_g[]' id='$jce_pnt_id' value='100'>";
}
else
{
echo "<input type='checkbox' name='tr_g[]' id='$jce_pnt_id' value='100' checked='checked'>";
}
echo "</center></td>";
Here is a screenshot (look at the red circled column):
Here is the processing snippet (not working):
$jce_pnt_id = $_POST['jce_pnt_id'];
$tr_g = $_POST['tr_g']; // jce_pnt_act_complete
foreach ($tr_g as $id => $trg) {
//if(empty($trg)) { $trg = "0"; }
$queryg = "UPDATE `jce_pnt` SET `jce_pnt_act_complete` = '$trg' WHERE `jce_pnt_id` = '$jce_pnt_id[$id]'";
$resultg = mysqli_query($cxn,$queryg);
}
* The value writes to the wrong ID in the database.

Sending jquery-ui selectable data using form

I need to send some POST data using jquery-ui selectable in a form.
Checked object will be stored in my database after clicking "Aggiorna" button.
I use the external Checked() function to preleve the last configuration by my database in order to dinamically choose the default selected items.
if(isset($_POST['Aggiorna'])) // button name
{
global $Gruppo_Sensori,$Gruppo_Elettrovalvole,$id_GS,$id_GE, $G;
// recupero le informazioni dal form
for($i=0;$i<count($G); $i++)
{
if(isset($_POST[$G[$i]]))
{
// UPLOAD $_POST[$G[$i]] on my database
unset($_POST[$G[$i]]); // clear the $_POST data
}
}
echo "<form action='' method='POST' name='programmazione' id='programmazione'>";
echo"<table>";
for($j=0;$j<7;$j++)
{
echo "<tr>";
echo"<td>$G[$j]</td>";
echo"<td>";
for($i=0;$i<24;$i++)
{
$k=$i+1; //calcolo l'estremo superiore dell'intervallo
$value = array($j,$i,0,$j,$k,0);
$nome = $G[$j];
if(Checked($j,$i,0,$j,$k,0)) {
$checked = "checked";
} else {
$checked="";
}
echo "<input type='checkbox' name='$nome"."[]' value='". implode(',',$value). "' $checked/> $i:$k";
}
echo"</td>";
echo "</tr>";
}
echo"</table>";
echo "<tr><td></td><td><input type='submit' value='Aggiorna' name='Aggiorna'></input>
This code works, but now I would like to use jquery to do the same work, for a obviuos graphical reason.
I have replaced the checkbox with
if(Checked($j,$i,$Minuto,$Giorno_Finale,$Ora_Finale,$Minuto_Finale))
{
echo "<li class='ui-state-default ui-selected' id='$id'>$i</li>"; // selected
$_POST[$nome][] = implode(',',$value); // adding items to $_POST in order to reinsert it on database
}
else
{
echo "<li class='ui-state-default' id='$id'>$i</li>"; // unselected
}
I can't understand why it don't work
An other problem will be to add other option than the defaults to $_POST using jquery
A demo is visible here under Programmazione tabs >> clicking on Clock images
User: guest, pass: guest
Thank you very much for your support

how to submit a form to another page in wordpress plugin

I am developing a wordpress plugin , which submits a form to another page. But when I try to submit the form to another page , then that page returns some php error. My form code is below
echo "<form action='".plugins_url()."/wp_voting_poll/frontend_poll_process.php' method='post'>";
echo "<input type='hidden' name='hide' value='$ques' />";
$total_vote_count = $wpdb->get_var( "SELECT COUNT(*) FROM $table_result WHERE question_uid='$ques'" );
if($ques!=""){
echo "<table>";
foreach($ans_data as $ans_res){
// $ans=$ans_res->answer;
$answer_id=$ans_res->id;
$type=$ans_res->answer_type;
$vote_count = $wpdb->get_var( "SELECT COUNT(*) FROM $table_result WHERE answer_id='$answer_id'" );
if($vote_count==0){
error_reporting(0);
}
$vote_percent=($vote_count*100)/$total_vote_count;
echo "<tr> <td>";
echo "<div class='answer_div'>";
if($type==1){
echo "<div class='input'><input type='radio' name='ans_name[]' value='$answer_id'/>".$ans_res->answer."<br/></div>";
}
elseif($type==0){
echo "<div class='input'><input type='checkbox' name='ans_name[]' value='$answer_id'/>".$ans_res->answer."<br/></div>";
}
if($backend==0){
echo "</td> <td>";
echo "<h4> total vote counted $vote_percent% </h4>";
// echo "<img src='$url' width='$width_img'/>";
$bar=$vote_percent*5.9;
echo "<img src='$url' height='10' width='$bar' />";
echo "</td></tr>";
}
}
echo "</table>";
echo "<input type='submit' value='Submit vote' />";
echo "</form>";
And this is my code of another page , which should process the form . But unfortunately it returns php error.
<?php
require_once("function_ip.php");
$vote_result=$_POST['ans_name'];
$uid=uniqid();
global $wpdb;
$table_vote=$wpdb->prefix."poll_answer_result";
$count=count($vote_result);
$hidden=$_POST['hide'];
$ans_data=$wpdb->get_results("SELECT * FROM $table_vote WHERE question_id='$hidden'" );
if($count>0){
foreach($vote_result as $vote_arr){
$wpdb->insert($table_vote,
array('answer_id' => $vote_arr,
'ip' =>get_client_ip(),
'question_uid' => $hidden
));
}
}
?>
Wordpress has a generic handler to deal with all forms - admin-post.php.
If you include a hidden field in your form called action, you can then hook in to a function of your choice with all the goodness of wordpress included.
echo "<form action='".get_admin_url()."admin-post.php' method='post'>";
echo "<input type='hidden' name='action' value='submit-form' />";
echo "<input type='hidden' name='hide' value='$ques' />";
{ Enter the rest of your first block of code from above here }
echo "</form>";
And then in your functions.php file (or any other php file that you have included via functions.php), you can use this method.
add_action('admin_post_submit-form', '_handle_form_action'); // If the user is logged in
add_action('admin_post_nopriv_submit-form', '_handle_form_action'); // If the user in not logged in
function _handle_form_action(){
{ Enter your second block of code from above here }
}
I'm not sure if you require a redirect once you reach your desired destination, but that can be easily accounted for if you do.
And one final question - is this form on the front end, or in the admin area? Not that it should make a difference that this answer, I'm just curious...
Your frontend_poll_process.php page is getting called out of the WordPress environment, therefore returning an error on $wpdb->get_results().
You can add your code to a plugin or functions.php using hooks:
<?php
add_action( 'after_setup_theme', 'so_19997913' );
function so_19997913() {
require_once("function_ip.php");
$vote_result = $_POST['ans_name'];
$uid = uniqid();
global $wpdb;
$table_vote = $wpdb->prefix . "poll_answer_result";
$count = count( $vote_result );
$hidden = $_POST['hide'];
$ans_data = $wpdb->get_results( "SELECT * FROM $table_vote WHERE question_id='$hidden'" );
if ( $count > 0 ) {
foreach ( $vote_result as $vote_arr ) {
$wpdb->insert( $table_vote, array('answer_id' => $vote_arr,
'ip' => get_client_ip(),
'question_uid' => $hidden
) );
}
}
}

Categories