I have a list of products in a table extracted from my DB.
Each product have a field with ALIQUOTA (= VAT, Tax).
I want to have the possibility to modify the aliquote value assigned to single products.
I did a drop menu next to the actual aliquote that contains all the allowed value from an aliquote table of my database. (that values are 0.00, 4.00, 10.00, 20.00).
Once selected, that value will be inserted in a readonly input text field with id "aliquota_XXX" (where XXX is the id that correspond to the product).
Then i want to save that value pressing the button CONFIRM VAT that activate the function save_modify (this function already exists in the project).
This is the code:
<select class="piccolo elemento_modulo_obbligatorio" id="aliquota_dropdown_<?php echo $row['rid']; ?>" name="aliquota_dropdown">
<?php
$aliquote = "SELECT aliquota,id AS aid FROM aliquote ORDER BY aliquota ASC";
$result_aliquote = mysql_query($aliquote) or die("Invalid query: " . mysql_error());
while ($row_aliquote = mysql_fetch_array($result_aliquote)) {
echo '<option onclick=\'';
?>
$("#aliquota<?php echo $row['rid']; ?>").val("<?php echo $row_aliquote['aliquota']; ?>");
<?php
echo ';\' value="' . $row_aliquote['aid'] . '">' . $row_aliquote['aliquota'] . '</option>';
}
?>
</select>
<input autocomplete="off" type="text" class="class12" id="aliquota<?php echo $row['rid']; ?>" name="aliquota" readonly="readonly" value="" />
<input type="button" onclick="save_modify("aliquota",document.getElementById('aliquota_<?php echo $row['rid']; ?>').value,<?php echo number_format($row['aliquota'],2,".",","); ?>);" value="CONFIRM VAT" />
The function save_modify is that:
function save_modify(cosa, valore_nuovo, valore_vecchio) {
$.ajax({
type: "GET",
url: "ajax_salva_modifica_valore.php",
data: "id_documento=" + <? php echo $_GET['id_documento']; ?> +"&cosa=" + cosa + "&id=" + id + "&valore_nuovo=" + valore_nuovo + "&valore_vecchio=" + valore_vecchio,
cache: false,
success: function(data) {
$("#sezione_messaggi").html("Succesfully modified!");
},
beforeSend: function() {
$("#sezione_loading").html("<img src='../images/ajax-loader.gif' />");
},
complete: function() {
$("#sezione_loading").html("");
post_modifica(id);
carica_righe();
}
});
}
And the part of ajax_salva_modifica_valore.php that interest that is:
<?php
session_start();
$cosa = $_GET['cosa'];
$array_id = split("_",$id);
$id_riga = $array_id[1];
$valore_nuovo = $_GET['valore_nuovo'];
$valore_vecchio = $_GET['valore_vecchio'];
if($cosa == "aliquota") {
$modifica = "UPDATE righe_documenti
SET aliquota = '" . $valore_nuovo . "'
WHERE id = " . $id_riga;
$result = mysql_query($modifica) or die("Invalid query: " . mysql_error());
}
?>
I don't know where is the problem, because the parameter passed to the function are correct, but the modify it's not applied...
Someone can help me to fix it or try another solution?
The save_modify and ajax_salva_modifica_valore.php are not made by me, so i suppose that them are correct (and they works for the edit of other products information...)
Thanks!
The main problem is that number_format() formats number as a string and should be enclosed in double quotes (") in your case.
<input type="button" onclick="save_modify("aliquota",this.id,$("#aliquota<?php echo $row['rid']; ?>").val(),"<?php echo number_format($row['aliquota'],2,",","."); ?>");" value="CONFIRM ALIQUOTA" />
However by looking at the rest of your code, it seems you don't need number_format() at all:
<input type="button" onclick="save_modify("aliquota",this.id,$("#aliquota<?php echo $row['rid']; ?>").val(),<?php echo $row['aliquota']; ?>);" value="CONFIRM ALIQUOTA" />
Related
My goal is to submit a set of variables to my AJAX function from with in a while loop in php. This is my first shot at using AJAX, so please excuse if it is messy, and not close to correct. I appreciate any assistance.
PHP FORM:
x=0;
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$id = $row['col1'];
$ad = $row['col2'];
cho '<form id="msu_form">';
echo "<tr><td>{$ad}</td>";
echo "<td>";
$query2 = "SELECT col1,col2 FROM table WHERE notes = 'x'";
$result2 = mysql_query($query2);
$count2 = mysql_num_rows($result2);
if($count2 > 0)
{
echo '<select class="Primary" name="primary" onchange=doAjaxPost()>';
while($row2 = mysql_fetch_array($result2))
{
echo "<option value=".$row2['col1'].">".$row2['col2']."</option>";
}
echo "</select>";
}else
{
echo "Blah";
}
echo "</td>";
echo "<td>";
$query3 = "SELECT col1,col2 FROM table2 WHERE notes = 'y'";
$result3 = mysql_query($query3);
$count3 = mysql_num_rows($result3);
if($count3 > 0)
{
echo '<select class="Secondary" name="secondary">';
while($row3 = mysql_fetch_array($result3))
{
echo "<option value=".$row3['col1'].">".$row3['col2']."</option>";
}
echo "</select>";
}else
{
echo "Bah";
}
echo "</td>";
echo '<input type="hidden" class="ID" name="ID" value="'.$id.'"/>';
echo '<input type="hidden" class="desc" name="desc" value="'.$ad.'"/>';
//echo '<td>'."<input type='submit' name='btnupdate' value='UPDATE' /></td>";
echo '</form>';
$x = $x+1;
}
So what happens is every time I change any of the "primary" select boxes on the screen, I get the value of the variables on the first line only. I want to receive the values of the form from the select box. I have tested it via a button, that submits the form it is commented out, but that button submits all the correct information to the page, but I don't want to submit the data every time. Is there a way to accomplish my goal?
Thanks - below the ajax if it helps with an answer.
<script>
function doAjaxPost() {
// get the form values
var primary = $(this).val();
var secondary = $(this).parent().next().child('.Secondary').val();
var hidden = $(this).parent().nextAll('.ID').val();
//var desc = $(this).parent().nextAll('#desc').val();
$.ajax({
type: "POST",
url: "functions/database_write.php",
data: $('#msu_form').serialize(),
//data: "Primary="+primary+"&Hidden="+hidden+"&Secondary="+secondary,
success: function(resp){
//we have the response
alert("'" + resp + "'");
},
error: function(e){
alert('Error: ' + e);
}
});
}
</script>
First, in your php code change the following 4 lines (using id)
echo "<select id=Primary name=primary onchange=doAjaxPost()>";
echo "<select id=Secondary name=secondary>";
echo '<input type="hidden" id="ID" name="ID" value="'.$id.'"/>';
echo '<input type="hidden" id="desc" name="desc" value="'.$ad.'"/>';
to (using class) edited
echo '<select class="Primary" name="primary" onchange="doAjaxPost(this)">'; //added (this)
echo '<select class="Secondary" name="secondary">';
echo '<input type="hidden" class="ID" name="ID" value="'.$id.'"/>';
echo '<input type="hidden" class="desc" name="desc" value="'.$ad.'"/>';
Then, in your javascript code, change
function doAjaxPost() {
var primary = $('#Primary').val();
var secondary = $('#Secondary').val();
var hidden = $('#ID').val();
var desc = $('#desc').val();
to edited
function doAjaxPost(sel) { // added (sel)
var primary = $(sel).val(); //changed to $(sel)
var secondary = $(sel).parent().next().children('.Secondary').val(); //changed to $(sel) and changed to children()
var hidden = $(sel).parent().nextAll('.ID').val(); //changed to $(sel) and changed to nextAll()
var desc = $(sel).parent().nextAll('#desc').val(); //changed to $(sel) and changed to nextAll()
If everything works fine when submitting normally, then probably you are generating the ajax data wrong, instead give your form an id:
echo '<form id="myform">';
Then serialize the form to get the correct data:
function doAjaxPost() {
$.ajax({
type: "POST",
url: "functions/data.php",
data: $('#myform').serialize(),
success: function(resp){
//we have the response
alert("'" + resp + "'");
},
error: function(e){
alert('Error: ' + e);
}
});
}
EDIT Ok you edit has cleared things up a bit, I didn't notice you have multiple forms.
Using the same doAjaxPost function as above, change the data property to:
data: $(this).parents('form').serialize();
Context:
using PHP to echo HTML.
Issue:
Echoed HTML does not display unless I've hard-coded $n (i.e. $n = 2;).
Trouble-shooting:
-I've confirmed that I'm receiving the POST data via echo,var_dump,print_r.
-I've confirmed that the for loop works by substituting hard-coded numbers for $n.
-I've made sure that the string being received via POST is an integer.
<?php
$n=intval($_POST["a"]);
for($count=1;$count<=$n;$count++)
{
echo '<li>foo ' . $count . ':<input type="text" name="bar' . $count . '" value="baz ' . $count . '"></li>';
};
?>
EDIT: The PHP gets POST from AJAX (see below)
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#formid").change(function(){
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
data : $(this).serialize(),
success : function( response ) {
alert( response );
}
});
$("#div1").load("load.php");
});
});
</script>
Edit: As per your originally posted question
You are missing a ' after value="baz
value="baz . $count . '"></li>
^ // right there
Full echo should be:
echo '<li>foo ' . $count . ':<input type="text" name="bar' . $count . '" value="baz' . $count . '"></li>';
This has bitten me before, and what I usually do to concatenate long strings is after each period, I hit enter and create a new line.
Remember, PHP is white-space insensitive so feel free to separate lines all you'd like.
It's unclear as to what your expected result should be, yet using the (fixed) code that follows, produced the following in HTML source:
<li>foo 1:<input type="text" name="bar1" value="baz1"></li>
<li>foo 2:<input type="text" name="bar2" value="baz2"></li>
<li>foo 3:<input type="text" name="bar3" value="baz3"></li>
<li>foo 4:<input type="text" name="bar4" value="baz4"></li>
<li>foo 5:<input type="text" name="bar5" value="baz5"></li>
PHP (using 5 as a number)
Sidenote: I added . "\n" at the end of the code for clarity.
<?php
// $n=intval($_POST["a"]);
$n=intval(5);
for($count=1;$count<=$n;$count++)
{
echo '<li>foo ' . $count . ':<input type="text" name="bar' . $count . '" value="baz' . $count . '"></li>' . "\n";
};
?>
Edit
Successful test with form included:
<?php
if(isset($_POST['submit'])){
// $n=intval(5);
$n=intval($_POST["a"]);
for($count=1;$count<=$n;$count++)
{
echo '<li>foo ' . $count . ':<input type="text" name="bar' . $count . '" value="baz' . $count . '"></li>' . "\n";
};
}
?>
<form method="post" action="">
Number:
<input type="text" name="a">
<br>
<input type="submit" name="submit" value="Submit">
</form>
Sidenote:
Just to test both methods - one with and one without (intval), $n=$_POST["a"]; also worked.
I am having trouble using a checkbox to select one or multiple fields of data for PHP/AJAX to process and display. I have the PHP/AJAX working great on my <select>s but as soon as I try setting up the checkbox all hell breaks lose.
I also am very unsure on how to further prevent SQL injection on the site so if anyone could fill me in a little more about this I would GREATLY appreciate it! I read the link I was provided and just don't understand how bid_param or PDO works exactly.
The ajax script:
(I can't seem to insert the ajax/js so I'll leave a link to the live site)
Link to Agent search page
My php page that displays the data:
<div id="bodyA">
<h1>Find a Local OAHU Agent.</h1>
<!-- This is where the data is placed. -->
</div>
<div id="sideB">
<div class="sideHeader">
<em>Advanced Search</em>
</div>
<form class="formC">
<label for="last">Last Name</label><br />
<select id="last" name="Last_Name" onChange="showUser(this.value)">
<?php
include 'datalogin.php';
$result = mysqli_query($con, "SELECT DISTINCT Last_Name FROM `roster` ORDER BY Last_Name ASC;");
echo '<option value="">' . 'Select an Agent' .'</option>';
while ($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row['Last_Name'].'">'.$row['Last_Name'].'</option>';
}
?>
</select>
<label for="company">Company</label><br />
<select id="company" name="users" onChange="showUser(this.value)">
<?php
include 'datalogin.php';
$result = mysqli_query($con, "SELECT DISTINCT Company FROM `roster` ORDER BY Company ASC;");
echo '<option value="">' . 'Select a Company' .'</option>';
while ($row = mysqli_fetch_array($result)) {
if ($row['Company'] == NULL) {
} else {
echo '<option value="'.$row['Company'].'">'.$row['Company'].'</option>';
}
}
?>
</select>
<label for="WorkCity">City</label><br />
<select id="WorkCity" name="WorkCity" onChange="showUser(this.value)" value="city">
<?php
include 'datalogin.php';
$result = mysqli_query($con, "SELECT DISTINCT WorkCity FROM `roster` ORDER BY WorkCity ASC;");
echo '<option value="">' . 'Select a City' .'</option>';
while ($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row['WorkCity'].'">'.$row['WorkCity'].'</option>';
}
?>
</select>
<label for="WorkZipCode">Zip Code</label><br />
<select id="WorkZipCode" name="WorkZipCode" onChange="showUser(this.value)">
<?php
include 'datalogin.php';
$result = mysqli_query($con, "SELECT DISTINCT WorkZipCode FROM `roster` ORDER BY WorkZipCode + 0 ASC;");
echo '<option value="">' . 'Select a Zip Code' .'</option>';
while ($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row['WorkZipCode'].'">'.$row['WorkZipCode'].'</option>';
}
?>
</select>
<label for="agent">Agent Expertise</label><br />
<label for="ancillary"><input type="checkbox" value="Ancillary" name="Ancillary[]" id="ancillary" />Ancillary</label><br />
<label for="smallgroup"><input type="checkbox" value="Smallgroup" name="Smallgroup[]" id="smallgroup" />Small Group</label><br />
<label for="largegroup"><input type="checkbox" value="LargeGroup" name="LargeGroup[]" id="largegroup" />Large Group</label><br />
<label for="medicare"><input type="checkbox" value="Medicare" name="Medicare[]" id="medicare" />Medicare</label><br />
<label for="longterm"><input type="checkbox" value="LongTerm" name="LongTerm[]" id="longterm" />Long Term Care</label><br />
<label for="individual"><input type="checkbox" value="Individual" name="Individual[]" id="individual" />Individual Plan</label><br />
<label for="tpa"><input type="checkbox" value="TPASelfInsured" name="TPASelfInsured[]" id="tpa" />TPA Self Insured</label><br />
<label for="ppaca"><input type="checkbox" value="CertifiedForPPACA" name="CertifiedForPPACA[]" id="ppaca" />Certified for PPACA</label><br />
</form>
</div>
My php page that pulls the info and places it into a container on the page:
$q = (isset($_GET['q'])) ? $_GET['q'] : false; // Returns results from user input
include 'datalogin.php'; // PHP File to login credentials
$sql="SELECT * FROM `roster` WHERE Company = '".$q."' OR Last_Name = '".$q."' OR WorkCity = '".$q."' OR WorkZipCode = '".$q."' ORDER BY Last_Name ASC";
$result = mysqli_query($con,$sql) // Connects to database or die("Error: ".mysqli_error($con));
echo "<h1>" . "Find a Local OAHU Agent." . "</h1>";
while ($row = mysqli_fetch_array($result)) { // Gets results from the database
echo "<div class='agentcon'>" . "<span class='agentn'>" . "<strong>".$row['First_Name'] . " " .$row['Last_Name'] . "</strong>" . "</span>" . "" . "<span class='email'>".$row['Email'] . "</span>" . "" ."<div class='floathr'></div>";
if ($row['Company'] == NULL) {
echo "<p>";
}
else {
echo "<p>" . "<strong>" .$row['Company'] . "</strong>" . "<br>";
}
echo $row['WorkAddress1'] . " " .$row['WorkCity'] . "," . " " .$row['WorkStateProvince'] . " " .$row['WorkZipCode'] . "<br>";
if ($row['Work_Phone'] !== NULL) {
echo "<strong>" . "Work" . " " . "</strong>" .$row['Work_Phone'] . "<br>";
}
if ($row['Fax'] !== NULL) {
echo "<strong>" . "Fax" . " " . "</strong>" .$row['Fax'] . "<br>";
}
echo "<strong>" . "Agent Expertise:" . "</strong>";
if ($row['Ancillary'] == 1) {
echo " " . "Ancillary" . "/";
}
if ($row['SmallGroup'] == 1) {
echo " " . "Small Group" . "/";
}
if ($row['IndividualPlans'] == 1) {
echo " " . "Individual Plans" . "/";
}
if ($row['LongTermCare'] == 1) {
echo " " . "Long Term Care" . "/";
}
if ($row['Medicare'] == 1) {
echo " " . "Medicare" . "/";
}
if ($row['LargeGroup'] == 1) {
echo " " . "LargeGroup" . "/";
}
if ($row['TPASelfInsured'] == 1) {
echo " " . "TPA Self Insured" . "/";
}
if ($row['CertifiedForPPACA'] == 1) {
echo " " . "Certified For PPACA";
}
echo "</p>" . "</div>";
}
mysqli_close($con);
?>
I appreciate any and all help on this topic! Any time I add the checkbox values to my php file it ends up displaying everyone in the database for all fields in the form.
I am also trying to prevent sql injection on this but how can a user do this if I don't have a field the user can input text into?
EDIT As of today I gave a try with using jQuery to activate the checkboxes and then call some AJAX.
Here is the script I wrote and it is pulling an agent, just not everyone that has that "expertise".
$('input').click(function() {
$.ajax({
url: "process.php",
data: { value: 1},
success: function (data) {
$('#bodyA').html(data);
}
});
});
Here's a quick example of something I recently worked on in which I needed to loop through multiple checkboxes and pass those values into a SQL statement. Although this example happens on a button click, hopefully its something along the lines of what you are trying to accomplish, or at least at start... :)
<?php
$array = array();
if (isset($_POST['medicare'])) {
foreach ($_POST['medicare'] as $value) {
array_push($array, $value);
}
}
// this will return the value of each selected checkbox, separating each with a comma
$result = implode(",", $array);
// if you want to loop through each individually (for example pass each into a SQL statement)
foreach ($_POST['medicare'] as $value) {
// Do your SQL here
// $value will be the value of each selected checkbox (Smallgroup, Largegroup, etc.)
$sql = "insert into tablename(fieldname) values ('$value')"; // just an example
}
?>
<input type="checkbox" name="medicare[]" id="smallgroup" value="Smallgroup" />
<label for="smallgroup">Small Group</label>
<br />
<input type="checkbox" name="medicare[]" id="largegroup" value="Largegroup" />
<label for="largegroup">Large Group</label>
<br />
<input type="checkbox" name="medicare[]" id="medicare" value="Medicare" />
<label for="medicare">Medicare</label>
<br />
<input type="checkbox" name="medicare[]" id="individualplan" value="IndividualPlan" />
<label for="individualplan">Individual Plan</label>
<br />
<input type="submit" value="Submit" id="btnSubmit" name="btnSubmit" />
UPDATE
Instead of setting one variable, try setting a variable for each select control and putting your SQL statement in a foreach loop. I just tested this with some dummy data and didn't have any issues with it.
<?php
$lastname = (isset($_GET['Last_Name'])) ? $_GET['Last_Name'] : false;
$users = (isset($_GET['users'])) ? $_GET['users'] : false;
$workCity = (isset($_GET['WorkCity'])) ? $_GET['WorkCity'] : false;
$WorkZipCode = (isset($_GET['WorkZipCode'])) ? $_GET['WorkZipCode'] : false;
foreach ($_GET['medicare'] as $value) {
//echo $value;
$sql="SELECT * FROM roster WHERE Company = '$users' OR Last_Name = '$lastname' OR WorkCity = '$workCity' OR WorkZipCode = '$WorkZipCode' OR Ancillary = '$value' ORDER BY Last_Name ASC";
}
...continue as you were...
?>
I DID IT!! Wohoo! I ended up just making a separate php page called expertise.php to process the checkboxs using jquery/ajax.
The jQuery that achieved this: (Thank god I went onto the jQuery website to look up functions!)
$('input').click(function() {
$.ajax({
url: "expertise.php",
data: { value: 1},
success: function (data) {
$('#bodyA').html(data);
}
});
});
The PHP page is the same as my process.php page except for the sql:
$sql="SELECT * FROM `roster` WHERE Ancillary = '1' AND SmallGroup = '1' AND CertifiedForPPACA = '1' ORDER BY Last_Name ASC";
If anyone would enlighten me more on making this better protected against sql injections, feel free to!
Agent Search Page
Well I at least got both parts of the search working but a new problem has arose :p
Now in the sql I can use AND or OR, with AND it pulls only agents that have everyone of those expertise and with OR it seems to pull everyone. Any ideas?
Ok, so I have an input function that allows me to add items to a database, and displays this as a table. As part of the table, I am trying to add delete and edit buttons.
I am trying to figure out the best way to add delete and edit functionality. I'm thinking for editing, I will have to use Javascript. However, for deletions, I am not sure if I should use PHP, Javascript, or some combination therein.
So far, here's my code:
<html>
<header><title>Generic Web App</title></header>
<body>
<form action="addculture.php" method="POST">
<span><input type="text" size="3" name="id" />
<input type="text" name="culture" />
<input type="submit" value="add" /></span>
</form>
<?php
/* VARIABLE NAMES
*
* $con = MySQL Connection
* $rescult = MySQL Culture Query
* $cultrow = MySQL Culture Query Rows
*/
$con = mysql_connect("localhost", "root", "");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("generic");
$rescult = mysql_query("SELECT * FROM culture order by cult_id");
if (!$rescult) {
die('Invalid query: ' . mysql());
}
echo "<table><tbody><tr><th>ID</th><th>Culture Name</th>";
while ($cultrow = mysql_fetch_array($rescult)) {
echo "<tr>" . "<td>" . $cultrow[0] . "</td>" . "<td>" . $cultrow[1] . "</td>" . '<td><button type="button">Del</button></td>' . '<td><button type="button">Edit</button></td>' . "</tr>";
}
echo "</tbody></table>";
?>
</body>
</html>
Currently I have del and edit set as buttons, just for visible reference. What's the best way to deal with a situation where you have multiple buttons like this?
I apologize if my answer is too broad but so is your question.
Both, Editing and Deleting should use a combination of JavaScript and PHP code; for example when the user clicks on the delete button you can send an Ajax request to the server, have the record deleted from the DB and upon successful return from the server-side call, use JavaScript to visually delete the record from the markup. The same would apply to the Edit functionality.
Here's a nice intro on how to perform ajax requests using JQuery:
http://www.devirtuoso.com/2009/07/beginners-guide-to-using-ajax-with-jquery/
The first think I would do is add a value and name to the buttons:
<button type="button" value="$cultrow[0]" name="Delete">Delete</button>
<button type="button" value="$cultrow[0]" name="Edit">Edit</button>
The value of the button is going to be the id of the row, and the name is going to be the action that button will do. The next thing I would do is bind those buttons to actions with jquery.
$('button').click(function(){
//determine whether is delete or edit
//Once you determine what action use the id to make the request
//if delete prompt to verify if yes, ajax the server with a delete request
//if edit redirect user to a page that will handle editing of the row edit.php?id=5
});
For deleting row
1 - Make new page name it del_culture.php
session_start();
$id = base64_decode($_GET['id']);
$con = mysql_connect("localhost", "root", "");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$q = mysql_query("DELETE FROM culture WHERE cult_id = '".$id."' ");
if($q):
echo "Done";
else:
echo "ERROR";
endif;
2 - in your page add the following code
while ($cultrow = mysql_fetch_array($rescult))
{
echo "<tr>" . "<td>" . $cultrow[0] . "</td>" . "<td>" . $cultrow[1] . "</td>" . '
<td>Delete' . '<td><button type="button">Edit</button></td>' . "</tr>";
}
For Editing a row add link for edit like i did to page name it edit_cult.php
and do the same as you input put the values from database and then update it
This is your javascript
function performAction(action) {
// ASSIGN THE ACTION
var action = action;
// UPDATE THE HIDDEN FIELD
document.getElementById("action").value = action;
switch(action) {
case "delete":
//we get an array with every input contained into the form, and the form have an id
var aryCheck=document.getElementById('adminform').getElementsByTagName('input');
//now we parse them
var elm=null;
var total=0;
for(cptCnt=0;cptCnt<aryCheck.length;cptCnt++) {
elm=aryCheck[cptCnt];
if(elm.type=='checkbox') {
//we have a checkbox here
if(elm.checked==true){
total++;
}
}
}
if(total > 0) {
if(confirm("Are you sure you want to delete the selected records?")) {
// SUBMIT THE FORM
document.adminform.submit();
}
}
else {
alert("You didn't select any records");
}
break;
case "edit":
//we get an array with every input contained into the form, and the form have an id
var aryCheck=document.getElementById('adminform').getElementsByTagName('input');
//now we parse them
var elm=null;
var total=0;
for(cptCnt=0;cptCnt<aryCheck.length;cptCnt++) {
elm=aryCheck[cptCnt];
if(elm.type=='checkbox') {
//we have a checkbox here
if(elm.checked==true){
total++;
}
}
}
if(total > 1) {
alert("You can only edit one record at a time");
}
else if(total == 0) {
alert("You didn't select a record");
}
else {
document.adminform.submit();
}
break;
default:
}
}
and in your form you need something like this
<form id="adminform" name="adminform" action="<?php $_SERVER['REQUEST_URI'] ?>" method="post">
<img src="/admin/images/news.png" alt="news" title="news" />
<input type="button" class="back" id="backbutton" title="go back" onclick="performAction('back');" />
<input type="button" class="delete" id="deletebutton" title="delete" onclick="performAction('delete');" />
<input type="button" class="archive" id="archivebutton" title="archive" onclick="performAction('archive');" />
<input type="button" class="edit" id="editbutton" title="edit" onclick="performAction('edit');" />
<input type="button" class="add" id="addbutton" title="add" onclick="performAction('add');" />
<table id="admintable">
<tr><th class='tdleft'>
<?php
if($err !=0) {
echo"<input type='checkbox' name='all' onclick='checkAll(adminform);' />";
}
echo "</th><th class='tdright'>Title</th></tr>";
$z = 0;
// Iterate through the results
while ($row = $result->fetch()) {
if($z % 2==0) {
//this means if there is a remainder
echo "<tr class='yellow'>\n";
$z++;
} else {
//if there isn't a remainder we will do the else
echo "<tr class='white'>\n";
$z++;
}
echo "<td class='tdleft'><input type='checkbox' name='id[]' value='{$row['id']}' /></td><td class='tdright'><a href='/admin/news/edit-news-".$row['id']."'>{$row['title']}</a></td></tr>";
}
?>
</table>
<input type="hidden" id="action" name="action" value="" />
and at the top of your page before the html put
if($_POST && array_key_exists("action", $_POST)){
// CARRY OUT RELAVANT ACTION
switch($_POST['action']) {
case "edit":
foreach($_POST['id'] as $value) {
$id = $value;
}
header('Location: /admin/blogs/edit-blog-'.$id);
break;
case "delete":
if(!empty($_POST['id'])) {
//do your delete here
}
break;
}
}
}
ALL EDITED
Hi,
How can I auto populate the data from db by dropdown selected? and my dropdown result already appear as well, the code as following:
<?php
echo '<tr>
<td>'.$customer_data.'</td>
<td><select name="customer_id" id="customer_id" onchange="getCustomer();">';
foreach ($customers as $customer) {
if ($customer['customer_id'] == $customer_id) {
echo '<option value="'.$customer['customer_id'].'" selected="selected">'.$customer['name'].'</option>';
} else {
echo '<option value="'.$customer['customer_id'].'">'.$customer['name'].'</option>';
}
}
echo '</select>
</td>
</tr>';
?>
has html view code as
<select name="customer_id" id="customer_id" onchange="getCustomer();">
<option value="8">admin</option>
<option value="6">customer1</option>
<option value="7" selected="selected">FREE</option>
</select>
now if one of dropdown selected i want another e.g. <?php echo $firstname; ?>, <?php echo
$lastname; ?>
appear in
<tr>
<td><div id="show"></div></td>
</tr>
that based on customer id/name selected
to do that i try to use json call as following:
<script type="text/javascript"><!--
function getCustomer() {
$('#show input').remove();
$.ajax({
url: 'index.php?p=customer/customers&customer_id=' + $('#customer_id').attr('value'),
dataType: 'json',
success: function(data) {
for (i = 0; i < data.length; i++) {
$('#show').append('<input type="text" name="customer_id" value="' + data[i]['customer_id'] + '" /><input type="text" name="firstname" value="' + data[i]['firstname'] + '" />');
}
}
});
}
getCustomer();
//--></script>
the php call json placed at customer.php with url index.php?p=page/customer)
public function customers() {
$this->load->model('account/customer');
if (isset($this->request->get['customer_id'])) {
$customer_id = $this->request->get['customer_id'];
} else {
$customer_id = 0;
}
$customer_data = array();
$results = $this->account_customer->getCustomer($customer_id);
foreach ($results as $result) {
$customer_data[] = array(
'customer_id' => $result['customer_id'],
'name' => $result['name'],
'firstname' => $result['firstname'],
'lastname' => $result['lastname']
);
}
$this->load->library('json');
$this->response->setOutput(Json::encode($customer_data));
}
and the db
public function getCustomer($customer_id) {
$query = $this->db->query("SELECT DISTINCT * FROM " . DB_PREFIX . "customer WHERE customer_id = '" . (int)$customer_id . "'");
return $query->row;
}
but i get the wrong return as following
is there someone please how to solved it to more better? thanks in advance
Something on your PHP-Coding style:
For a PHP Code-Block, don't use new php-Tags for every line. Also, if you want an HTML-Output from PHP, you can use the echo-Method to do this. So your Code looks like this:
<?php
echo '<tr>
<td>'.$customer.'</td>
<td><select name="customer_id">';
foreach ($customers as $customer) {
if ($customer['customer_id'] == $customer_id) {
echo '<option value="'.$customer['customer_id'].'" selected="selected">'.$customer['name'].'</option>';
} else {
echo '<option value="'.$customer['customer_id'].'">'.$customer['name'].'</option>';
}
}
echo '</select>
</td>
</tr>';
?>
The thin is, every time the PHP-Interpreter finds an opening PHP-Tag, it starts Interpreting it's code, and when it finds a closing Tag, it stops doing this. So in your code, the interpreter starts and stops all the time. This is not very performance.
I guess you want to set the value of your text-fields? That's really not what PHP does. That is more a JavaScript thing, because it actually happens in the Browser, not on the Server.
Instead of this:
success: function(data) {
for (i = 0; i < data.length; i++) {
$('#show').append('<input type="text" name="customer_id" value="' + data[i]['customer_id'] + '" /><input type="text" name="firstname" value="' + data[i]['firstname'] + '" />');
}
}
in Your JS AJAX call do this:
success: function(data) {
$('#show').append('<input type="text" name="customer_id" value="' + data['customer_id'] + '" /><input type="text" name="firstname" value="' + data['firstname'] + '" />');
}
as Your PHP function returns ONLY ONE object. If You then loop over the objects property You loop over one character of the property value indeed...