How to print PHP dropdown in a loop using JavaScript - php

I am trying to print the text-box and the drop-down from a database. I am printing the text-box and drop-down based on the input given.
For example: say I am giving the input as 4. For that, it will create four text-boxes and drop-downs.
But I have the dropdown code in PHP, so now I want to print the PHP dropdown in a loop using JavaScript. How can I do this?
JavaScript code:
function create(param) {
'use strict';
var i, target = document.getElementById('screens');
target.innerHTML = '';
for(i = 0; i < param; i += 1) {
target.innerHTML +='</br>';
target.innerHTML +='New Movie '+i+' ';
target.innerHTML += '<input type="text" name="Fname">';
target.innerHTML +=' '+'Language '+' ';
target.innerHTML += '<input type="text" name="timings">';
target.innerHTML +='</br>';
target.innerHTML +='</br>';
}
}
PHP dropdown:
<?php
try {
$dbh = new PDO('mysql:dbname=theaterdb;host=localhost','tiger','tiger');
}
catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = "SELECT language FROM languages;";
$sth = $dbh->prepare($sql);
$sth->execute();
echo "<select name='language' id='course'>";
echo "<option>----Select Language----</option>";
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo "<option value='" . $row['language'] ."'>" . $row['language']. "</option>";
}
echo "</select>";
?>
In place of
target.innerHTML += '<input type="text" name="timings">';
I should get a PHP dropdown instead of a textbox.

The easy way, since you have both codes....
function create(param) {
'use strict';
var i, target = document.getElementById('screens');
target.innerHTML = '';
<?php
try {
$dbh = new PDO('mysql:dbname=theaterdb;host=localhost','tiger','tiger');
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = 'SELECT language FROM languages;';
$sth = $dbh->prepare($sql);
$sth->execute();
$combo = "<select name='language' id='course'>";
$combo .= "<option>----Select Language----</option>";
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$combo .= "<option value='" . $row['language'] ."'>" . $row['language']. "</option>";
}
$combo .= "</select>";
?>
for(i = 0; i < param; i += 1) {
target.innerHTML +='</br>';
target.innerHTML +='New Movie '+i+' ';
target.innerHTML += '<input type="text" name="Fname">';
target.innerHTML +=' '+'Language '+' ';
target.innerHTML += "<?php echo $combo; ?>";
target.innerHTML +='</br>';
target.innerHTML +='</br>';
}
}

Related

jQuery href adding variables

I hope this is not a duplicate but I have not found it yet.
To be honest I found this method online and and cant find where I original found it or I would search there for the answer. The below is a test page I am testing my code.
My question is this how do I keep the clock value in the href and add the cellnumber to the href ?? Right now I get dropdowntest.php?cellnumber=8&?clock=8 which is the same value as the cellnumber I believe is in the line:
+ ['?cellnumber', $(this).val()].join('=') + ['&?clock', $(this).val()].join('=');
I have tried changing $(this) on the clock but I could not find the correct syntax.. below is all the code:
<?php
session_start();
require('/db_connection/connect.db.php');
require('settings.php');
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.clock').on('change', function() {
location.href = location.href.split('?')[0]
+ ['?clock', $(this).val()].join('=');
});
$('.cellnumber').on('change', function() {
location.href = location.href.split('?')[0]
+ ['?cellnumber', $(this).val()].join('=') + ['&?clock', $(this).val()].join('=');
});
});
</script>
<?php
$clock = mysqli_query($connection, "SELECT username FROM user WHERE wocreate = 1 and hide = 1");
echo "<select class='clock' name='clock' style='width:200px'>";
echo "<option size =30 ></option>";
while($row = mysqli_fetch_array($clock)){
echo "<option value='".$row['username']."''>".$row['username']."</option>";
}
echo "</select>";
if (isset($_GET['clock'])) {
$_SESSION['clock'] = $_GET['clock'];
echo "<p></p>";
echo 'Person Requesting Ticket is '.$_SESSION['clock'].'';
echo "<p></p>";
}
?>
<?php
echo "<br>";
$cellnumbers = mysqli_query($connection, "SELECT DISTINCT location FROM machinenumber WHERE status = 1 ");
echo "<select class='cellnumber' name='cellnumber' style='width:200px'>";
echo "<option size =30 ></option>";
while($row = mysqli_fetch_array($cellnumbers)){
echo "<option value='".$row['location']."''>".$row['location']."</option>";
}
echo "</select>";
if (isset($_GET['cellnumber'])) {
$_SESSION['cellnumber'] = $_GET['cellnumber'];
echo "<p></p>";
echo 'Person Requesting Ticket is '.$_SESSION['clock'].'';
echo "<br>";
echo 'Cell '.$_SESSION['cellnumber'].' is the location';
echo "<p></p>";
}
?>
<?php
if (isset($_GET['cellnumber'])) {
$cellnumber=$_GET['cellnumber'];
echo "<h3>Choose Machine Number</h3>";
$machinenumber = mysqli_query($connection,"SELECT number FROM machinenumber WHERE location =".$cellnumber." ;");
echo "<select class='machinenumber' name='machinenumber' style=width:200px>";
echo "<option size =30 ></option>";
while($row = mysqli_fetch_array($machinenumber)) {
echo "<option value='".$row['number']."'>".$row['number']."</option>";
}
echo "</select>";
}
?>

Variable empty without reason

I am developing a shopping cart system and everything is working perfectly, except for one thing.
Well, I use PHP SESSION to store the data for each product, including ID, name, price and quantity. All variables are correctly completed, unless the price variable. I do not know why! I use jQuery to fetch the values and send them to the page that will process them in the SESSION.I will put the relevant parts of my code to facilitate. This is the content of my products.php:
<?php
session_start();
?>
<html>
<body>
<?php
$connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$sql = "SELECT id, name, price FROM products ORDER BY id";
$result = $connection->query($sql);
if ($result->num_rows > 0)
{
echo "<table>";
echo " <tr>";
echo " <th>ID</th>";
echo " <th>NAME</th>";
echo " <th>PRICE</th>";
echo " <th>QUANTITY</th>";
echo " </tr>";
while($row = $result->fetch_assoc())
{
echo " <tr>";
echo " <td><div class='id-product'>". $row["id"]."</div></td>";
echo " <td><div class='name-product'>". $row["name"]."</div></td>";
echo " <td>$<div class='price-product'>". $row["price"]."</div></td>";
echo " <form class='add'>";
echo " <td><input type='number' name='quantity' value='1' min='1'/></td>";
echo " <td><button type='submit'>Add</button></td>";
echo " </form>";
echo " </tr>";
}
echo "</table>";
}
$connection->close();
?>
<script>
$(document).ready(function()
{
$('.add').on('submit', function()
{
var id = $(this).closest('tr').find('.id-product').text();
var name = $(this).closest('tr').find('.name-product').text();
var price = $(this).closest('tr').find('.price-product').val();
var quantity = $(this).closest('tr').find('input').val();
window.location.href = "add.php?id=" + id + "&name=" + name + "&price=" + price + "&quantity=" + quantity;
return false;
});
});
</script>
<body>
</html>
Now in add.php I have the following:
<?php
session_start();
$id = isset($_GET['id']) ? $_GET['id'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";
$price = isset($_GET['price']) ? $_GET['price'] : "";
$quantity = isset($_GET['quantity']) ? $_GET['quantity'] : "";
$cart_item = array
(
'id' => $id,
'name' => $name,
'price' => $price,
'quantity' => $quantity
);
if(!isset($_SESSION['cart']))
{
$_SESSION['cart'] = array();
}
if(array_key_exists($id, $_SESSION['cart']))
{
header('Location: products.php?action=exists&id=' . $id . '&name=' . $name);
}
else if($quantity <= 0)
{
header('Location: products.php?action=invalidquantity&id=' . $id . '&name=' . $name);
}
else
{
$_SESSION['cart'][$id] = $cart_item;
header('Location: products.php?action=added&id=' . $id . '&name=' . $name);
}
?>
To show the products that exists in the SESSION, I use foreach in my page cart.php:
$total = 0;
foreach($_SESSION['cart'] as $id)
{
echo "<tr>";
echo "<td>{$id['name']}</td>";
echo "<td>${$id['price']}</td>";
echo "<td>{$id['quantity']}</td>";
echo "<td>";
echo "<a href='remove.php?id={$id['id']}&name={$id['name']}'>Remove</a>";
echo "</td>";
echo "</tr>";
$total += ($id['price'] * $id['quantity']);
}
As I said earlier, I have returned the values of ID, name and quantity, but the price remains empty. What's wrong?
You're not setting the price right in your JS i believe.
window.location.href = "add.php?id=" + id + "&name=" + name + "&price" + price + "&quantity=" + quantity;
return false;
Should be
window.location.href = "add.php?id=" + id + "&name=" + name + "&price=" + price + "&quantity=" + quantity;
return false;
See difference in jquery's .val and .text
Difference between val() and text()
try this:
var price = $(this).closest('tr').find('.price-product').text();

Mark an option as selected

I am populating a dropdown menu with data in a database, using this code:
$query = "SELECT * FROM my_gallery";
$execute = mysqli_query($link, $query);
$results = mysqli_num_rows($execute);
if ($results!=0) {
echo '<label>The galleries are: ';
echo '<select id="galleries" name="galleries">';
echo '<option value=""></option>';
for ($i=0; $i<$results; $i++) {
$row = mysqli_fetch_array($execute);
$name = htmlspecialchars($row['galleryName']);
echo '<option value="' .$name. '">' .$name. '</option>';
}
echo '</select>';
echo '</label>';
}
I want to add the selected=selected to the option selected and then use that option in another query, but I have problem adding the selected tag in the actual selected entry.
More INFO:
I am using dropzone.js to upload images, and I want to select the category on the fly. The category has to be selected from the dropdown menu and used in the INSERT query.
if you have a form with POST then the code is
$selected = "";
if($_POST['galleries']==$name) $selected=" selected='selected'";
echo '<option value="' .$name. '"'.$selected.'>' .$name. '</option>';
Just as an example try this,
$query = "SELECT * FROM my_gallery";
$execute = mysqli_query($link, $query);
$results = mysqli_num_rows($execute);
if ($results!=0) {
echo '<label>The galleries are: ';
echo '<select id="galleries" name="galleries">';
echo '<option value=""></option>';
for ($i=0; $i<$results; $i++) {
$row = mysqli_fetch_array($execute);
$name = htmlspecialchars($row['galleryName']);
if( $i == 1 )
{
$sel = 'selected="selected"';
}
else
{
$sel = '';
}
echo '<option value="' .$name. '"'. $sel .' >' .$name. '</option>';
}
echo '</select>';
echo '</label>';
}
If you want to select a specific option then you are going to have a variable containing that specific option example:
$conditionalName = "Mark";
$query = "SELECT * FROM my_gallery";
$execute = mysqli_query($link, $query);
$results = mysqli_num_rows($execute);
if ($results!=0) {
echo '<label>The galleries are: ';
echo '<select id="galleries" name="galleries">';
echo '<option value=""></option>';
for ($i=0; $i<$results; $i++) {
$row = mysqli_fetch_array($execute);
$name = htmlspecialchars($row['galleryName']);
echo '<option value="' .$name. '"'; if($name=$conditionalName){ echo ' selected=selected';} echo '>'. $name. '</option>';
}
echo '</select>';
echo '</label>';
}

How to add dropdown dynamically

I am trying to add the dynamic drop down through javascript.
i have a dropdown which has numbers, when selected creates the drop down.
but i want to add the dynamic dropdown through javascript.
how can i do this?
here is php code
code:
<?php
try {
$dbh = new PDO('mysql:dbname=theaterdb;host=localhost','tiger','tiger');
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = "SELECT theater_name FROM theater;";
$sth = $dbh->prepare($sql);
$sth->execute();
echo "<select name='theater_name' id='course' onchange='showUser(this.value);'>";
echo "<option>----Select Theater----</option>";
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo "<option value='" . $row['theater_name'] ."'>" . $row['theater_name']. "</option>";
}
echo "</select>";
?>
This php code gets the drop down values from mysql database.
but this drop down will be created dynamically from javascript
javascript code
function create(param) {
'use strict';
var i, target = document.getElementById('screens');
target.innerHTML = '';
for(i = 0; i < param; i += 1) {
target.innerHTML +='</br>';
target.innerHTML +='Movie in hall '+i+' ';
target.innerHTML += '<?php
try {
$dbh = new PDO('mysql:dbname=theaterdb;host=localhost','tiger','tiger');
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = "SELECT theater_name FROM theater;";
$sth = $dbh->prepare($sql);
$sth->execute();
echo "<select name='theater_name' id='course' onchange='showUser(this.value);'>";
echo "<option>----Select Theater----</option>";
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo "<option value='" . $row['theater_name'] ."'>" . $row['theater_name']. "</option>";
}
echo "</select>";
?>';
target.innerHTML +=' '+'Timings '+' ';
target.innerHTML += '<input type="text" name="timings">';
target.innerHTML +='</br>';
target.innerHTML +='</br>';
}
}
so now i have added this php code in javascript but it is not creating the dropdown..
Why? How can i do this
You are using PHP to generate JavaScript as the JavaScript is interpreted by the browser and PHP is processed by the server the code below will not work
target.innerHTML += '<?php'; ...
For you to understand the process is as follows,
Server reads and processes the php
The server generates the HTML from php
The JavaScript that is contained in the HTML is interpreted by the browser
what you can do is pass data to javascript, and generate the dropdown.
or if you need information from the User (as parameters) to generate the dropdown, you can make a request by ajax.
the link explain about the ajax with dropdown -> http://imasters.com.br/artigo/3918/javascript/ajax-e-php-carregando-dados-sem-refresh/
This is a string delimiter problem. You are using single quotes ' for your javascript string in
target.innerHTML += '<?php
so the string is supposed to end at the first next single quote, that is the first echoed in this line:
echo "<select name='theater_name' id='course' onchange='showUser(this.value);'>";
Javascript interpreter ends the string in ...<select name=. There is no operator or ; after that, (there is the character t) and it stucks.
You should just add a backslash \ in front of each single quote, as an escape:
echo "<select name=\'theater_name\' id=\'course\' onchange=\'showUser(this.value);\'>";
Or you can substitute the string delimiter for your echo, using the same delimiter for both javascript and php like:
echo '<select name="theater_name" id="course" onchange="showUser(this.value);">';
The same occurs in the third echo, in while.
There is some difference in PHP while using single ' or double quote " as a string delimiter: double quoted strings have more escape sequences and do expand variables. Please refer to PHP docs while making your choice. Any choice has no consequences in your script.

How to insert multiple values into database using php for loop

i have one textbox and one dropdown box in each row.
now i want to enter some date in text box and select some value in dropdown.
when i click it should get saved into database.
How can i do this?
here is my code
php insert code:
When i click submit this php code should
<?php
mysql_connect("localhost", "tiger", "tiger") or die(mysql_error());
mysql_select_db("theaterdb") or die(mysql_error());
$query = mysql_query("INSERT INTO movie (movie_name,language) VALUES('$_POST[Fname]','$_POST[language]') ") or die(mysql_error());
?>
drop down is generated dynamically
code:
function create(param) {
'use strict';
var i, target = document.getElementById('screens');
target.innerHTML = '';
for(i = 0; i < param; i += 1) {
target.innerHTML +='</br>';
target.innerHTML +='New Movie '+i+' ';
target.innerHTML += '<input type="text" name="Fname">';
target.innerHTML +=' '+'Language '+' ';
target.innerHTML += "<?php
try {
$dbh = new PDO('mysql:dbname=theaterdb;host=localhost','tiger','tiger');
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = 'SELECT language FROM languages;';
$sth = $dbh->prepare($sql);
$sth->execute();
echo "<select name='language' id='course'>";
echo "<option>----Select Language----</option>";
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo "<option value='" . $row['language'] ."'>" . $row['language']. "</option>";
}
echo "</select>";
?>";
target.innerHTML +='</br>';
target.innerHTML +='</br>';
}
}
the ui looks something like this...
Add name
for text box and select box like this
name="text_box"+i and name="select_box"+i. "i"
is value from counter in loop, for example if you have 100 New Moview you will have name for each text box like this text_box1, text_box2. ..... text_box100. You should on submit remeber the numbers of "New MovieS" and that is "i" and in php code just loop for each element and save them. In first iteration you will have $_POST[Fname1] and $_POST[language1], etc..
Add a line in your js which makes the inputs to print something along the lines of target.innerHTML = '<input name="RowCount" value="' + param + '" hidden />' then in your PHP use:
for ($i=0; $i < $_POST["RowCount"]; $i++) {
$query = sprintf("INSERT INTO movie ('movie_name', 'language') VALUES ('%s', '%s')",
mysqli_real_escape_string($_POST["Fname"]), // Escaping values before inserting.
mysqli_real_escape_string($_POST["language"]));
mysqli_query($con, $query);
}
in HTML Form: Set textbox and dropdown element name as same algorithm ElementName+RowNumber;
insert element for RowCount: <input type="hidden" name="RowCount" value="3">
in PHP: get values:
for($iRow=0;$iRow less $_POST['RowCount'];$iRow++) {
mysql_query("INSERT INTO movie (movie_name,language) VALUES('".$_POST['Fname'.$iRow]."','".$_POST['language'.$iRow]."');
}

Categories