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>
Related
My script removes the http:// and www from urls displayed in a post's content but for some reason it either affects all the posts but the last one or just the first post of the page depending on where I place the script.
For instance if it's in the loop it will affect all the posts but the last but if it's outside the loop it only affects the first post.
I'm looking for a solution so that it takes affect on all urls being displayed on a page. Any help would be much appreciated.
<?php
if (have_posts()) :
while (have_posts()) : the_post(); ?>
<Script>
$(document).ready(function removeFunction() {
let post_id = '<?php global $post; echo $post->ID; ?>';
var str = document.getElementById("link" + post_id).innerHTML;
var res = str.replace(/^(?:https?:\/\/)?(?:www\.)?/i, "").split('/')[0];
document.getElementById("link" + post_id).innerHTML = res;
});
</Script>
<p><?php the_content(); ?></p>
<!-- This is where the URL's are EX: <a id="link[return_post_id]" href="http://example.com/">http://example.com/</a> -->
<?php endwhile;
else :
echo '<p>No content found</p>';
endif;
?>
1.You tagged jQuery there so put jQuery code outside of loop.
2.It has to iterate over all <p> and do what you are doing.
3.Change <p><?php the_content(); ?></p> to <p data-id="<?php global $post; echo $post->ID; ?>"><?php the_content(); ?></p> (inside while loop)
4.After above steps followed, change jQuery code like below:
<Script>
$(document).ready(function() {
$('p').each(function(){
let post_id = $(this).data('id');
var str = $(this).html();
var res = str.replace(/^(?:https?:\/\/)?(?:www\.)?/i, "").split('/')[0];
$(this).html(res);
});
});
</Script>
there is a problem and this is on mixture of php and javascript.
Your php code Generate JS Within a Loop, in each loop it will create a function named removeFunction() and your browser interpreter mixed up things. it will replace the last one.
There Are 2 Solution for Your problem:
First is to make These Functions Distinct like This:
$(document).ready(function removeFunction<?php echo $post->ID; ?>() {
this will make function names as removeFunction1() removeFunction2() ...
The Second Sulotion is to Define The function outside The loop and in the php loop just call the function like this:
while (have_posts()) : the_post(); ?>
<script>
removeFunction(<?php global $post; echo $post->ID; ?>);
and your function definition would be like this:
removeFunction(post_id){
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);
?>
I have a page in PHP and I would open a function with a click.
Function shows me a query result, but when I write this code it doesn't work
<div class="btn-group">
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
Frequenza <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<?php
$query_frequenza="SELECT DISTINCT FREQUENZA FROM Dettagli_macchina WHERE macchine_id='$macchine' and Email='$_SESSION[login_user]'";
$result=mysqli_query($conne,$query_frequenza);
while($row=mysqli_fetch_array($result)){
$frequenza=$row['FREQUENZA'];
echo"<li><a href='#?frequenza=$frequenza' onclick='showfiltro2()'>$frequenza</a></li>";
}
?>
</ul>
</div>
<script type = "text/javascript">
function showfiltro2() {
document.getElementById("filtro2").style.display = "block";
document.getElementById("filtro1").style.display = "none";
}
</script>
<div id = "filtro2" style="display:none">
<?php
$filtro2=$_GET['frequenza'];
$query="SELECT DISTINCT * FROM Dettagli_macchina WHERE macchine_id='$macchine' and Email='$_SESSION[login_user]' and FREQUENZA='$filtro2' ";
$result=mysqli_query($conne,$query);
echo 'Found '. mysqli_num_rows($result) .'results';
echo "<table><tr>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr><td>";
echo $row['COMPONENTE'];
echo "</td>";
echo "<td>";
echo $row['DETTAGLIO ATTIVITA'];
echo "</td>";
echo "<td>";
echo $row['FREQUENZA'];
echo "</td>";
echo "<td>";
echo $row['DATA-PREVISTA'];
echo "</td>";
echo "</tr>";
}
echo"</tr></table>";
?>
</div>
Your question stems from a misunderstanding of how PHP and HTML work, and how data flows between the two.
First off it's important to remember that PHP and HTML are two completely separate parts, which do not interact with each other outside of the "request->reply" chain.
This means that all of the PHP code gets executed on the server, before the client gets the output of this processing. The server (PHP) doesn't care about what kind of output it is, nor does it understand how to parse it; For all PHP knows, it's all simple text.
After the PHP code has been completely parsed, the client receives the resulting text. Then it notices that it can understand this text as HTML, and parses it as a web-page. At this point the PHP code doesn't exist in the code at all, and the web browser (client) doesn't know anything about it.
It is unfortunate that so many tutorials keep mixing PHP and HTML code like you've done above, as this further confuses the two and makes it look like they're inter-communicative. What I recommend is to move all of your PHP code above any HTML-code, and do all of the processing before sending anything to the browser.
Not only will this make it a lot easier to actually keep track of, and understand, what's happening and why; But it will also allow you to add more functionality to your code, without trying to break the laws of physics. (For example: Deciding that you don't want to show a form to the user after all, half-way through the generation of said form.)
All this means that you don't "open a function" with a click. You send a request to the server with said click, and then the PHP code checks the incoming data for some predetermined condition (GET-parameter, etc), and then calls the function of said condition is fulfilled.
Something like this, in other words:
// First off we should use PDO, as mysql_*() is deprecated and removed in PHP7.
$db = new PDO ($dsn);
// Using prepared statements here, to prevent SQL injections.
$stmt = $db->prepare ("SELECT DISTINCT FREQUENZA FROM Dettagli_macchina WHERE macchine_id=:machineID and Email=:email");
$data = array (':machineID' => $macchine, ':email' => $_SESSION['login_user']);
if (!$stmt->exec ($data)) {
// Something went wrong, handle it.
}
// Initialize a variable to hold the generated menu, and a template to use when creating it.
$menuOut = $searchOut = '';
$menuTemplate = "<li><a href='#?frequenza=%s' onclick='showfiltro2()'>%s</a></li>";
// Using prepared statements we can iterate through all of the results with foreach().
foreach ($stmt->fetchAll () as $row) {
// Using htmlspecialchars() and rawurlescape() to prevent against XSS, and other HTML-injection attacks/mistakes.
// Notice where and in what order I've used the different functions, as one protects the URL as well.
$menuOut .= sprintf ($menuTemplate, htmlspecialchars (rawurlencode ($row['FREQUENZA'])), htmlspecialchars ($row['FREQUENZA']));
}
// Since this is probably the "function" you want to execute with said click, this is where we check if it
// has been sent by the client.
if (!empty ($_GET['frequenza'])) {
// Here you want to check to see if the parameter is actually something you'd expect, and not some random(?) garbage.
$filtro2 = $_GET['frequenza'];
// Again, prepared statements as your code was open to SQL injections!
$query = "SELECT DISTINCT * FROM Dettagli_macchina WHERE macchine_id=:machineID and Email=:email and FREQUENZA=:frequency";;
$stmt = $db->prepare ($query);
$data = array (
':machineID' => $macchine,
':email' => $_SESSION['login_user'],
':frequency' => $filtro2);
if (!$res = $stmt->exec ($data)) {
// Somethign went wrong with the query, handle it.
}
// Initialize a variable to hold the output, and the template to use for generating it.
$searchOut = '<table>';
$searchTemplate = '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>';
$count = 0;
foreach ($stmt->fetchAll () as $row) {
// Again, protection against XSS and other HTML-breaking mistakes.
$searchOut .= sprintf ($searchTemplate,
htmlspecialchars ($row['COMPONENTE']),
htmlspecialchars ($row['DETTAGLIO ATTIVITA']),
htmlspecialchars ($row['FREQUENZA']),
htmlspecialchars ($row['DATA-PREVISTA']));
}
$searchOut = "<p>Found {$count} results</p>{$searchOut}</table>";
}
?>
<div class="btn-group">
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
Frequenza <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<?php echo $menuOut; ?>
</ul>
</div>
<script type="text/javascript">
function showfiltro2() {
document.getElementById("filtro2").style.display = "block";
document.getElementById("filtro1").style.display = "none";
}
</script>
<div id="filtro2" style="display: none">
<?php echo $searchOut; ?>
</div>
I've added some comments to explain what and why I've done things, as well as changed over from the old(!), deprecated and obsolete mysql_*() functions to PDO.
You can read more about how to use PDO in the PHP manual
HTML:
<section class="clientbox">
<div class="container">
<div class="col-lg-10 col-lg-offset-1">
<h2>WHAT CLIENT SAYS</h2>
<h4>POSITIVE REVIEWS FOR LOVING PROBLAM.COM </h4>
<p id="testimonial"><?php echo $alldata[0]['text'] ?></p>
</div>
</div>
</section>
javascript:
<script type="text/javascript">
<?php $i = 1; ?>
setInterval(function()
{
document.getElementById('testimonial').innerHTML = "<?php echo $alldata[$i]['text'] ?>";
<?php $i++; ?>
}, 3000);
What actually I am trying to do is change the text of 'testimonial' from values stored in $alldata array every 3 secs.
The problem is that the php variable $i is not getting updated. It stays 1 only.
You mixed the server side logic (PHP) with the client side logic (JavaScript).
When the client request your web page, PHP render the contents which contains HTML, CSS, JavaScript and some other contents and the web server send these contents to the client side.
The web browser receives these contents and then execute the JavaScript and render the HTML according to the styles.
You need to generate all the contents needed by the JavaScript setInterval on the server side, and adjust your JavaScript logic to iterate on these data.
The logic may looks like the following. I'm not familiar with PHP, not sure if this is valid. The JavaScript doesn't check if all data has been consumed.
<script type="text/javascript">
<?php
function get_data($e) {
return($e['text']);
}
$data = array_map("get_data", $alldata);
?>
var js_alldata = <?php echo json_encode($data) ?>;
var i = 1;
setInterval(function()
{
document.getElementById('testimonial').innerHTML = js_alldata[i % js_alldata.length];
i++;
}, 3000);
You can't mix PHP and Javascript like that. PHP runs first, producing some data for Javascript to interpret. From Javascript's perspective, it can only see this:
<script type="text/javascript">
setInterval(function()
{
document.getElementById('testimonial').innerHTML = "some data";
}, 3000);
</script>
You would need to pass all of the data to Javascript so it can iterate over it.
See this answer for how to mix PHP and Javascript.
I've made this code and it is working. As people above told you, server side cannot work with the client-side iterations or setIntervals, therefore you should send the whole data beforehand.
Example:
$array = array();
$array[0]['text'] = 'hi';
$array[1]['text'] = 'hey';
$array[2]['text'] = 'hou';
$js_array = json_encode($array);
?>
<p id="testimonial"><?php echo $array[0]['text'] ?></p>
<script>
var json;
var i=1;
json = <?php echo $js_array; ?>
setInterval(function()
{
document.getElementById('testimonial').innerHTML = json[i]['text'];
i++;
}, 3000);
console.log(json);
</script>
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')"