get the unique id of div generated using while loop - javascript

<?php
include('config/config.php');
if($_POST)
{
$q=$_POST['searchword'];
$sql_res=mysql_query("select uid,username,email,media,country from select_tag where username like '%$q%' or email like '%$q%' order by uid LIMIT 5");
while($row=mysql_fetch_array($sql_res))
{
$username=$row['username'];
$email=$row['email'];
$media=$row['media'];
$country=$row['country'];
$b_username='<b>'.$q.'</b>';
$b_email='<b>'.$q.'</b>';
$final_username = str_ireplace($q, $b_username, $username);
$final_email = str_ireplace($q, $b_email, $email);
?>
<div class="display_box" id="display">
<img align="top" src="<?php echo $media; ?>" style="width:40px; height:40px;" />
<span class="name" id="name" data-ruid="<?php echo addslashes($row[uid]); ?>" style="position: relative;top:11px;" onclick="showselected_people();"><?php echo $final_username; ?></span></div>
<?php
}
}
?>
so i edited the post but now i m getting error "Use of undefined constatnt uid"..???

you can use uid in your span like this:
<span class="name" id="name-<?php echo $row[uid] ?>" style="position: relative;top:11px;"><?php echo $final_username; ?></span></div>
then in jquery:
$(".name").on('click', function(){
var arr = this.id.split('-');
var id = arr[1]; //its your uid
});

By this code, when you'll click on div, there will be store the user name in userName variable.
var parElem = document.getElementById('display');
parElem.addEventListener('click', getName);
var userName;
function getName(){
var allspan = this.getElementsByTagName('span');
for(var i=0; i<allspan.length; i++){
if(allspan[i].id == 'name'){
userName = allspan[i].innerHtml;
break;
}
}
}

Though #Awlad Liton's solution is adequate, I usually prefer placing such data in separate attributes.
<span class="name" id="name" data-ruid="<?php echo addslashes($row['uid']); ?>" ....
Then in JS:
$(".name").on('click', function() {
var rowId = $(this).attr("data-ruid");
//and maybe even clean it up
rowId = parseInt(rowId);
});

Related

My SQL PHP Generated edit button is only working once

I'm developing a web application which is like a notepad or a to-do list with php sql html css jquery
The query gets the list at index page and displays it and on displaying it adds a button with an "edit" class.
When they press on the edit the edit works but only once after submitting.
On submitting the button launches an ajax call with jQuery to another PHP file which edits the data and and displays all the items from the database again.
There's also an "add item" button which adds a new item. Which on submit adds a new item and also gets everything again from the database and displays it (also ajax).
The bug is either after submitting a new item or after editing, the edit button stops working
Please check the snippet below -- snippet 1 is the jquery, snippet 2 is the file to be run on ajax call, and snippet 3 is the index php file:
$("#submit").click(function(){
textarea = $("#textarea").val();
date = $("#date").val();
if(textarea == "" || date == ""){
$("#message").html("<span class='error'>Make sure you didn't leave anything empty");
}
else{
$("#message").html("");
submitItem();
$("#contentCont").fadeOut(200);
}
});
$(".edit").click(function(){
i = "edit";
itemID = $(this).attr("name");
var dateValue = $("#date"+itemID).text();
var statusValue = $("#status"+itemID).attr("name");
var textboxValue = $("#textbox"+itemID).text();
var categoryValue = $("#category"+itemID).text().toLowerCase();
$("#contentCont").fadeIn(200);
$("#textarea").val(textboxValue);
$("#date").val(dateValue);
$("#categories").val(categoryValue).prop("selected",true);
$("#status").val(statusValue).prop("selected",true);
});
function submitItem(){
textarea = $("#textarea").val();
status = $("#status").val();
category = $("#categories").val();
date = $("#date").val();
var ajaxReq = new XMLHttpRequest();
ajaxReq.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("todoCont").innerHTML = this.responseText;
}
}
ajaxReq.open("POST","../php/addItem.php",true);
ajaxReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxReq.send("textarea="+textarea+"&category="+category+"&status="+status+"&date="+date+"&itemID="+itemID+"&i="+i);
}
<?php
session_start();
require("server.php");
$cnx = new mysqli($server_name,$server_username,$server_password,$db);
$category = validate($_POST["category"]);
$item = $_POST["textarea"];
$date = $_POST["date"];
$status = validate($_POST["status"]);
$userID = $_SESSION["userID"];
$itemID = $_POST["itemID"];
$i = $_POST["i"];
$searchForCategoryID = "SELECT * FROM categories where userID='$userID' AND categoryname = '$category'";
$result = $cnx->query($searchForCategoryID);
$row = $result->fetch_assoc();
$categoryID = $row["CategoryID"];
if ($i === "new"){
$addItem = "INSERT INTO Items(userID,ItemValue,DueDate,CategoryID,Status) VALUES ($userID, '$item' , '$date' , $categoryID,'$status')";
$cnx->query($addItem);
}
else if ($i === "edit"){
$editItem = "UPDATE Items SET ItemValue='$item' , DueDate='$date' , CategoryID = $categoryID,Status='$status' WHERE itemID = $itemID " ;
$cnx->query($editItem);
}
$getTableRows = "SELECT * FROM Items WHERE userID = $userID ORDER BY DueDate";
$result = $cnx->query($getTableRows);
if($cnx->error){
echo "Could not get your stuff";
}
if($result->num_rows > 0){
while ($rows = $result->fetch_assoc()){
$getCategory = "SELECT CategoryName FROM Categories WHERE CategoryID = " . $rows["CategoryID"] . ";";
$result2 = $cnx->query($getCategory);
$rows2 = $result2->fetch_assoc();
if ($rows["Status"] == "ongoing"){
$status = "ongoing";
}else
if ($rows["Status"] == "overdue"){
$status = "overdue";
}else
if ($rows["Status"] == "done"){
$status = "done";
}
echo ' <div class="box-container">
<div class="right">
<div class="textbox">
<span id="textbox'.$rows["itemID"].'">'. $rows["ItemValue"] .'</span>
</div>
<div class="footer">
<div class="status '. $status .'" id="status'.$rows["itemID"].'" name="'.$status.'"></div>
<span class="date" id="date'.$rows["itemID"].'">'.$rows["DueDate"].'</span>
<span class="category" id="category'.$rows["itemID"].'">'.ucfirst($rows2["CategoryName"]).'</span>
<button type="button" name="'. $rows["itemID"] .'" class="btn btn-info edit">Edit</button>
</div>
</div>
</div>';
}
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php session_start();?>
<?php
include("server.php");
$cnx = new mysqli($server_name,$server_username,$server_password,$db);
$userID = $_SESSION["userID"];
<!--This is how the info is shown and the EDIT button is made-->
echo ' <div class="box-container">
<div class="right">
<div class="textbox">
<span id="textbox'.$rows["itemID"].'">'. $rows["ItemValue"] .'</span>
</div>
<div class="footer">
<div class="status '. $status .'" id="status'.$rows["itemID"].'" name="'.$status.'"></div>
<span class="date" id="date'.$rows["itemID"].'">'.$rows["DueDate"].'</span>
<span class="category" id="category'.$rows["itemID"].'">'.ucfirst($rows2["CategoryName"]).'</span>
<button type="button" name="'. $rows["itemID"] .'" class="btn btn-info edit">Edit</button>
</div>
</div>
</div>';
}
?>
you need to register your events more globally:
$("body").on("click", "#submit", function(){
});
and
$("body").on("click", ".edit", function(){
});
You need to delegate as the element is getting created dynamically.
Change the below line:
$(".edit").click(function(){
to:
$(".edit").on('click', function(){
And the same applies for
$("#submit").click(function(){
to
$("#submit").on('click', function(){

Exploding string and putting values in <select>

I have a column in my db, tip_sting:
1 row example(each one has the same format):
G1-11, G2-21, P2-50, P4-20, P100-2,
I'm using this when editing a item(I want to create(as many selects in the string) and put the values automaticaly in the select) :
https://jsfiddle.net/avrzwt6k/
So I was thinking of doing something like:
$pieces = explode(",", $tip_stingu);
$a=count($pieces); // piece1
echo $a;
echo '<br>';
echo $pieces[1]; // piece2
echo '<br>';
$tip_stinga=explode("-",$pieces);
I just dont know how could I continue?
Do you need something like this?
<?php
$items = "G1-11, G2-21, P2-50, P4-20, P100-2";
$pieces = explode(",", $items);
echo ("<select>");
foreach ($pieces as $piece) {
$tip_stinga = explode("-", $piece);
echo ('<option value="'.$tip_stinga[1].'">'.$tip_stinga[0].'</option>');
}
echo ("</select>");
?>
Using PHP & Javascript you can do:
<html>
<body>
<form id="example" name="example">
<select name="myName" id="myID" onchange="updateText()">
<?php
$tip_stingu = "G1-11, G2-21, P2-50, P4-20, P100-2,";
$pieces = explode(', ', $tip_sting);
$piece1 = explode('-', $pieces[0])[1];
foreach($pieces as $piece) {
$tip_stinga = explode("-", $piece);
echo ('<option value="'.$tip_stinga[1].'">'.$tip_stinga[0].'</option>');
}
echo '</select><input type="text" value="'.$piece1.'" id="quantity" /><br />'
?>
</form>
<script>
function updateText() {
document.getElementById("quantity").value = document.getElementById("myID").value;
}
</script>
</body>
</html>
You also have a trailing comma at the end of your example, if that's a problem you can use:
echo ('<option value="'.rtrim($tip_stinga[1], ',').'">'.$tip_stinga[0].'</option>');
instead of:
echo ('<option value="'.$tip_stinga[1].'">'.$tip_stinga[0].'</option>');

how should i put data fetched from ajax call in hidden div box

i am working on a project and come across a module.
page1
user have to search from search bar which will take him to page 2.
page2
On page 2 all fetched results will get displayed to user in div's. Each result has a checkbox associated with it.
when i click on add to compare check box ,ajax call is executed and fetched selected result should appear in hidden div.
my problem is it is only shows first result in hidden div and not working with another result.
My code of page 2
<script type="text/javascript">
$(document).ready(function()
{
var check = $('#compare').val();
$("#compare").change(function() {
if(this.checked) {
$.ajax({
type: 'POST',
url: 'compare.php',
dataType : 'JSON',
data:{value : check},
success: function(data)
{
console.log(data);
$('#compare_box').html(data);
}
});
$("#compare_box").show();
}
else
{
$("#compare_box").hide();
}
});
});
</script>
</head>
<body>
<?php
$query = $_GET['search_bar'];
$query = "call fetch_data('$query')"or die(mysqli_error($conn));
$result = mysqli_query($conn,$query);
while($row = mysqli_fetch_array($result))
{
$id = $row['course_id'];
$title = $row['course_title'];
$description = $row['course_description'];
$course_url = $row['course_url'];
$video_url = $row['course_video_url'];
$fee = $row['course_fee'];
$duration = $row['course_duration'];
$start_date = $row['course_start_date'];
$university = $row['university_name'];
$course_provider = $row['course_provider_name'];
$instructor = $row['instructor_name'];
$_SESSION['result'][$id] = Array('id'=> $id,'course_title' => $title,'course_description'=> $description,'course_url' => $course_url,'video_url' => $video_url,'fee' => $fee,'course_duration'=>$duration,'start_date'=>$start_date,'university' => $university,'course_provider'=>$course_provider,'instructor'=>$instructor);
?>
<div id='compare_box'>
</div>
<div class="col-md-3 photo-grid " style="float:left">
<div class="well well-sm">
<a href="final.php?id=<?php echo $id;?>&name=<?php echo $title;?>" target="_blank">
<h4><small><?php echo $title; ?></small></h4>
</a>
<br>
<input type ='checkbox' name="compare" id="compare" value="<?php echo $id;?>">add to compare
</div>
</div>
<?php
}
?>
page3 compare.php
<?php
session_start();
include 'includes/dbconfig.php';
$check = $_POST['value'];
$sql = "SELECT * from course_info_table where course_id = '$check' " or die(mysqli_error($conn));
$result = mysqli_query($conn,$sql);
$index = 0;
while($row = mysqli_fetch_array($result))
{
$title = $row['course_title'];
?>
<?php
}
echo json_encode($title);
?>
You can change
<input type ='checkbox' name="compare" id="compare" value="<?php echo $id;?>">
to
<input type ='checkbox' name="compare" class="compare" value="<?php echo $id;?>">
^you can only have one unique 'id' value in your html doc, which means your first id="compare" will work fine and others with id="compare" will be ignored by the DOM tree
Reference:
http://www.w3schools.com/tags/att_global_id.asp

how to check checkbox in javascript loop

I already get the id from a php loop for my checkboxes, and pass them as a string(maybe not because I could not split them with comma) in parameter, then I need to check if the checkbox is checked in javascript using the ids I passed through.
It doesnt seem like I can split it in javascript as well, and after I ran the for loop, the data is undefined in the new string.
Do you have any ideas? Please help
here is my php
echo "<div id='addstock'>";
$ids = '';
while($row_add = mysqli_fetch_array($result_add)){
$id=$row_add['id'];
$company = $row_add['companyname'];
//create checkbox for company
echo "<p class='checkbox'><input type='checkbox' name='stocks' id='".$id."' value='".$id."'>".$company."</p><br>";
$ids .= $id;
}
echo "</div>";
echo "<p class='input'><input type='submit' class='submitbutton' value='Submit' onclick='updatetable(".$ids.",".$user.")'></p>";
here is my javascript
//update table after add to stock
function updatetable(ids,user){
var url = "update.php";
//var res= ids.split(" ");
alert(ids);
var stocks = "";
//check if the checkbox is checked
for(var id in ids){
if(document.getElementById(ids[id]).checked)
{
stocks += ids[id];
alert(ids[id]);
}
}
//alert(stocks);
var data = "ids="+stocks+"&user="+user;
alert(data);
ajaxRequest(url, "POST", data, true, proceedUpdate);
}
function proceedUpdate(response){
target_div = document.getElementById("tablediv");
target_div.innerHTML = response;
}
Try this:
<div id="addstock">
<?php
$ids = array();
while($row = mysqli_fetch_array($result_add)) {
$ids[] = $row_add['id'];
echo '<p class="checkbox"><input type="checkbox" name="stocks" id="' . htmlspecialchars($id) . '" value="' . htmlspecialchars($id) . '">' . htmlspecialchars($company). '</p><br>' . "\n";
}
?>
</div>
<p class="input">
<input type="submit" class="submitbutton" value="Submit" onclick="updatetable('<?php echo htmlspecialchars(implode(',', $ids)); ?>', '<?php echo htmlspecialchars($user); ?>')">
</p>

Give Default Checked Value To The Checkbox Using Jquery

I tried to add checked property to a specific checkbox using jquery, but it seems doesn't work properly.
Checkbox Function Display
function product_category_loop_array ($product_category_array = array (), $parent_id = 0, $margin = -20) {
if (!empty ($product_category_array[$parent_id])) {
$margin = $margin + 20;
foreach ($product_category_array[$parent_id] as $items) {
echo "<input style='margin: 0 0 0 ".$margin."px; overflow: hidden;' id='".$items['id']."' class='category_checkbox left' name='product_category[]' type='checkbox' value='".$items['id']."'><label class='category_checkbox_label left'>".$items['name']."</label>
<div class='clear'></div>";
product_category_loop_array ($product_category_array, $items["id"], $margin);
}
}
}
function product_category () {
$db_connect = mysqli_connect (db_host, db_username, db_password, db_name);
$product_category_query = $db_connect->query ("SELECT id, name, parent_id FROM `product_category` ORDER BY name ASC");
$product_category_array = array ();
if (mysqli_num_rows ($product_category_query)) {
while ($row = mysqli_fetch_array ($product_category_query, MYSQLI_ASSOC)) {
$product_category_array[$row['parent_id']][] = $row;
}
product_category_loop_array ($product_category_array);
}
}
HTML
<div id="tabs-2" class="product_detail hide">
<div class="left">
<form class="product_detail_form" method="post" action="">
<?php product_category () ?>
<p class="detail_submit"><input name="save_product_category" type="submit" value="Save"></p>
</form>
</div>
</div>
Jquery
<script>
$ (document) .ready (function () {
<?php echo $hide_div ?>;
var selected_array = <?php echo json_encode ($product_category_selected) ?>;
$.each (selected_array (key, value) {
$ ("#"+value).prop("checked", true);
});
});
</script>
Any help will be appreciated.
Use
$ ("#"+value).attr("checked", "checked");
<script>
$(document).ready(function() {
<?php echo $hide_div ?>;
// DECODE JSON IN JS
var selected_array = $.parseJSON(<?php echo json_encode ($product_category_selected) ?>);
$.each(selected_array(key, value) {
$("#" + value).prop("checked", true);
});
});
</script>

Categories

Resources