javascript call inside php where loop not working and breaks query - javascript

I am attempting to call a javascript function inside a php where loop. I've succeeded in calling the variable, however the function only works on the first line, and then breaks a subsequent query.
The javascript is a simple show/hide of a div or span tag with a specific id. I'm trying to have this appear for every instance of a variable, but only open the span associated with that entry, so I used a php variable from the query.
The javascript code is contained in the header; it works fine without the php, and the php works fine without the javascript but I can't seem to make them work together.
Here's the code:
while($row = mysqli_fetch_array($qir)) {
$ingredient_id = $row['ingredient_id'];
echo '<input type="checkbox" value="' . $ingredient_id . '" name="markdelete[]">';
echo $row['amt'] . ' ' .$row['ingredient_name']; ?> <button onclick="showHide('<?php echo $row['ingredient_id']; ?>'); return false">Edit amount</button> <br />
<span id="<?php echo $row['ingredient_id']; ?>" class="hide">
<?php include_once('amt.php');
echo '</span> ';
// }
echo '<br />';
}
echo '<input type ="submit" name="remove" value="Remove">';
First of all, the showHide is only working on the first record
It is also making this query not respond at all.
if (isset($_POST['remove'])) {
iF (!empty($_POST['markdelete'])) {
foreach ($_POST['markdelete'] as $delete_id) {
// remove specific source from source_subject
$rem_ing = "DELETE from dish_ingredient
where ingredient_id = $delete_id
and dish_id = $dish_id ";
mysqli_query($dbc, $rem_ing)
or die ('Error removing ingredient: '.mysqli_error($dbc));
}
}
}
I tried removing the return false;, to no avail. Please let me know if I need to show more of the code (e.g. the javascript itself)
Edit:
I've tried working within the php string (this is actually what I had tried first) but it seems to break everything (no javascript, no php)
echo $row['amt'] . ' ' .$row['ingredient_name'] . '<button onclick="showHide(\''. $row['ingredient_id'] .'\') return false">Edit amount</button> <br />';
echo '<span id=" '. $row['ingredient_id'] .' " class="hide">';
include_once('amt.php');
echo '</span> ';
Edit: I am open to other solutions if this is not something that is possible. I'm feeling a bit stumped. Realistically I just want to have a list of items called from a mysql database, and have a field appear onclick to edit an associated variable if desired without having to send it to another page or reload the script for usability (hence the javascript piece).
Thanks again, anyone who can assist.
Note: this is the script that I am calling:
<script language="JavaScript" type="text/JavaScript">
menu_status = new Array();
function showHide(theid){
if (document.getElementById) {
var switch_id = document.getElementById(theid);
if(menu_status[theid] != 'show') {
switch_id.className = 'show';
menu_status[theid] = 'show';
}else{
switch_id.className = 'hide';
menu_status[theid] = 'hide';
}
}
}
</script>

You don't need tag there as you are already in php block.Try it without and use
showHide(\''.$row['ingredient_id'].'\')
and change
<?php include_once(....);
to
include_once(........);
Hopefully that would work

===========
try this for you javascript
<script language="JavaScript" type="text/JavaScript">
function showHide(theid){
if (document.getElementById) {
var switch_id = document.getElementById(theid);
if(!switch_id) {
switch_id.className = (switch_id.className.indexOf("show") > -1) ? "hide" : "show"
}
}
}

Okay after a long time on this, I finally figured out what was going on. Part of the issue was that I was trying to call a form inside a form, which I had forgotten is not permitted in HTML, so this required some redesign.
Other issues involved calling loops within inside loops, which caused problems where the first record would work, but not for the remaining records.
The javascript above did not need to be modified, only the way that it was called.
Here is what worked. The main key was using include() instead of include_once().
while($r = $qir->fetch_assoc()) {
$ingredient_id = $r['ingredient_id'];
$amt = $r['amt'];
$ingredient_name = $r['ingredient_name'];
echo $r['amt'] . ' ' .$r['ingredient_name'];
if ($row['user_id'] == $user_id) {
echo ' <span class="openlink"><button onclick="showHide(\''.$ingredient_id. '\')">edit amount</button></span><br/>';
echo '<div id="'.$ingredient_id.'" class="hide">';
include('amt1.php');
echo '</div>';
}
}

Related

Incorrect argument being passed to javascript

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 {
}
}

Javascript not printing within php loop

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.

placing php inside javascript

<script>
var strWidth = document.getElementById("mydiv").style.width;
var strHeight = document.getElementById("mydiv").style.height;
var link = "<?php if(isset($_GET["ggg"])) {
echo $_GET["ggg"].".php?width=800&height=460";
} else {
echo "page1.php?width=800&height=460";
}
?>";
</script>
this is my script, php inside javascript. how do i place this variable strWidth inside
php?width=800&height=460
so becomes some how like this
php?width=strWidth&height=460
EDIT 2
well, the only thing i am trying to do here to show variable value between those line is it a big deal ?
it might be done by separating like using concatenation or something ?
Add an input-field in PHP, hide it (if necessary) and read the value of this field with JS.
First of all if you want to use php values in javascript you need the script to be written in a php file. Suppose you do this then you can do this in this way:
<script>
var strWidth = document.getElementById("mydiv").style.width;
var strHeight = document.getElementById("mydiv").style.height;
var link='<?php echo (isset($_GET["ggg"]))?isset($_GET["ggg"]):''; ?>'; // this assigns the valueto link variable
if(link==''){
// your logic starts here
}else{
// your logic starts here
}
</script>
Add an input-field and assign a value to the hidden element and then get value through javascript.
It is not a good idea to combine PHP and Javascript.
Refer this about explanation on client-side vs server-side coding.
you can't really do that. but this works
<?php
echo "<script>\n";
echo "var strWidth = document.getElementById(\"mydiv\").style.width;\n";
echo "var strHeight = document.getElementById(\"mydiv\").style.height;\n";
if(isset($_GET["ggg"])) {
echo "var link =" . $_GET["ggg"] . ".php?width=800&height=460';\n";
}
else {
echo "var link ='page1.php?width=' + strWidth + '&height=' + strHeight + '';\n";
}
echo "</script>\n";
?>
the reference to ggg completely confuses the understanding of this process so really it should be taken out:
__ page1.php
<?php
if (!isset($_GET['foundWidth'])){
//stops double hit
echo "<script>\n";
echo "var strWidth = document.getElementById(\"mydiv\").style.width;\n";
echo "var strHeight = document.getElementById(\"mydiv\").style.height;\n";
echo "var link ='/page1.php?foundWidth=true&width=' + strWidth + '&height=' + strHeight + '';\n";
echo "window.location = link;"
echo "</script>\n";
}
elseif (isset($_GET['foundWidth']) && ($_GET['foundWidth']=='true')) {
if (isset($_GET['width']) && is_numeric($_GET['width'])){
//use your width here SERVER SIDE
// or
echo "<script> alert('Width is: '+ " . $_GET['width']) . "); </script>\n";
}
if (isset($_GET['height']) && is_numeric($_GET['height'])){
//use your height here SERVER SIDE
// or
echo "<script> alert('Height is: '+ " . $_GET['height']) . "); </script>\n";
}
}
?>
using this "trick" you can then write the PHP params into the javascript url with whatever get string you like, including triggering a reload of the page with the width as a param, so if you want to test if $_GET['width'] is set to a number you can insert it etc

Pass a variable from JavaScript to PHP

I'm trying to pass the variable from a JavaScript function - selected text - to the same page using php post method:
if (isset($_POST['u_name']))
{
echo $_POST['u_name'] . '</p>';
}
echo "<script type='text/javascript'>";
echo "var var1 = 0; var range = window.getSelection ();";
echo "function gst () { var range = window.getSelection (); alert (range.toString ()); var1 = range.toString ();}";
echo "document.write('<form method=\'post\'>');";
echo "document.write('<p>selected area:<br />');";
echo "document.write('<button onclick=\'gst ()\' type=\'submit\' name=\'u_name\' value = \'' + var1 + ' \' />Button</button>');";
echo "document.write('</form>');";
echo "alert (interesting);";
echo "</script>";
after pressing the button the selected page text is correct: it is checked with alert (range.toString ()) , however, the initial value of var1 variable - 0 is posted.
What could cause it and how one can pass the value, obtained from the javascript function through post method ?
Anton
That's because you set value attribute on the page load.
You can change it dynamically on button click. Replace one of your rows to:
echo "document.write('<button onclick=\"this.setAttribute(\'value\', var1); gst()\" type=\'submit\' name=\'u_name\' value = \'' + var1 + ' \' />Button</button>');";
Note this.setAttribute.
If you want to pass JavaScript variables to PHP, you'll have to use an Ajax request.
PHP is server sided, whereas JavaScript is client sided. This means that all PHP code is done before any JavaScript is even triggered. You can manipulate JavaScript with PHP, but if you want to manipulate PHP with JavaScript, use an Ajax call.

Rendered first Javascript before PHP

Assuming in PHP file there're :
function printAllRows(){
for( everyrows in db){
echo "<tr>";
echo "<td> $_POST['..'] <td>";
echo "<td> $_POST['..'] <td>";
echo "<tr>";
}
}
function printSpecifRows($keyword){
.....
}
// When the page loads for the first time
if ($db->preRow() >0){ // count rows in DB , if there already show them as table
printAllRows();
}
At the same time , there is
<input type="text" name="keywoard" />
<input type="submit" name="find" value="search" />
If the user enter the keyword press the button , then just show the rows match the keyword!
so :
if( $_POST["find"]){
?>
<script>
// first clear the current DOM table
document.getElementById("myTable").innerHTML="";
</script>
<?php
// then print again! according to printSpecifRows($keyword)
function printSpecifRows($keyword){
.....
}}
But the problem here is that JS is rendered first before PHP , so printSpecifRows($keyword) won't never be reached , any idea. I really appreciate your help. Thanks.
You are massively over-complicating things. Get rid of the <script> entirely. There is no need or point in involving JS here.
Just change the PHP so it doesn't output all the data in the first place if you don't want it on the page.
if ($_POST["find"]){
printSpecifRows($_POST["find"]);
} else {
printAllRows();
}

Categories