Javascript and PHP radio buttons to change visibility - javascript

I'm trying to work my way through a problem. It's two parts:
I want to create a loop that reads out each of my page's menu_name from the database and on the same line that it reads it out, put a radio button to change the visibility. So far It looks like my radio buttons are all connected because (instead of being checked "no" for each of them it is only checked no on the last <li> item:
//K's function:
function get_all_pages() {
global $connection;
$query = "SELECT *
FROM pages ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$page_set = mysql_query($query, $connection);
confirm_query($page_set);
return $page_set;
}
//K's function:
function list_all_pages(){
$output = "<ul>";
$page_set = get_all_pages();
while ($page = mysql_fetch_array($page_set)) {
$output .= "<li>{$page["menu_name"]}</li>";
$output .= " <input type=\"radio\" name=\"visible\" value=\"0\" checked=\"checked\" /> No <input type=\"radio\" name=\"visible\" value=\"1\" /> Yes";
}
$output .= "</ul>";
return $output;
}
I'm trying to do some sort of ajax thing with Javascript.. so I want the visible radio buttons to be next to my dynamically generated menu list. I want them to all be checked to no... when they are checked to yes I want a dropdown list to appear where they can pick the numbers 1-8 (the numbers will mean what position they will appear in).
I am new and trying to figure this out is a little out of my reach without some assistance from Javascript and php/mysql experts.

Your radio buttons all have the same "name" attribute, so you can only select one at a time. You could append some unique identifier to the attribute value. For example, visible_{$page_id}:
function list_all_pages(){
$output = "<ul>";
$page_set = get_all_pages();
while ($page = mysql_fetch_array($page_set)) {
$page_id = urlencode($page["id"]);
$output .= "<li>{$page["menu_name"]}</li>";
$output .= " <input type=\"radio\" name=\"visible_{$page_id}\" value=\"0\" checked=\"checked\" /> ";
$output .= "No <input type=\"radio\" name=\"visible_{$page_id}\" value=\"1\" /> Yes";
}
$output .= "</ul>";
return $output;
}
Advanced tip: With PHP you can simplify the processing of "page" data by using specially-formatted input names -- like so:
Let the radio buttons use names like pages[$page_id][visible].
Let the lists (aka select) use a name like pages[$page_id][order].
Once the user submits this data, PHP converts it into a "pages" array (with indices being page_id's). You can then do something like:
function process_pages($pages) {
foreach ($pages as $page_id => $data) {
$is_visible = $data['visible'] === '1';
$page_order = (int) $data['order'];
//... update page's visibility/page order
}
}
$pages = $_REQUEST['pages'];
process_pages($pages);

1. Change the name attribute of each radio button to disconnect them e.g. use visible1, visible2, ...
2. put the <input> tag within <li> after your <a> tag. That will show your radio buttons next to your dynamically generated menu.
3. You can create select list for number by creating and calling a javascript function that will be executed by onclick of Yes options, which will create and show the select fields.
Please comment on the answer if you need more clarification.

Related

How to make the div editable to textarea and upload/delete existing images

I have a website where user can upload images, name and description. I am saving it in mysql and fetching that information to show on my website. That's what my below code does, let the user enter those information (image and text) and show it on the website when they click submit button.
My question is how can I make the div (that shows images, name and desc) to editable when user clicks the edit button (so change that same div to textarea or something that is editable) and for images should have an cross mark near the image when clicked on edit button, so user can delete it and upload button to upload more images.
What I have done: I try to use javascript to get the value of div and use that to change it to textarea, but it says the value is undefined for the grid div.
So, how can I make my div editable as explained above, as what I have try so far is not complete, so is there any better way to make the div editable same way I explained above so user can edit text and upload or delete images?
My code:
<?php
require "database.php"; // connecting to database
session_start();
global $username;
$username = $_SESSION['userUsername'].$_SESSION['userId']; //fetching the username
$image = "userPos/$username"; //fetching image posted by specific user
function listFolderFiles($dir, $username){
<!-- The div my_class is getting the images from local storage
that was initially uploaded by user in the website
(and we stored it in the local storage) to display them on the website -->
echo '<div class="my_class">';
$ffs = scandir($dir);
unset($ffs[array_search('.', $ffs, true)]);
unset($ffs[array_search('..', $ffs, true)]);
// prevent empty ordered elements
if (count($ffs) < 1)
return;
foreach($ffs as $ff){
$s = "'<li>'.$ff";
$saving = "$dir/$ff";
$string = "$saving";
global $string_arr;
$string_arr = (explode("/",$string));
$sav;
$sav = '<li>'.$ff;
global $sa;
$sa = "$ff";
echo '<div class="imagess">';
if(is_file($saving)) {
echo '
<div class="images">
<img src="'.$saving.' " width="100" height="100" alt="Random image" class="img-responsive" />
</div>
' ;
}
echo `</div>`;
if(is_dir($dir.'/'.$ff)) listFolderFiles($dir.'/'.$ff, $username);
}
echo `</div>`;
require "database.php";
<!--Here we are fetching the name and description
that was entered by user on the website
and displaying them on the website now-->
$username = $_SESSION['userUsername'].$_SESSION['userId'];
$sql = "SELECT * FROM `_desc` WHERE `username` = '$username' AND `id` = '$string_arr[2]';";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if($resultCheck > 0) {
echo '</br>';
while($row = mysqli_fetch_assoc($result) ) {
//name and desc
echo '<div class="grid">' . '<h2>' . $row["_name"] . '</h2>' . '</div>';
echo '<div class="grid2">' . '<p>' . $row["_desc"] . '</p>' . '</div>';
}
<!--Here I am trying when user click on edit button it should
change that div to editable textarea so user can edit
and save it or delete the whole div-->
echo '<button onClick="editName()" class="btn btn-info">
Edit</button>';
echo '<a href="deleteUserInfo.php?edit= '.
$row["id"].'"class="btn btn-danger ">Delete</a>';
}
echo '</div>';
}
listFolderFiles($image, $username);
?>
<script>
function editName() {
console.log("calling");
var divName = $("grid").html();
console.log(divName); //value is undefined here
var editableName = $("<textarea />");
editableName.val(divName);
$("grid").replaceWith(editableName);
editableName.focus();
editableName.blur(saveName);
}
function saveName() {
var htmlName = $(editableName).html();
var viewableText = $("<div>");
viewableText.html(htmlName);
$(editableName).replaceWith(viewableText);
$(viewableText).click(editName);
}
</script>
</body>
</html>
It is quite simple, you should use contenteditable attribute available and set that value to true. This will make the div element editable.
Like this,
<div class="grid" contenteditable="true">I am editable!</div>
In your case, you should use a function to select the element and set the attribute to true. And for the div element on clicking the type='file' input tag, you can write function that will delete the file that is previously uploaded and upload the new file. I would recommend you to research before posting a question in the community as you might get negative impacts on such questions. Hope it helps! Happy coding!!
When the user clicks the edit button, set the contenteditable attribute to true on the target element and set the focus to that element.
function editName() {
$("grid").attr("contenteditable", true);
$("grid").focus();
$("grid").blur(saveName);
}

Renaming input Fields IDs in a form created with a while loop

I am trying to POST a form that is generated through a while loop that iterates on some elements of a table and they can vary in number according to the different companies. Because the IDs of the input/edit fields are created by a while-loop they all have the same id and this is creating a problem when I try to submit the form, is there a way to change automatically the IDs? I tried to use Javascript with no success. Is there a way to name the IDs according to the loop cycle?
Also is there a better way to create a number of input/edit fields according to the number of items to be edited in an SQL table?
echo '<form id="myForm" action="edit.php" method="POST">';
echo '<div class="leftcontact">';
$i=0;
while($query_data = mysqli_fetch_row($result)) {
$_SESSION["List"]=$query_data[2];
$_SESSION["List_company_id"]=$query_data[0];
$result2 = mysqli_query($connection, "SELECT * FROM `calling_lists` WHERE `calling_list_id`='".$_SESSION["List"]."'");
$query_data2 = mysqli_fetch_row($result2);
$_SESSION["list_name"]=$query_data2[1];
echo '<div class="form-group">';
echo '<p>List number</p>';
echo '<select class="dropdown" name="ID">';
echo "<option selected = 'selected' value=\"".$_SESSION["List_company_id"]."\">".$_SESSION["list_name"]."</option>";
$query1="SELECT * FROM `calling_lists`";
$result1=mysqli_query($connection,$query1) or die ("Query to get data from list table failed: ".mysql_error());
while ($row1=mysqli_fetch_array($result1)) {
$list_name=$row1["calling_list_name"];
$list_description=$row1["calling_list_description"];
$list_id=$row1["calling_list_id"];
echo "<option value=\"$list_id\">"
. $list_name .
"</option>";
};
$i=$i+1;
};
Just use your $i variable to create the id attribute of the controls you emit from your while loop. So they would be named for example “select1”, “select2” and so on.
it was late and I could not figure out the answer, but with a fresh look I found it. In the code there are actually 2 problems, one is that the operator is missing and there was a problem with " ' ".
The working code is here below, in case anybody needs it. It creates a number of dropdown menu, as many as my $results rows.
Hope it helps anybody.
$i=0;
while($query_data = mysqli_fetch_row($result)) {
$_SESSION["List_company_id"]=$query_data[3];
$_SESSION["List"]=$query_data[1];
$_SESSION["list_name"]=$query_data2[2];
echo '<div class="form-group">';
echo "<p>List number $i</p>";
echo '<span class="icon-case hidden-xs"><i class="fa fa-home"></i></span>';
echo "<select class='dropdown' name=\"".$_SESSION['List_company_id']."\">";
echo "<option selected = 'selected' value=\"".$_SESSION["List_company_id"]."\">".$query_data[2]."</option>";
$query1="SELECT * FROM `calling_lists`";
$result1=mysqli_query($connection,$query1) or die ("Query to get data from list table failed: ".mysql_error());
while ($row1=mysqli_fetch_array($result1)) {
$list_name=$row1["calling_list_name"];
$list_description=$row1["calling_list_description"];
$list_id=$row1["calling_list_id"];
echo "<option value=\"$list_id\">
$list_name
</option>";
};
echo "</select>";
echo "</div>";
$i=$i+1;
};

Transferring data with PHP and AJAX

I'm having a few problems with my "architecture". I'm really rusty in this field.
So the code below is basically PHP that reads a database table and prints row by row (columns are "name" (text), and "votes" (int) ) with a button near each row which is named by the "name" column as in the table.
Very simple by now, works perfectly.
Now, each button should add +1 to a row in table in the database (to votes column), by the name of the button, simple, but since the number of buttons is not constant and is changing by the number of rows in each table (dynamic), I need to create a JS event that will get a button pressed with its name/value, and call a php function (I need specifically with functions) with the name as a variable (parameter), so it will add +1 to the votes where the name is the name pressed).
$allsql = "SELECT * FROM `voting` ORDER BY `voting`.`groupName` DESC, `voting`.`votes` DESC";
$result = mysqli_query($conn, $allsql);
if (mysqli_num_rows($result) > 0) {
echo '<form method="post" id="voting_area">';// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$name = $row["name"];
$votes = $row["votes"];
echo 'name: ' .$name. ' - votes: ' .$votes. ' <button type="button" name="'.$name.'" value="'.$name.'">'.$name.'</button><br>';
}
echo '</form>';
}
Please try and explain me specifically each code (JS, AJAX, PHP).

dropdown value stores data upto space only

I have two dropdowns in my form.
1)Brand Name of car
2)Model name in which data is going to be retrieved from database on the basis of brand name selected.
so I have taken a div tag and appended that second dropdown.The data in dropdown is displayed properly but the problem is in storing the data selected from the second dropdown, It stores the model name upto the space only.length in the database for that field is also taken properly.
eg- if the model name is "series 1" than it will store only series.
Php page of second dropdown:
<?php
$brand = $_GET['brand'];
include('connection.php');
$sql = "select * from modelname where Brand_Name='" . $brand . "'";
$result = mysqli_query($conn, $sql);
$html = "";
$html = '<select name="model">';
while ($row = mysqli_fetch_assoc($result)) {
$html.='<option value=' . $row['M_Name'] . '>' . $row['M_Name'] . '</option>';
}
$html.='</select>';
echo $html;
?>
because you are not quoting your attributes.
value=hello world
is seen as
value="hello" world
Add the missing quotes.

getting the wrong POST value because of div show / hide

in my code i'm showing drop down select field list base on user school choice. for example -
if user choose 'School of Economics' from drop down list, i'm showing in another drop down list just the relevant lanes (based on a mysql query).
to do this i have 5 div's, on for etch school:
<div id='a'>
<span><label>Lane</label></span>
<?php
$sql = "SELECT lane_name FROM lane WHERE `lane_school_id` = 1 ORDER BY `lane_name` ASC";
$result = mysql_query($sql);
echo "<select name='lane_name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['lane_name'] ."'>" . $row['lane_name'] ."</option>";
}
echo "</select>";
?>
</div>
<div id='b'>
<span><label>Lane</label></span>
<?php
$sql = "SELECT lane_name FROM lane WHERE `lane_school_id` = 2 ORDER BY `lane_name` ASC";
$result = mysql_query($sql);
echo "<select name='lane_name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['lane_name'] ."'>" . $row['lane_name'] ."</option>";
}
echo "</select>";
?>
</div>
i have a listener to show just the right 'lane' div when user chooses school and hide all other 'lane' div's:
$(document).bind('pageinit', '#indexPage', function(){
$("#a").show();
$("#b").hide();
$("#c").hide();
$("#d").hide();
$("#e").hide();
//this will call our toggleFields function every time the selection value of School field changes
$("#school").change(function () {
toggleFieldsA();
toggleFieldsB();
toggleFieldsC();
toggleFieldsD();
toggleFieldsE();
});
});
function toggleFieldsA() {
if ($("#school").val() == 'School of Economics'){
$("#a").show();
}
else
$("#a").hide();
}
function toggleFieldsB() {
if ($("#school").val() == 'School of Computer Science')
$("#b").show();
else
$("#b").hide();
}
the problem: when user submit the form, i get the wrong 'lane_name' from POST array. i'm getting the last school selected lane value (that is hidden from the user) and not the user selected lane name , plz help
You need to give each <select> element a unique name, otherwise the last element with a particular name will be the only one you can access. PHP has no way of determining which of the 5 lane_name you are referring to.
To figure out what option set was selected you could make the first option blank: <option value=""></option>. You can add some logic to reset to the blank option when you hide/show the DIVs so only one of the lane_names will have any data in it.
The mysql_* is depreciated as of PHP 5.5.0. You should consider switching to mysqli.

Categories

Resources