Multiple variables in PHP function - javascript

I looked around but couldnt find what i looked for so i thought i should try and ask.
Also i should mention i am quite new to most codes.
I am trying to get multiple variables from my database into my function.
From here i need the image link and the id. (As you can see i tried to link them in the onclick=)
<div id="HeadItems" >
<?php
$sqlhead = "SELECT * FROM items
WHERE part = 'head'";
$headquery = mysqli_query($con, $sqlhead) or die (mysqli_error($con));
while($headf = mysqli_fetch_assoc($headquery))
{
?>
<img class="headArmor" src="<?php echo $headf['image']; ?>" onclick="headHide('<?php echo $headf['image']; ?>", "<?php echo $headf['id']; ?>')"/>
<?php
}
?>
</div>
They go into my function:
function headHide(src, chosenid) {
var head = document.getElementById("head");
var HeadItems = document.getElementById('HeadItems');
HeadItems.style.display = 'none';
head.innerHTML = "<img src='" +src+ "' width=80; height=80;>";
var chosenhead = chosenid;
}
(when i click on the image the image is then inserted into the head.innerHTML)
Problem is that after i put in the second variable in the function (chosenid and the $headf['id'] in the while loop) it stopped working.
I probably made it hard to understand now (I'm dutch) so a small summary:
I want my onclick function to give me the $headf['head'] and $headf['id'].
so i can make the $headf['id'] into a var

You seem to have some single quotes missing here:
onclick="headHide('<?php echo $headf['image']; ?>', '<?php echo $headf['id']; ?>')"
^ ^

The problem is with the quotes in the definition of onclick.
This should work.
onclick="headHide(<?php echo '\''.$headf['image'].'\',\''.$headf['id'].'\''; ?>)"
//This will be onclick="headHide('image','id')"

Related

Make new variable in script calling from php

I'm using jquery-3.3.1.min to live update and calling it to my main.php
<script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#show').load('smoke.php')
$('#show2').load('pids.php')
$('#show3').load('flame.php')
$('#show4').load('panic.php')
}, 2000);
});
/////
I'm echo in php using
$smoke_status = $row['smoke_status'];
$pids_status = $row['pids_status'];
$flame_status = $row['flame_status'];
$panic_status = $row['panic_status'];
$startdate = $row['startdate'];
$stopdate = $row['stopdate'];
echo "<tr>";
echo "<td id='show'></td>";
echo "<td id='show2'></td>";
echo "<td id='show3'></td>";
echo "<td id='show4'></td>";
echo "<td>$startdate</td>";
echo "<td>$stopdate</td>";
echo "</tr>";
but now...i want to make my live update data into a variable in script
how can i declare it.
i'm success calling this
var i = <?php echo $panic_status ?>;
and how can i call
echo "<td id='show'></td>";
echo "<td id='show2'></td>";
echo "<td id='show3'></td>";
echo "<td id='show4'></td>";
into new variable??plsss help and srry for the long question
Hello I do not know what you are actually doing with the code. its so scattered that one cannot easily know where to start
1.) You are displaying a result and i did not see where you are trying to escape those database with htmlentities() or htmlspecialchars() functions against xss attack.
2.) I do not know whether you are still using mysql_connect deprecated functions in your database query. if so please better move it to mysqli or PDO.
3.) i can see you calling simultaneously four php files simultaneously with 2 seconds call. What is it you are trying to achieve. This will cause alot of issues to the server including latency, poor performance and over consumption
of data. If you need a real time update why don't you switch over to nodejs and socket.io.
To answer your question, I have created an ajax example to get you started
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
//$('#result').click(function(){
var post1 = 'data to post if any';
$('#loader').fadeIn(400).html('Please Wait. Data is being Loaded');
// assuming that you want query result by posting a variable
var datasend = "alert1="+ post1;
$.ajax({
type:'POST',
url:'smoke.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(msg){
$('#loader').hide();
$('#result').fadeIn('slow').prepend(msg);
}
});
//})
});
</script>
<div id="loader"></div>
<div id="result"></div>
The above script will make a call to smoke.php and display any result contained there in
<?php
$smoke_status = 'I am not smoking';
/* if data is to be displayed in html form, you have to escape it with either htmlspecialchars() or htmlentities() functions to ensure
that XXS attack is not possible. you can read further on how to escape both single, double quotes with it as case may be
*/
echo htmlspecialchars($smoke_status);
?>

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

javascript call inside php where loop not working and breaks query

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>';
}
}

Assist with javascript functions being contained within a loop (PHP)

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>

Headlines links wont be created

I'm currently busy with a ticketsystem. A headline will be displayed. When the headline has over 40 characters, the headline will be cut and the '...' will be added. Now, when I try to link the headlines to its messages, it won't create a link. I'm using Ajax to do this without a page refresh, but no links are being created, which means that the full ticket wont be openend. I've tried several things but I cant get it to work. I'm also not that familiar with it :')
This is my piece of JS:
//Show ticket
function showTicket(id) {
$.ajax({url:"readTicket.php?ticket_id=" + id});
}
This is the piece of code supposed to link the headlines:
<?php echo '<a id="showTicketNow" onclick="showTicket('.$stt["ticket_id"].')">' ?>
<?php if(strlen($stt['subject']) > 40) $stt['subject'] = substr($stt['subject'], 0, 40).'...';
echo $stt['subject'] ?>
<?php echo '</a>' ?>
This is my readTicket.php
$user_id = $_SESSION['user_id'];
$ticket_id = mysqli_real_escape_string($mysqli, $_GET['ticket_id']);
$getTicketInfo = mysqli_query($mysqli,"SELECT * FROM tickets WHERE ticket_id = '$ticket_id' AND user_id = '$user_id'");
while ($row=mysqli_fetch_array($getTicketInfo)) {
$subject = $row['subject'];
$message = $row['message'];
}
echo '<div class="showTicket display subject">'.stripslashes($subject).'</div>
<div class="showTicket display message">'.stripslashes($message).'</div>';
Thanks in advance..
Try this, you were missing all of the syntax goodness.
echo'<a id="showTicketNow" onclick="showTicket('.$stt["ticket_id"].')">';
if(strlen($stt['subject']) > 40){
$stt['subject'] = substr($stt['subject'], 0, 40).'...';
}
echo $stt['subject'];
echo '</a>';
You need to specify href attribute of <a> tag, something like this:
<?php echo '<a href="javascript:void(0);" id="showTicketNow" onclick="showTicket('.$stt["ticket_id"].')">' ?>

Categories