Clicking on a div and saving its value to use with PHP - javascript

I have been having some problems with some code.
So I'm developing a website that accesses a mysql database and creates a number of divs accordingly to the number of specialties that are on the database.
<div id="services_panel">
<?php foreach ($specialties as $especialidade_id => $especialidade) { ?>
<div class="service_div" onclick ="highlightLink(this); $('#content_div').show();" value="<?php echo $especialidade_id; ?>"><?php echo $especialidade; ?></div>
<?php } ?>
</div>
<div id="content_div""/>
Now what I wanted to do was set the value of the content div to the value of $especialidade of the div that was clicked, but since javascript runs clientside and php runs server side, I know that I can't do it on onclick()
I'd really hope you guys could help me with this issue
Thanks in advance

Using onclick() inline you could do
onclick ="highlightLink(this); $('#content_div').show().html(this.innerHTML);"
or if you bind it separately using .on() and 'click'
$(function(){
$('.service_div').on('click',function(){
$('#content_div').show().html($(this).html());
});
});

Related

Check a button has been clicked in JS and then do something in PHP

I'm working in PHP and I have this button, than when clicked, should print something.
I've (unsuccessfully) tried the following:
<?php
echo '<button type="submit" id="enviarRecibos" class="btn btn-primary float-end">Imprimir Lista</button>';
?>
<script>
if(document.getElementById('enviarRecibos').clicked == true){
<?php
echo $listaDatos;
?>
}​;​
</script>
What am I doing wrong?
Note: $listaDatos is a variable that's already in the page with some content in JSON format.
I'm not sure i've well understand what you exactly want, but anyway your javascript script need improvement :
<?php
echo '<button type="submit" id="enviarRecibos" class="btn btn-primary float-end">Imprimir Lista</button>';
?>
<script>
document.getElementById('enviarRecibos').addEventListener('click', function (){
document.getElementById('enviarRecibos').insertAdjacentHTML('afterend', '<?php echo $listaDatos;?>') ;
}) ;
</script>
First the best way to track click on an element in javascript is with addEventListener.
Next, you want load content, ok, but you need to define the position / DOM element where the content need to be loaded. You can use "insertAdjacentHTML", an usefull function putting HTML content next to an existing element (here your button).
Take care "<?php echo $listaDatos;?>" doesn't contain a quote ' and return a valid HTML string.
AS #brombeer just told you, PHP is a server side language while Javascript is client side. PHP can only help you prepare the raw file code.

How to make an input value permanent in wordpress or work with global variables

I currently make my first Wordpress website using Java script snippets for a countdown that refreshes itself constantly and allows me to click a button once every 6 hours. So I managed that the time refreshes itself but I need one permanent variable that tells me if I already clicked the button or not (since it should work wether I refresh the page, go to another side or even log in with another user).
Basically I just want one variable that changes between 0 and 1.
I implemented a hidden input field and it works just fine as long as I stay on the side (refreshing the side works as well) but as soon as I change the page it sets the variable back. I tried to implement a global variable in the function.php of my theme (and a function as well) but it still doesn't work.
I tried it like this:
global $x;
echo $x;
And this:
function displayX() {
global $x;
$x = "0";
echo $x;
}
The thing is I don't want to set a value because the variable needs to be changeable any time.
That's my current html:
<input type="text" id="id1" value="<?php echo $x; ?>" <="" input="">
But it just doesn't work.
My second approach was to make the input field permanent (but updateable) - again this approach works as long as I don't change the side.
I tried it like this:
<span id="00">
<input type="text" id="id1">
</span>
Can anybody please help me? Also please specifiy where I have to set the global variable since there are so many function.php files.
THANK YOU!
Easiest way to do that is using of update_option and get_option.
update_option is for save data to database that will be permanent.
get_option is for fetching data from database.
<form method="post">
<input type="text" name="permanent" id="permanent" value="<?php echo get_option('permanent_data'); ?>"/>
<input type="submit" name="save" value="submit"/>
</form>
You can catch form data in backend using an action like this:
in functions.php
add_action('init','save_permanent');
function save_permanent(){
if(isset($_POST['save'])){
update_option('permanent_data', $_POST['permanent']);
}
}
Below code checks that if form is submitted:
if(isset($_POST['save'])){
update_option('permanent_data', $_POST['permanent']);
}
If form submitted it gets value of input text that named permanent
Mentioned code permanent the data in database as name of permanent_data
If you want to fetch stored data you just call get_option(option name) like this:
<?php echo get_option('permanent_data'); ?>
For first question you can do it in such way:
in functions.php
<?php
if(if(isset($_POST['save']))){
update_option('already_clicked', '1');
}
And for fetch stored data you can use:
<?php
if(get_option('already_clicked') == '1'){
//do somthing
}
?>

Jquery and AJAX script to run a PHP script in the background to avoid any refreshing

I have built a follow/unfollow Twitter like system using PHP. Now I would like to run the follow-unfollow PHP script in the background using AJAX/JQUERY to avoid refreshing the page when you follow/unfollow a user. To make things simpler, I will be here just using the example of “unfollow”. As you notice, I am running an iteration to output all the members in the database. I am outputting here (as well for simplicity) just the member’s name and an unfollow button to each one.
This is the code using php.
members.php
<?php foreach($members as $member){ ?>
<p class="member_name"><?php echo $member->name; ?></p>
<p class="follow_button">Unfollow</p>
<?php } ?>
unfollow.php
<?php
if($_GET['unfollow_id']){
$unfollow_id=$_GET['unfollow_id'];
$unfollow=Following::unfollow($id, $unfollow_id); //Function that will make the changes in the database.
// $id argument will be gotten from a $_SESSION.
}
I am trying to achieve the same result running unfollow.php in the background to avoid any refreshing. This is what I have come up with, as you might imagine it is not working properly. I am including the Jquery script inside the iteration which I think is the only way of obtaining the $member->id property to then assign it to the Jquery variable.
members.php THE NEW ONE THAT TRYS TO RUN THE SCRIPT WITH AJAX JQUERY
<?php foreach($members as $member){ ?>
<p class="member_name"><?php echo $member_name; ?></p>
<button type="button" class="unfollow_button" id="unfollow">Unfollow</button>
<script type="text/javascript">
$(document).ready(function(){
$("#unfollow").click(function(){
// Get value from input element on the page
var memberId = "<?php $member->id ?>";
// Send the input data to the server using get
$.get("unfollow.php", {unfollow_id: memberId} , function(data){
// Success
});
});
});
</script>
<?php } ?>
Can you provide me any help for this to work?
Thanks in advance.
Remember, in HTML, id attributes have to be unique.
Because you're rendering multiple members on a single page, you should not use an id selector in jQuery, but a class selector (e.g. button.unfollow). If you use #unfollow, you'll run into ID conflicts between each of the members' buttons.
First, render all of your members with unfollow buttons without ids. I'm adding the member_id in the markup using a data attribute called data-member_id.
<?php foreach($members as $member) { ?>
<p class="member_name"><?=$member_name?></p>
<button type="button" class="unfollow_button" data-member_id="<?=$member->id?>">Unfollow</button>
<?php } ?>
Then add a single click handler for all button.follow buttons, which extracts the member_id from the clicked button's data-member_id attribute and sends it to the server.
<script type="text/javascript">
$(document).ready(function() {
$("button.unfollow_button").on('click', function() {
// Get value from input element on the page
var memberId = $(this).attr('data-member_id');
// Send the input data to the server using get
$.get("unfollow.php", {unfollow_id: memberId} , function(data) {
// Success
});
});
});
</script>
On a side-note, you should probably look into building a RESTful service for this, to which you can post proper HTTP requests using http://api.jquery.com/jquery.ajax/.
See here for an intro on REST in PHP I wrote a while back:
Create a RESTful API in PHP?

how to put output php on a specic place

I have made two divs besides each other, the left div contains a list of names and in the right one is empty.
The names in the left div are generated from a database, also it's wrapped into a a tag so I can click on it.
echo "<a href='Overview.php?id=" .$row['ID'] . "'>" .$row['COMPANY']." </td> <br>";
When somebody clicks on the a tag it will generate a new variable: id in the browser link.
Now my main goal is to get this $row['ID'] variable into the right div.
What I tried (php function):
If the ID is set (= somebody clicked on the a tag) it will echo the id. But I have no clue how to place this into the right div (#rightcolumn)
function runMyFunction() {
echo $_GET['id'];
}
if (isset($_GET['id'])) {
runMyFunction();
}
Thank you for reading!
so call your function in right div
<div id="rightcolumn"><?php if(isset($_GET['id'])) {runMyFunction();}?></div>
Someone already posted a solution for PHP.
But you can also consider using JQuery and fire an on click event :
<div class="container">
<div class="left">
Name1<br>
</div>
<div class="right">
</div>
</div>
JQuery:
$('#Id1').on('click', function(){
var id = $('#Id1').attr('id');
$('.right').text(id);
});
Use Jquery or javascript
echo "$('#rightcolumn').html(".$_GET['id'].");";
or
echo "document.getElementById('rightcolumn').innerHTML = ".$_GET['id'].";";

How to run php code in javascript when callback is called?

I'm using easyModal to create modal windows in my web. Saw that they have callback onClose and I want use php code on close is it possible, if yes How to do that? I want to unset some values from sessions (don't have much experience in javascript, jquery or ajax)
This is my code:
<div id="ebox">
<?php
echo $_SESSION['unameE'];
echo $_SESSION['pwordE'];
echo $_SESSION['emailE'];
?>
</div>
$(function() {
$('#ebox').easyModal( {
autoOpen:<?php echo $error; ?>
onClose:???
});
});
Or maybe there is another solution that unsets values from session after displaying it once?
on your script you should have :
onClose: function(){
$("#ebox").html(' ') ;
$.post("remove-session.php");
}
and then on the page "remove-session.php" you can do all sort of stuff with your session:
<?php
unset($_SESSION['unameE']);
//...
//or even
session_destroy();
?>

Categories

Resources