I'm displaying as many buttons as the number of rows in query. Every row has it's own names & properties. When i click on any of the buttons, it should pass that particular value to the function. But, when i tried with the following code, it only passes very first value if i click on any buttons.
<?php
while ($rec = mysql_fetch_array($query)) {
echo "<figure>";
echo "<button onclick='change()' title='".$rec["UserName"]."' class='fa fa-user' id='myButton1' value='".$rec["UserName"]."' style='font-size:100px;color:red'></button>";
echo "<figcaption>".$rec["UserName"]."</figcaption>";
echo "</figure>";
//echo "</a>";
}
?>
<script type="text/javascript">
function change()
{
var elem = document.getElementById("myButton1");
alert(elem.value);
// SQL Query and display the results in a proper table <?php echo "<table><tr><td>".elem.value."</td></tr></table>"; ?>
}
</script>
How do make it passing dynamic values (clicking upon any buttons, it should pass it's corresponding value) ?
id values must be unique in HTML. Having multiple elements with the same id is invalid and will not work as desired.
You don't need ids at all. Instead, the minimal change is to pass this into your function:
<button onclick='change(this)' ... >
and in your function
function change(btn) {
alert(btn.value);
}
But the real answer is don't use onclick attribute event handlers. They're a mid-1990's technology. Things have moved on in 20 years.
In this case, I'd use a delegated handler on the container all these figures are in. There's probably a container nearer to them that you can use, but in the worst case, you can use document.body:
Put a common identifying feature on the buttons (say, a class), then:
$(document.body).on("click", ".the-class", function() {
alert(this.value);
});
One handler handles all the buttons, since click bubbles.
Again you probably want a container closer to the list of figures, rather than document.body.
<?php
while ($rec = mysql_fetch_array($query)) {
echo "<figure>";
echo "<button onclick='change(this.value)' title='".$rec["UserName"]."' class='fa fa-user' id='myButton1' value='".$rec["UserName"]."' style='font-size:100px;color:red'></button>";
echo "<figcaption>".$rec["UserName"]."</figcaption>";
echo "</figure>";
//echo "</a>";
}
?>
<script type="text/javascript">
function change(button_val)
{
alert(button_val);
// SQL Query and display the results in a proper table <?php echo "<table><tr><td>".button_val."</td></tr></table>"; ?>
}
</script>
Related
I am building a simple website for my family to track the jigsaw puzzles they own. One feature is the ability to delete a puzzle they no longer own. I intend to pass the row ID to a separate file as an argument, but thought I should put a javascript confirmation popup in the middle. I seem to have everything running almost correctly, but the argument being passed is incorrect and I don't know why. It is passing the ID of the last row in the table, rather than the current row ID. Hoping someone can point me in the right direction.
PHP Code
while ($row = $result->fetch_assoc()) {
echo "<script>var puzzleID = " . $row['id'] . "</script>";
echo "<td><a href='puzzleedit.php?=" . $row['id'] . "'>Edit</a> | <button onclick='confirmationBox()'>Delete</button></td>";
}
JS Code in a separate file
function confirmationBox() {
if (confirm("Are you sure you want to delete this puzzle?")) {
window.location = './puzzledelete.php?=' + puzzleID
} else {
}
}
The interesting thing is that using $row['id'] in the edit link works as expected, it is grabbing the correct row ID from the database. The $row['id'] in the script is grabbing the table's last row ID.
Your loop keeps reassigning puzzleId. When you call confirmationBox(), it will have the last value that was assigned, not the one that was assigned before each <td>.
Instead of using a global variable, use a function parameter.
while ($row = $result->fetch_assoc()) {
echo "<td><a href='puzzleedit.php?=" . $row['id'] . "'>Edit</a> | <button onclick='confirmationBox(" . $row['id'] . ")'>Delete</button></td>";
}
function confirmationBox(puzzleID) {
if (confirm("Are you sure you want to delete this puzzle?")) {
window.location = './puzzledelete.php?=' + puzzleID
} else {
}
}
new to php and javascript. I am trying to print an id using javascript within a php loop and nothing is turning up. Here is the code:
$sql = "SELECT dueDate, assignmentName, className FROM assignments INNER JOIN classes ON assignments.class = classes.id ORDER BY DATE(dueDate)";
if ($result = mysqli_query($link, $sql)) {
if (mysqli_num_rows($result) > 0) {
echo "Assignments";
while ($row = mysqli_fetch_array($result)) {
echo '<div class="popup" id="popup">';
echo '<div class="overlay"></div>';
echo '<div class = "content">' . $row['dueDate'] . $row['className'] . '</div>';
echo '<div class="close-btn content" onclick="togglePopup()">×</div>';
echo '<div class = "btn-group">' . '<button onclick="togglePopup()">' . $row['assignmentName'] . '</button>' . '</div>';
echo '</div>';
echo '<script type=\"text/javascript\"> document.write(printID()); </script>';
}
}
The problem is, that you want PHP to know, what printID() is and what it should do. PHP knows nothing about JavaScript functions, because JavaScript and PHP are executed on totally different places. PHP renders your HTML and sends a response to your browser, which executes JavaScript. JavaScript will not be executed, when PHP is processing data.
There 's one thing you could do. Wait until everything is rendered and execute your JavaScript functions at the end of your HTML before the </body> tag.
document.addEventListener('DOMContentLoaded', (event) => {
const elements = document.querySelectorAll('.popup');
Array.prototype.forEach.call(elements, (element) => {
let id = printID();
element.appendChild(document.createTextNode(id));
});
});
What does the above code snippet? It waits and will be executed, until all DOM is loaded. Then it searches for all elements with the css class named "popup". By the way there is another issue in your code. You 're processing your database query result with a loop and you 're using an id attribute. Id attributes should only be used once in your markup. So please use a css class instead of an id attribute. When using a class names "popup" you can read out all elements and execute your javascript function printID() and append a new element. That 's it.
Your failure is, that you didn 't recognize, that JavaScript is a client side language and is not executed by php. Even when it 's written in an html template.
A possible better approach
As you said you want to change a parameter in your togglePopup JavaScript function. The following code shows up a possible solition.
<?php
...
$i = 0;
while ($row = mysqli_fetch_array($result)) {
echo '<div class="popup">';
echo '<div class="overlay"></div>';
echo '<div class = "content">' . $row['dueDate'] . $row['className'] . '</div>';
echo '<div class="close-btn content">×</div>';
echo '<div class = "btn-group">' . '<button id="popup-' . $i . '">' . $row['assignmentName'] . '</button>' . '</div>';
echo '</div>';
$i++;
}
Instead of placing onclick attributes just leave this out. Instead place an id parameter on the button element. Keep in mind, that tha value of a id parameter has to be unique. Instead of using an id attribute, you can use a data attribute like data-id="my-value". Data attributes ensure, that the value of this attribute has not to be unique. Just to show you to possible ways ...
At the end of your HTML before the </body> tag place the following.
<script>
const togglePopup = (event) => {
let target = event.target;
let id = target.getAttribute('id');
// do something with the id attribute
}
document.addEventListener('DOMContentLoaded', (event) => {
const elements = document.querySelectorAll('.popup button[id^="popup-"]');
Array.prototype.forEach.call(elements, (element) => {
element.addEventListener('click', togglePopup);
});
});
</script>
This small snippet adds a click event handler to every button inside an element with the class .popup which has an id attribute which begins with popup-. When this button will be clicked the togglePopup function will be called. Inside this function the id attribute comes from the target element.
With this solution you keep your html markup clean and all javascript stuff is separated from the php code.
In one of my pages, I have an <a> tag. When I click it, I am passing the variable as a GET parameter and retrieving it in the same page and displaying the details.
The code to get the parameters:
if(isset($_GET['CatId']))
{
$CatId= $_GET['CatId'];
}
else $CatId=0;
if(isset($_GET['MainProductId']))
{
$MainProductId= $_GET['MainProductId'];
$FilterAllProductQuery ="WHERE Product.MainProductId = '$MainProductId'";
$FilterProductQuery = "AND Product.MainProductId = '$MainProductId'";
}
else
{
$MainProductId=0;
$FilterAllProductQuery="";
$FilterProductQuery="";
}
The <a> tag:
<a href='Products.php?CatId=<?php echo $CatId;?>&MainProductId=<?php echo $id;?>' ><?php echo $row["MainProdName"] ?></a>
The details to be displayed:
if($CatId == 0)
{$sql = "SELECT *,Product.Id AS ProdId, Product.Name as ProdName FROM Product $FilterAllProductQuery ";}
else
{$sql = "SELECT * ,Product.Id AS ProdId, Product.Name as ProdName FROM Product INNER JOIN MainProduct ON MainProduct.Id = Product.MainProductId
INNER JOIN Category ON Category.Id = MainProduct.CategoryId WHERE Category.Id = '$CatId' $FilterProductQuery ";}
$result1 = $dbcon->query($sql);
if ($result1->num_rows > 0) {
while ($row = $result1->fetch_assoc()) {
$id = $row["ProdId"];
// $image=$row["ImagePath1"];
$qty = $row["Quantity"];
?>
<li class="col-lg-4">
<div class="product-box">
<span class="sale_tag"></span>
<div class="row">
<img src='themes/images/<?php echo $row["ImagePath1"]; ?>' height='200' width='250'> </a></div></div></li>
Now the code is working fine, but what's happening is that when I click the <a> tag, as I am passing the get parameters, the page is refreshing. As all the code are on the same page, I don't want the page to be refreshed. For that, I need to use Ajax request. How can I do that?
I would make an onclick() event on the a tag like so:
<?php echo '<a c_id="'.$CatId.'" MainProductId="'.$id.'" onclick="sendProduct()">'.$row["MainProdName"].'</a>';
Afterwards i would in a .js file write a simple function called sendProduct() and inside i would do an ajax request to a page named ex: insertproduct.php, get the information back and Insertproduct.php would process the data and you could use .html() or .append() to assign the data to the div showing the data with a normal id.
The c_id, MainProductId are custom attributes you could recieve in the .js file as $("#youraTag").attr("c_id");
There's a really good guide here on basic ajax: https://www.youtube.com/watch?v=_XBeGcczFJo&list=PLQj6bHfDUS-b5EXUbHVQ21N_2Vli39w0k&index=3&t=1023s
First you have to remove the href of the link and give it an id.
<a id='link'>
<?php echo $row["MainProdName"] ?>
</a>
Then you put this jQuery into your page. Note, you need to have a div in which you are going to put in all your obtained results. I reffered to this div in the code as #mydiv.
$("#link").click(function(){
$("#mydiv").load("Products.php?CatId=<?php echo $CatId;?>&MainProductId=<?php echo $id;?>");
});
So I have this serie of radio buttons generated by a php script that call a javascript function when they get clicked on:
<?php
$databases = mysqli_query($link, "SHOW DATABASES");
while($row = mysqli_fetch_row($databases)) {
$db = $row[0];
echo "<input type='radio' name='database' id='".$db."' onclick='displaydbcontent(".$db.")'>";
}
?>
The javascript function then has to alert the content of the string:
function displaydbcontent(dbid) {
alert("This is a test");
alert(dbid);
}
Now, no matter what the content of the variable $db is, after displaying the first alert printing "This is a test", the second one always prints "[object HTMLInputElement]".
I am pretty sure that it's all a matter of quotation marks, but I don't see any way to work around it.
And for those who are wondering about it even thought it hasn't to do much with my issue, the $link variable has been initializated and works correctly.
Pass this.id as argument which will return id property of the clicked-element
onclick='displaydbcontent(this.id)'>";
As you are passing $db as argument, it represents the element. Element with id becomes the global variables.
function callMe(elem) {
console.log(elem);
}
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<div id='elem' onclick='callMe(elem)'>Hello!!!!!</div>
Edit: Or echo '<input type="radio" name="database" id="'.$db.'" onclick="displaydbcontent(\'$db\')">';
I am working on a project where I have divisions stored in mysql database with the "division id" and the "division name";
what I want to have is so that i use php to do a "while" loop and go through all the divisions;
then for each division it creates a button which will trigger a javascript function…
I have done a lot of testing on this so I know certain parts are working…; here is my code:
<p id="id57512">How are you?</p>
<script>
var g_myobj = {};
</script>
<?php
$result_g1 = mysql_query("SELECT * FROM divisions");
while($row = mysql_fetch_array($result_g1, MYSQL_BOTH))
{
$div_id=$row[div_id];
$div_name=$row[div_name];
$button_id="b";
$button_id.=$div_id;
$function_id="f";
$function_id.=$div_id;
?>
<button id=<?php echo $button_id; ?>><?php echo $div_name; ?></button>
<script>
var f_id='<?php echo $function_id; ?>';
var b_id='<?php echo $button_id; ?>';
var div_id='<?php echo $div_id; ?>';
var newFieldName = f_id;
var newFieldValue = function() {document.getElementById("id57512").firstChild.nodeValue=gman_code1(div_id);};
g_myobj[newFieldName] = newFieldValue;
var gman_code1 = function(number) {
var result1 = number*2;
console.log(result1);
return result1;//add return statement
}
//define the behavior
document.getElementById(b_id).addEventListener("click", g_myobj[f_id] , false);
</script>
<?php
}
the function names need to be a variable; but I figured out how to do that by making it an object; and so can access the different functions that way…
I basically tested this all when it was not in a loop; where I manually had it do everything twice (even creating the functions in the object) and it all worked fine…
basically when you click on a button it is supposed to send a number to that "p" container and multiply it by 2
when I did it manually and not in loop i just had it create the object g_myobj first and then just started adding items to the object…
but now that i am doing this in a loop - I felt I could not have the statement that creates the empty object in the loop or it would just keep recreating it; so I went above the loop and had the object created there in its own "script" tags all by itself…
that part may be a problem with this, not sure at all…
another potential problem is that I am not sure if I can do all this in a loop like this
it is a "php loop" and so maybe this just all cannot be done in a loop like that…
What is going on is the first button works but none of the others do…
So, I am hoping someone can advise me on what I am doing wrong on this…
Thanks so much...
If all you are trying to do is send a number to <p> and multiply it by 2, see this one liner function. I assume you are trying to accomplish more than just the multiplying thing otherwise you probably would have just done a simple function like below...
Also, I'm sure you will get lots of comments on it, but you should not be using the mysql_ functions anymore. They are both deprecated and potentially unsafe. You should use mysqli or PDO prepared statements.
On your button, you should probably put quotes around the id="yadayada" instead of id=yadayada. jQuery may be a good option for your js to handle functions or what-have-you.
<p id="id57512">How are you?</p>
<?php
$result_g1 = mysql_query("SELECT * FROM divisions");
while($row = mysql_fetch_array($result_g1, MYSQL_BOTH)) {
$div_id = $row[div_id];
$div_name = $row[div_name];
$button_id = "b$div_id";
$function_id = "f$div_id"; ?>
<button id="<?php echo $button_id; ?>" onClick="MyRadFunction('<?php echo $div_id; ?>')">
<?php echo $div_name; ?></button>
<?php } ?>
<script>
function MyRadFunction(DivId) {
$("#id57512").html(DivId*2);
// var NewNum = $("#id57512").text();
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
When rendering your button, you should wrap the id in quotes, e.g.
<button id='<?php echo $button_id; ?>'><?php echo $div_name; ?></button>