PHP: print from a list of data (loop difficult) - javascript

Hi i have a little problem,my code create a list of buttons and each button have a name(value) from my list (table 'usernames')
....for exemple (table 'usernames' have 3 lines aa-bb-cc my code make 3 button with values aa & bb & cc..............
so what i want to do, is when i click on a button i want to print the value of this button in a div, for exemple if i click on the button who have the value 2 i want to print 2 in the div(i have a problem whit my loop, and i need help please)
this is my code:
$conn=mysqli_connect("localhost", "root", "pwd","sn") or die(mysqli_error());
$que2=mysqli_query($conn,"select usernames from posts", MYSQLI_USE_RESULT); // return a lot of lines on 'usernames'
$re=0;
$datax=array();
$i=0;
while ($r = mysqli_fetch_array($que2))
{
$re = $r["cnt"];
$datax[$i]=$re;
?>
<input id="ppost" name="ppost" value="<?php echo $datax[$i]; ?>" type="submit">
<br>
<script type="text/javascript">
$(function(){
$('#ppost').click(function(){
alert("<?php echo $datax[$i]; ?>");
});
});
</script>
<?php
$i++;
}

Ok, so there're few things to have a look at:
take the <script> out of the loop - one script can take care of all the buttons
you can't give same ID to all your inputs - id="..." has to be unique throughout your script
the JS script (assuming you have jQuery included prior to your ) should be:
<script type="text/javascript">
$(function(){
$('input[type="submit"]').click(function(){
alert($(this).attr('value'));
});
});
</script>
this should do the trick, let me know if this is what you wanted.

Related

How to populate second drop down box on first drop down (Hard)

I want to populate my second drop down box based on what value the user has chosen on the first. This is what I have done so far:
In the PHP file:
function displayDropDown()
{
$table_tester = "TBL_TESTER_LIST";
$query_string = "select * from $table_tester";
$result = #mysql_query($query_string) or die (mysql_error());
echo "<select id=\"tester_type\" onChange=\"getTesterType();\">";
while($data = mysql_fetch_array($result))
{
$tester_type = $data['tester_type'];
echo "<option value='$tester_type'>$tester_type</option>"; // first drop down
}
echo "</select>";
}
function displaySecondDropDown($selected_tester_type)
{
$table_tester = "TBL_TESTER_LIST";
$query_string = "select * from $table_tester where tester_type = '$selected_tester_type'";
$result = #mysql_query($query_string) or die (mysql_error());
echo "<select>";
while($data = mysql_fetch_array($result))
{
$tester_name = $data['tester_name'];
echo "<option value='$tester_name'>$tester_name</option>";// second drop down
}
echo "</select>";
}
?>
<?php
$action = rtrim($_REQUEST['action']);
if($action=="insert")
{
$tester_type = rtrim($_REQUEST['tester_type']);
$tester_name = rtrim($_REQUEST['tester_name']);
echo checkDuplicateTesterName($tester_type, $tester_name);
}
else if($action=="displayDropDown")
{
$selected_tester_type = $_REQUEST['tester_type'];
echo displayDropDown();
echo displaySecondDropDown($selected_tester_type);
}
?>
In the external JavaScript file:
function displayDropDown()
{
var page = "database.php";
$.post(page, {
action : "displayDropDown"
}, function(data) {
$("div#drop_two_list").html(data);
});
}
function getTesterType()
{
var tester_type = $("#tester_type").val();
var page = "database.php";
$.post(page, {
tester_type : tester_type
}, function(data) {
$("div#drop_two_list").html(data);
});
}
In the HTML file:
<html>
<head>
<title>Delete Tester</title>
<link rel="stylesheet" type="text/css" href="style.css"/>
<script language="javascript" type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="function.js"></script>
<script type="text/javascript">displayDropDown();</script>
</head>
<body>
<h3>Delete Tester</h3>
<div id="drop_two_list"></div>
<table class="deleteTable">
<tr>
<td/><td><br>
<input type="button" value="Cancel" onclick="window.close();"/>
<input type="button" name="send" value="Delete" onclick="deleteTester();"/>
</td>
</tr>
</table>
</body>
</html>
Two drop down boxes do appear. The first one has values(which are wrong I'll explain in the later part) and the second is empty. Also, an error appeared: Notice: Undefined index: tester_type in /opt/lampp/htdocs/Signup/module1/database.php on line 86 which is $selected_tester_type = $_REQUEST['tester_type']; in the PHP file. If I were to select a value in the first one then another error would replace everything on the page with: Notice: Undefined index: action in /opt/lampp/htdocs/Signup/module1/database.php on line 75 which is $action = rtrim($_REQUEST['action']);.
Now onto the part where I state why the first drop down box has the wrong values. Before proceeding, to understand my question better here is the table(TBL_TESTER_LIST) that I am trying to populate the drop down boxes with.
Note: I am only showing 5 sample rows in random order because I have more than 500 rows in this table and wouldn't want to put everything here.
id tester_type tester_name
1 LMX LMX-01
2 LMX LMX-04
26 LCX LCX-06
40 CAT CAT-14
95 HPPS HPPS-01
The tester_type column is what I want to populate my first drop down box with, and tester_name column is what I want to populate my second drop down box with, accordingly. As you can see, there duplicates for tester_type because one tester_name can belong to the same tester_type(An example would be green apple no.1(tester_name) is an apple(tester_type) and green apple no.2(tester_name) is also an apple(tester_type)).
What I am currently getting in my first drop down box is just: LMX, LMX, LMX, LMX, and so on. That is because my first 31 Rows are LMX. How do I code my drop first down box such that it would only display one of each type, and my second drop down box would display the values that are based on what the user selected?
An example would be: If the user selects LMX in the first drop down box, then all the tester_names that are LMX tester_type would populate the second drop down box.
If more information needed on the table, please do tell me. Been searching for a solution for 5 days and I don't seem to be close to a conclusion.
Without asking why your table is structured that way, would it not be enough to use the DISTINCT clause in your query to eliminate duplicates.
select DISTINCT tester_type from $table_tester

Using auto complete textbox get table record from mysql database and shows in text fields

I need to access the table record from the database when they press enter in the autocomplete textbox (at the time of select value), and it shows data in text element.
I have tried this code but cannot get the whole record:
html code:
<input class="form-control" name="sel_product_name" id="sel_product_name" >
<input class="form-control" name="sel_product_id" id="sel_product_id">
javascript code:
<script type="text/javascript">
$(document).ready(function(){
$("#sel_product_name").autocomplete({
source:'autocomplete.php',
minLength:1
});
});
</script>
autocomplete.php
<?php
mysql_connect("localhost","root","");
mysql_select_db("es_restaurant");
$term=$_GET["term"];
$query=mysql_query("SELECT fld_product_id,fld_product_name
FROM tbl_product_master_header
where fld_product_name like '%".$term."%' ");
$json=array();
while($product_name=mysql_fetch_array($query))
{
$json[]=array(
'value'=> $product_name["fld_product_name"]
//I want to add one more column value to display fld_product_id in
//another text box
);
}
echo json_encode($json);
?>
Try hanging the code to this:
$json = array();
while($product_name=mysql_fetch_array($query)) {
$json[]= $product_name["fld_product_name"];
}
echo json_encode($json);
I think because you are adding another layer to the array it is not working.
http://jqueryui.com/autocomplete/ shows using an array without keys.
http://www.smarttutorials.net/jquery-autocomplete-search-using-php-mysql-and-ajax/ also confirms this.
As to your comment try this:
while($product_name=mysql_fetch_array($query)) {
$json[]= array('id' => $product_name["fld_product_id"],
'value' => $product_name["fld_product_name"]);
}
http://www.simonbattersby.com/blog/jquery-ui-autocomplete-with-a-remote-database-and-php/

javascript display and hide div element

I am new to Javascript, and I currently have an article that is being fetched from database, the article has two rows. title & content there are about 100 of these in my database. Now the objective is to list all the titles first, and when a user clicks on a title, to make the the relevant content appear underneath it. I can do this however this way.
<?php
//mysql query here...
foreach($result as $row) { ?>
<div id='title'> <?= $row['title'] ?> </div>
<div id='<?= $row['id'] ?>' style='display:none'
onclick=showContent(<?= $row['id'] ?>) > <?= $row['content'] ?>
</div>
<?php } ?>
The javascript to hide the show the content is this:
<script type='text/javascript'>
function showContent(id){
document.getElementById(id).style.display='inline';
}
</script>
The showContent() function hides the div based on the id passed through the paramenter.
But, the only problem is that, I need other previously displayed divs to truntate when a new one opens.
Meaning, the content should be visible only once, then when you click on another title, the previously opened content should disappear and only the new content should appear.
I hope that made sense. as I am lacking the grammar to explain it all. I tried to give small example here, which for some reason does not seem to work at all, but does in my localhost http://jsfiddle.net/YL6aH/
EDITED:
My full PHP loop, together will all the js/html
<?php
$articlesForPreview = $createQuery
->query("SELECT * FROM timeline");
$fetchAll = $articlesForPreview->fetchAll(PDO::FETCH_ASSOC);
foreach($fetchAll as $row) {?>
<div id='timeline_container'>
<span class='timeline_date'> <?= $row['time'] ?></span>
<span class='timeline_title'> <a href='#' onclick=timeline(<?= $row['id'] ?>)><?= $row['title'] ?></a></span>
<p id='<?= $row['id'] ?>' style='display:none;'> <?= $row['event'] ?></a></span>
</div>
<?php }?>
</aside>
</section>
<script type='text/javascript'>
function timeline(id){
document.getElementById(id).style.display='inline';
}
</script>
<footer id='footer_container'>
You can simply remember the last item that is visible:
var active;
function showContent(id){
if (active) active.style.display = 'none'; // hide previously visible element
active = document.getElementById(id); // keep track of the element you are about to show
active.style.display='inline'; // show the new element
}
Keep in mind that this solution starts with no items visible and after that only allows one item to be visible at a time.
You should try this :
function showContent(id){
$('.active').hide().removeClass('active');
$('#'+id).show().addClass('active');
}
I see also that you will have multiple elements with id=title, you must change it to make every elem unique.
You can go through all elements with an onclick of "showContent", hide them all, afterwards you can just show the one you want.
function showContent(id){
var allElements = document.getElementsByTagName('*');
for ( var i = 0; i<allElements.length; i++ ) {
if ( (allElements[i].onclick + "").indexOf("showContent") >= 0) {
allElements[i].style.display = "none";
}
}
document.getElementById(id).style.display='inline';
}
I'm pretty new to javascript and jquery myself, but one of the things we just did in the class I'm taking was the accordion display, where you attach event handlers in the document.ready for the click events for the header objects, and their div children elements, and it was done by swapping the css classes on the click events... are you using css? in our version, anytime we clicked on a plus, it would expand the display to display the divs below, and clicking the minus pic it would close them... ours did it for all of them, but you should be able to code that even to "close" all of those displays, and then open/display only the divs that are children for the item clicked... is that what you're looking for?

Separating variables for SQL insert using PHP and JavaScript

A grid table is displayed via PHP/MySQL that has a column for a checkbox that the user will check. The name is "checkMr[]", shown here:
echo "<tr><td>
<input type=\"checkbox\" id=\"{$Row[CONTAINER_NUMBER]}\"
data-info=\"{$Row[BOL_NUMBER]}\" data-to=\"{$Row[TO_NUMBER]}\"
name=\"checkMr[]\" />
</td>";
As you will notice, there is are attributes for id, data-info, and data-to that are sent to a modal window. Here is the JavaScript that sends the attributes to the modal window:
<script type="text/javascript">
$(function()
{
$('a').click(function()
{
var selectedID = [];
var selectedBL = [];
var selectedTO = [];
$(':checkbox[name="checkMr[]"]:checked').each(function()
{
selectedID.push($(this).attr('id'))
selectedBL.push($(this).attr('data-info'))
selectedTO.push($(this).attr('data-to'))
});
$(".modal-body .containerNumber").val( selectedID );
$(".modal-body .bolNumber").val( selectedBL );
$(".modal-body .toNumber").val( selectedTO );
});
});
</script>
So far so good. The modal retrieves the attributes via javascript. I can choose to display them or not. Here is how the modal retrieves the attributes:
<div id="myModal">
<div class="modal-body">
<form action="" method="POST" name="modalForm">
<input type="hidden" name="containerNumber" class="containerNumber" id="containerNumber" />
<input type="hidden" name="bolNumber" class="bolNumber" id="bolNumber" />
<input type="hidden" name="toNumber" class="toNumber" id="toNumber" />
</form>
</div>
</div>
There are additional fields within the form that the user will enter data, I just chose not to display the code. But so far, everything works. There is a submit button that then sends the form data to PHP variables. There is a mysql INSERT statement that then updates the necessary table.
Here is the PHP code (within the modal window):
<?php
$bol = $_POST['bolNumber'];
$container = $_POST['containerNumber'];
$to = $_POST['toNumber'];
if(isset($_POST['submit'])){
$bol = mysql_real_escape_string(stripslashes($bol));
$container = mysql_real_escape_string(stripslashes($container));
$to = mysql_real_escape_string(stripslashes($to));
$sql_query_string =
"INSERT INTO myTable (bol, container_num, to_num)
VALUES ('$bol', '$container', '$to')
}
if(mysql_query($sql_query_string)){
echo ("<script language='javascript'>
window.alert('Saved')
</script>");
}
else{
echo ("<script language='javascript'>
window.alert('Not Saved')
</script>");
}
?>
All of this works. The user checks a checkbox, the modal window opens, the user fills out additional form fields, hits save, and as long as there are no issues, the appropriate window will pop and say "Saved."
Here is the issue: when the user checks MULTIPLE checkboxes, the modal does indeed retrieve multiple container numbers and I can display it. They seem to be already separated by a comma.
The problem comes when the PHP variables are holding multiple container numbers (or bol numbers). The container numbers need to be separated, and I guess there has to be a way the PHP can automatically create multiple INSERT statements for each container number.
I know the variables need to be placed in an array somehow. And then there has to be a FOR loop that will read each container and separate them if there is a comma.
I just don't know how to do this.
When you send array values over HTTP as with [], they will already be arrays in PHP, so you can already iterate over them:
foreach ($_POST['bol'] as $bol) {
"INSERT INTO bol VALUES ('$bol')";
}
Your queries are vulnerable to injection. You should be using properly parameterized queries with PDO/mysqli
Assuming the *_NUMBER variables as keys directly below are integers, use:
echo '<tr><td><input type="checkbox" value="'.json_encode(array('CONTAINER_NUMBER' => $Row[CONTAINER_NUMBER], 'BOL_NUMBER' => $Row[BOL_NUMBER], 'TO_NUMBER' => $Row[TO_NUMBER])).'" name="checkMr[]" /></td>';
Then...
$('a#specifyAnchor').click(function() {
var selectedCollection = [];
$(':checkbox[name="checkMr[]"]:checked').each(function() {
selectedCollection.push($(this).val());
});
$(".modal-body #checkboxCollections").val( selectedCollection );
});
Then...
<form action="" method="POST" name="modalForm">
<input type="hidden" name="checkboxCollections" id="checkboxCollections" />
Then...
<?php
$cc = $_POST['checkboxCollections'];
if (isset($_POST['submit'])) {
foreach ($cc as $v) {
$arr = json_decode($v);
$query = sprintf("INSERT INTO myTable (bol, container_num, to_num) VALUES ('%s', '%s', '%s')", $arr['BOL_NUMBER'], $arr['CONTAINER_NUMBER'], $arr['TO_NUMBER']);
// If query fails, do this...
// Else...
}
}
?>
Some caveats:
Notice the selector I used for your previous $('a').click() function. Do this so your form updates only when a specific link is clicked.
I removed your mysql_real_escape_string functions due to laziness. Make sure your data can be inserted into the table correctly.
Make sure you protect yourself against SQL injection vulnerabilities.
Be sure to test my code. You may have to change some things but understand the big picture here.

cakephp javascript dynamic update

all creating a cakephp(using 2.1.2) page. we prompt the user to enter how many fields they are after(an int) and then we want the page to use a for-loop for the number entered.
here is the code for the add page
<h2>Please select how many fields you wish to add</h2></br>
<?php
print $this->Session->flash('flash', array('element' => 'alert'));
echo $this->Form->create('Field', array('action'=>'add'));
For(int i=0; i<'flash'; i++)
{
echo $this->Form->input('name',array('label'=>'Please Enter Field Name: ', 'type'=>'text'));
echo $this->Form->input('description',array('label'=>'Please Enter Field Description: ', 'type'=>'text'));
}
echo $this->Form->end('Click Here To Submit Template');
?>
here is the code for the alert
<script type="text/javascript">
prompt('How many fields?','<?php print $message; ?>');
</script>
the question is how do we create a variable with the alert.ctp then be able to use that variable for a for loop to print out a form that takes user input.
EDIT:
Javascript function:
<script type="text/javascript">
var number_of_fields=prompt("How many fields?",'<?php print $message; ?>');
var field_html="";
for (i=0; i<number_of_fields; i++)
{
field_html +='<input type="text" name="data[FIELD]['+i+'][name]">';
}
$("#FORMID").append(field_html);
</script>
View:
<?php
print $this->Session->flash('flash', array('element' => 'alert'));
echo $this->Form->create('Field', array('action'=>'add'));
echo $this->Form->end('Click Here To Submit Template');
?>
Get no errors now, but cant display any fields. What do we put in the view to print the fields (which will be more input- so user can create a field)?
Since we are getting the value of no: of required in javascript , i recommend to create fields also in javascript by following conventions used by cakephp to create input fields. So you can use javascript for loop and concat the fields in to a js variable and insert this html inputs to the form using javascript.
eg:
var number_of_fields=prompt("How many fields?",'<?php print $message; ?>');
var field_html="";
for (i=0; i<number_of_fields; i++)
{
field_html +='<input type="text" name="data[MODELNAME]['+i+'][name]">';
}
$("#FORMID").append(field_html);
i hope this would make sense

Categories

Resources