Buttons having different id to call the same js function - javascript

foreach ($_SESSION['songlist']['items'] as $key => $value1) {
$id = $value1['id']['videoId'];
session_start();
$_SESSION['id'] = $id;
echo "<br>";
echo "<iframe src='//www.youtube.com/embed/$id?enablejsapi=1' frameborder='0' allowfullscreen id='video'></iframe>";echo "<br>";
echo '<div id="Added" style="display:none;">ADDED!</div>';
echo "<form id='demo' method='POST' action=''><button type='button' name='button' id='$id' method='POST' onclick='Count($id)'>Add to playlist</button></form>";
}
This is my button
I want to have a separate counter for different buttons using js onclick function.

Related

PHP Looped Array, jquery to print each id value

So far I have managed that when a button is clicked it will print all values within the array. I need it to be smarter and only print the value of the element clicked.
<?php
$Arr_shoppingList = array(
array("Volvo",22,18,0),
array("BMW",15,13,1),
array("Saab",5,2,2),
array("Land Rover",17,15,3)
);
//Looped through array and printed values
foreach ($Arr_shoppingList as $value) {
echo "<div class='ColumnRow Spacing Color2 Border'>";
echo "<h1> $value[0] </h1> <br>";
echo "<p>'MPG'. $value[1]</p> <br>";
echo "<p>'Stock' . $value[2]</p> <br>";
echo "<form method='GET'>";
echo "<button class='Border' type='submit' id='$value[0]' class='Button'> $value[0]
</button>";
echo "</form>";
echo "</div>";
}
?>
<script>
$('button').on('click', function (event) {
event.preventDefault()
$('button').each(function(index, value){
console.log(value.id)
})
});
</script>
EDIT: The first section has been completed many thanks, but similarly, but I also need the stock and MPG values to also be targeted, how would I go about incorporating that into this code? this is part of a checkout basket I'm attempting to create.
You can use event.target.id to get the id of the clicked element
<?php
$Arr_shoppingList = array(
array("Volvo",22,18,0),
array("BMW",15,13,1),
array("Saab",5,2,2),
array("Land Rover",17,15,3)
);
//Looped through array and printed values
foreach ($Arr_shoppingList as $value) {
echo "<div class='ColumnRow Spacing Color2 Border'>";
echo "<h1> $value[0] </h1> <br>";
echo "<p>'MPG'. $value[1]</p> <br>";
echo "<p>'Stock' . $value[2]</p> <br>";
echo "<form method='GET'>";
echo "<button class='Border' type='submit' id='$value[0]' class='Button'> $value[0]
</button>";
echo "</form>";
echo "</div>";
}
?>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$('button').on('click', function (event) {
event.preventDefault()
console.log(event.target.id);
});
</script>

Clicking specific class to trigger drop down event

How can I fix this? I have used php to display data from my database but I didn't foresee this bug.
When I click the gear icon both dropdown menu will appear. How can I fix this? What I want is when I click the gear of a specific project only one dropdown will appear. I hope you can help me its been bugging me for days. Thank you!!
Here is my code:
PHP CODE:
if ($level == "Level 1"){
$sql = "SELECT * FROM project";
$result = mysqli_query($conn,$sql);
$count = mysqli_num_rows($result);
if ($count > 0) {
while ($row = mysqli_fetch_array($result)) {
echo "<input type='hidden' id='".$row['project_id']."'>";
echo "<div class='col-3'>";
echo "<div class='card'>";
echo "<div class='row'>";
echo "<div class='col-2'>";
echo "<h6 class='card-title'>".$row['project_name']."</h6>";
echo "</div>";
echo "<div class='col-2'>";
echo "<div class='card-setting'><i class='fa fa-gear'></i></div>";
echo "<div id='card-setting-dropdown' class='card-dropdown-content'>";
echo "<button class='card-dropdown-menu' id='delete_project'>Delete Project</button>";
echo "<button class='card-dropdown-menu' id='add_task'>Add Task</button>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "<div class='row'>";
echo "<div class='col-2'>";
echo "<label class='project-details'>".$row['department']."</label>";
echo "</div>";
echo "<div class='col-2'>";
echo "<label class='project-details' style='float:right;'>Priority: ".$row['priority']."</label>";
echo "</div>";
echo "</div>";
echo "<div class='pr-task-data'>";
echo "<div class='pr-task-summary-l'>";
echo "<label class='pr-task-title'>Tasks</label>";
echo "<p class='pr-task-details'>12</p>";
echo "</div>";
echo "<div class='pr-task-summary-l'>";
echo "<label class='pr-task-title'>Completed</label>";
echo "<p class='pr-task-details'>5</p>";
echo "</div>";
echo "<div class='pr-task-summary-l'>";
echo "<label class='pr-task-title'>In-Progress</label>";
echo "<p class='pr-task-details'>2</p>";
echo "</div>";
echo "<div class='pr-task-summary-r'>";
echo "<label class='pr-task-title'>Not Completed</label>";
echo "<p class='pr-task-details'>5</p>";
echo "</div>";
echo "</div>";
echo "<div class='progress'>";
echo "<div class='progress-bar'>";
echo "<label class='progress-bar-percent'>50%</label>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
}
}
}
Script:
//Card-Settings Dropdown
$(".card-setting").click(function() {
$(".card-dropdown-content").toggleClass("card-dropdown-content-show");
$(this).toggleClass("card-setting-active");
});
When the script activates you toggle the class car-dropdown-content-show for all cards. You should only focus on the one inside the card and find the one with the card-dropdown-content class:
$(".card-setting").click(function() {
var $this = $(this);
$this.parent().find(".card-dropdown-content").toggleClass("card-dropdown-content-show");
$this.toggleClass("card-setting-active");
});
We first need to go up to the parent because the find looks through all the descendants, the div with the card-dropdown-content class is a sibling.
You need to find related element to clicked gear.
Try this:
$('.card-setting').on('click', function () {
var $this = $(this) ;
$this.next().toggleClass("card-dropdown-content-show");
$this.toggleClass("card-setting-active");
});

How do I get button's ID from a list of buttons?

I haven't worked much with php and javascript and was hoping to get some help. I want to be able to detect which button was clicked exactly. I'm creating one button per row but I don't know how to figure out what row the click was made in. This is what I have so far...
# Get all the table data from the database
$getData = mysqli_query($conn, "SELECT * FROM `query_table`") or die ("Error occured while selecting!");
// echo '<form method="post" action="index.php">';
echo '<table border="1">';
echo '<tr>';
echo '<td>Questions</td>';
echo '<td>Likes</td>';
echo '<td></td>';
echo '</tr>';
# Loop through each row and print out the question
while ($row = mysqli_fetch_array($getData)) {
echo '<tr>';
echo '<td>';
echo $row['Question'];
echo '</td>';
echo '<td>';
echo $row['Likes'];
echo '</td>';
echo '<td>';
?>
<input type="button" id="myButton" value="Like" onclick="myFunc(<?=$row['ID']?>)" />
<?php
echo '</td>';
echo '</tr>';
}
echo '</table>';
// echo '</form>';
echo '<p id="text"></p>';
mysqli_close($conn);
?>
<script type="text/javascript">
function myFunc(id) {
document.getElementById("text").innerHTML = id;
}
</script>
So far this prints out the row id where the button was clicked, but I don't suppose I can assign that parameter value directly to a php variable that I can then use for mysql queries. How is stuff like this normally done, please help.
<input type="button" data-id="<?=$row['ID']?>" value="Like" onclick="myFunc(this)">
and
<script type="text/javascript">
function myFunc(button) {
document.getElementById("text").innerHTML = button.getAttribute('data-id');
}
</script>
In JavaScript the token "this" refers to the context in which the code is running which in this case is the button. Store custom data in attributes prefixed with data- to ensure they are not disturbed - standard practise.

Get input before submitting to insert into action url

Im trying to get a value of an input into my buttons action url before the button is pushed.
I need to get the value of:
id="qty<?php echo $i;?>"
Into where it says:
<?php echo VALUE OF $qtyforaction; ?>
My Code is:
<?php $i = $_product->getId();?>
<form action="<?php echo $this->helper('checkout/cart')->getAddUrl($_product); ?>" method="post" id="product_addtocart_form_<?php echo $_product->getId()?>"<?php if($_product->getOptions()): ?> enctype="multipart/form-data"<?php endif; ?>>
<input type="text" name="qty" id="qty<?php echo $i;?>" maxlength="12" value="1" title="Qty" class="cartnum" />
<?php $qtyforaction = 'qty'.$i; ?>
<?php echo $qtyforaction; ?>
<button type="button" class="addtocartbutton button btn-cart" onclick="setLocation('<?php echo $this->helper('checkout/cart')->getAddUrl($_product); ?>qty/<?php echo VALUE OF $qtyforaction; ?>')" ><span><span>Order Again</span></span></button>
</form>
Would I have to use javascript to get it into the url string? My javascript is a bit ropey, would something like this work?
<script type="text/javascript">
var something= document.getElementById('<?php echo $qtyforaction;?>');
</script>
UPDATE WITH FULL CODE:
<?php
if (Mage::getSingleton('customer/session')->isLoggedIn()) {
/* Get the customer data */
$customer = Mage::getSingleton('customer/session')->getCustomer();
/* Get the customer's email address */
$customer_email = $customer->getEmail();
}
$collection = Mage::getModel('sales/order')->getCollection()->addAttributeToFilter('customer_email', array(
'like' => $customer_email
));
$uniuqProductSkus = array();
foreach ($collection as $order) {
$order_id = $order->getId();
$order = Mage::getModel("sales/order")->load($order_id);
$ordered_items = $order->getAllItems();
foreach ($ordered_items as $item)
{
if (in_array($item->getProduct()->getSku(), $uniuqProductSkus)) {
continue;
} else {
array_push($uniuqProductSkus, $item->getProduct()->getSku());
$_product = Mage::getModel('catalog/product')->load($item->getProductId());
$product_small_image_path = Mage::helper('catalog/image')->init($_product, 'small_image')->resize(200);
$product_thumbnail_path = Mage::helper('catalog/image')->init($_product, 'small_image')->resize(150);
$summaryData = Mage::getModel('review/review_summary')->load($item->getProductId());
echo "<li>";
echo "<div class='previous-name'><p><a style='color:black; font-weight:bold; font-size:14px;' href='" . $_product->getProductUrl() . "'>";
echo $item->getName() . "</a></p></div>";
echo "<div class='previous-image'><a href='" . $_product->getProductUrl() . "'>";
echo "<img src='" . $product_small_image_path . "' />";
echo "</a></div>";
echo "<div class='previous-rating'>";
echo "<p><a style='color:black; font-weight:bold; font-size:14px;' href='" . $_product->getProductUrl() . "#product_tabs_review_tabbed'>Review this beer now</a></p>";
echo $summaryData->getRatingSummary() . '% Would buy again <br/>';
echo "<div class='rating-box' style='float:left;'>";
echo "<div class='rating' style='width:" . $summaryData->getRatingSummary() . "%'></div></div>";
echo "</div>";
/**echo "<div class='previous-button'>";
echo '<button type="button" title="Add to Cart" class="button btn-cart" onclick="setLocation(\'';
echo $this->helper('checkout/cart')->getAddUrl($_product);
echo '\')"><span><span>Order Again</span></span></button>';
echo "</div>";**/
?>
<?php $i = $_product->getId();?>
<div class='previous-button'>
<form action="<?php echo $this->helper('checkout/cart')->getAddUrl($_product); ?>" method="post" id="product_addtocart_form_<?php echo $_product->getId()?>"<?php if($_product->getOptions()): ?> enctype="multipart/form-data"<?php endif; ?>>
<input type="text" name="qty" id="qty<?php echo $i;?>" maxlength="12" value="1" title="Qty" class="cartnum" />
<?php $qtyforaction = 'qty'.$i; ?>
<script type="text/javascript">
var xy = document.getElementsByTagName("input")[0].getAttribute("qty");
var x = "<button type='button' class='addtocartbutton button btn-cart' onclick='setLocation()'><span><span>Order Again</span></span></button>";
document.getElementById("buttonaddcart").innerHTML = x;
</script>
<div id="buttonaddcart">
<button type="button" class="addtocartbutton button btn-cart" onclick="setLocation('<?php echo $this->helper('checkout/cart')->getAddUrl($_product); ?>qty/')" ><span><span>Order Again</span></span></button>
</div>
</form>
</div>
<?php
echo "<div class='previous-clear'></div>";
echo "</li>";
}
}
}
?>
You need to get the value of the id attribute:
var x = document.getElementsByTagName("input")[0].getAttribute("id");
But how do you plan on using PHP to echo out this variable if PHP is loaded and done with before Javascript even comes into play? You could use Javascript though to display this variable on the page if that's all you needed.
If you had something in your HTML to target, you could do it like this:
document.getElementById("result").innerHTML = x;
But anyways, get the action attribute value...
var y = document.getElementsByTagName("form")[0].getAttribute("action");
Then set the action attribute to this + the qty...
document.getElementsByTagName("form")[0].setAttribute("action", x + y);
That should work for you, if not, try wrapping x + y in additional parentheses...("action", (x + y));

Passing an id to a PHP script using jQuery/Ajax

This is the code that the user have a participation with.
<html>
<head>
<title></title>
<script src="jquery-1.9.1.js"></script>
<script src="jquery.form.js"></script>
</head>
<body>
<?php
include 'connection.php';
$sql="SELECT * FROM blog";
$result=mysqli_query($link, $sql);
if(!$result)
{
$output='Error fetching students:'.mysqli_error($link);
}
?>
<div id="table">
<table border='1' cellpadding='10' id="table">
<tr>
<td><b>Title<b></td>
<td><b>Edit<b></td>
<td><b>Delete<b></td>
</tr>
<?php
while($row=mysqli_fetch_array($result))
{
echo '<tr class="record">';
echo '<td>'.$row['articletitle'] .'';
echo '<td>Edit';
echo "<input type='hidden' name='id' value='".$row['articleid']."'></td>";
echo '<td><div align="center">Delete</div></td>';
echo "</tr>\n";
}
echo '<form method="post" id="myForm" action="postview.php">';
echo '<input type="hidden" name="myID">';
echo '</form>';
?>
</table>
<button id="addrecord">Add New Post</button>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#addrecord").click(function(){
$("#table").load("addpost.php");
$("#addrecord").hide();
});//add
$(".delbutton").click(function(){
//Save the link in a variable called element
var element = $(this);
//Find the id of the link that was clicked
var del_id = element.attr("id");
//Built a url to send
var info = 'id=' + del_id;
if(confirm("Are you sure you want to delete this Record?"))
{
$.ajax({
type: "GET",
url: "delete.php",
data: info,
success: function(){}
});//ajax
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
});//delete
$(".title").click(function(){
$('[name=myID]').val($(this).attr('id'));
$('#myForm').submit();
});//view
$(".edit").click(function(){
var data=$("#tryform").serialize();
$.ajax({
type: "POST",
url: "editpost.php",
data: data
}).done(function( msg ) {
$("#table").html(msg);
});//ajax
});//delete
});
</script>
</body>
</html>
and this the PHP script that the code above redirect to.
<?php
include 'connection.php';
$id=$_GET['id'];
echo $id;
$sql="SELECT * FROM blog WHERE articleid='$id'";
$result=mysqli_query($link, $sql);
echo "<table>";
$row=mysqli_fetch_array($result);
echo "<tr>";
echo "<td>".$row['articletitle'] . "</td>";
echo "<td><img src='image.php?id=$row[articleid]' width='200' height='200' /><br/></td>";
echo "<td>".$row['articlemore'] . "</td>";
echo "</tr>";
echo "</table>";
//echo "</div>";
?>
I'm having this kind of error:
Undefined index: id in C:\xampp\htdocs\ckeditor\samples\postview.php on line 4
You need to check if argument "id" is passed to the php script first
<?php
include 'connection.php';
if( (isset($_GET['id'])) && ($_GET['id'] != '') ){ //check if the argument "id" is passed to the script
$id=$_GET['id'];
echo $id;
$sql="SELECT * FROM blog WHERE articleid='$id'";
$result=mysqli_query($link, $sql);
echo "<table>";
$row=mysqli_fetch_array($result);
echo "<tr>";
echo "<td>".$row['articletitle'] . "</td>";
echo "<td><img src='image.php?id=$row[articleid]' width='200' height='200' /><br/></td>";
echo "<td>".$row['articlemore'] . "</td>";
echo "</tr>";
echo "</table>";
//echo "</div>";
}
?>
Not so much an answer to your question, but probably a good suggestion to make your code a lot cleaner- try using PHP Alternative Syntax and moving in and out of PHP to make your HTML clean.
<?php while($row=mysqli_fetch_array($result)):?>
<tr class="record">';
<td><?php echo $row['articletitle'];?>
<td>Edit
<input type='hidden' name='id' value='<?php echo $row['articleid'];?>'></td>
<td>
<div align="center">
Delete
</div>
</td>
</tr>
<?php endwhile;?>
<form method="post" id="myForm" action="postview.php">
<input type="hidden" name="myID">
</form>
$sql="SELECT * FROM blog WHERE articleid='".$id."'";
try this line
That isnt an error, but a notice, which is lowlevel It simple means $_GET['id'] doesnt hav a value
echo $example['something']; // will give undefined index notice
$example['something'] = 'abc';
echo $example['something']; // No notices
Your website should be domain.ext/?id=123, if not, this notice will show.

Categories

Resources