I may have misunderstood the purpose of PHP here. But I want to do the following:
I have a PHP function, and I call it from HTML, e.g.
<BODY>
<DIV id='A'>
<?php emit("hello1"); ?>
</DIV>
<DIV id='B'>
<?php emit("hello2"); ?>
</DIV>
</BODY>
And I want to know, within the function, which DIV it was called from.
e.g.
<?php function emit($txt){
echo "$txt";
echo "from DIV id $DIVID"
}
?>
And I want it, obviously, to print
hello1 from DIV id A
hello2 from DIV id B
Is there any way of finding the "current" DIV's ID?
Yes, you have misunderstood the purpose of PHP.
PHP is a server side programming language, it does not run on the HTML page, but before the HTML gets loaded on to the browser.
The task that you are trying to do can be done from JavaScript if interested. I will give an example of jQuery:
var emit = function(el, txt) {
var id = el.attr('id');
el.html(txt+" from DIV id "+id);
}
Now call using
emit($("#a"), "hello1");
Same can be done from JS in the following way
var emit = function(el, txt) {
el = document.getElementById("el");
id = el.getAttribute('id');
el.innerHTML(txt+" from DIV id "+id);
};
Use like:
emit("a", "hello1");
Related
My question is simple.
I have the following code:
<div class="last"
<?php
if hasClass(last){
echo " style='width:100%;' ";
}
?>
></div>
I know the if statement is wrong, but the idea is there. I want to know how can I check if this div has the .last class then echo something.
I've been searching around but didn't work anything (didn't find much though).
Best regards.
As already in the comments told it's possible with PHP with DOM parsers.
I'm gonna give you 2 very simple solutions which will save you a lot of work:
CSS:
<style>
.last {
width:100%;
}
</style>
jQuery:
<script type="text/javascript">
$(document).ready(function(){
if($('div').hasClass('last')){
$('div').css('width', '100%');
}
});
</script>
PHP runs on server, so it generates HTML. If you have that class="last" you don't need to check - it's part of the code....hard-coded.
But you can have some PHP variable and depending on it's place print out class and also style for that other element:
<?php
$print_last = true;
?>
...
<div <?php if ($print_last) echo 'class="last" ';
<?php
if ($print_last){
echo " style='width:100%;' ";
}
?>
></div>
But if you want to check on html element you have to do it on client side (browser) from JavaScript and jQuery can be helpful too.
It is possible to check that using PHP, however that couldn't be done easliy (you'll need to parse buffered HTML using DOM parser, then look up for divs, etc...).... Much better solution is to do that with Javascript/jQuery, using Document.getElementsByClassName() function.
Sample solution:
var elements = document.getElementsByClassName("last");
for(var i = 0; i < elements.length; i++)
{
var element = elements[i];
element.style.width = "100%";
}
#azhpo
Obviously the HTML being the front end language you have to pass the elements either through some submit button or via ajax request.
Using submit button: select the class name of div using either javascript
var className = document.getElementById("myDIV").className
document.getElementById("myHiddenField").value = className;
Now on clicking the submit button it would get submitted
Using ajax:
Again take the classname either through javascript / jquery
var className = jQuery("#myDiv").attr("class");
Now fire ajax query and send the class name to your script
jQuery.ajax({
url: 'file.php',
type: 'POST',
data: 'class='+className,
success: function(data){//do whatever you want},
error:function(){//do whatever you want}
});
I am very new to PHP and I am trying to get a piece of PHP code to run inside of my HTML file.
I have a drop down menu. If users select one item, it should display additional fields. So, I want them to only display if they select that item from the drop down menu. I am trying to select it based on the value for that drop down item. I have not declared any PHP values in a PHP script. This is all in HTML.
I know that with jquery you have to pull in the jquery library before running the script. Do I need to do this with PHP also?
Here is the code that I am trying to run:
Thank you in advance!
html file
<?php
if ($dropmenuValue == specificDropDownOption) {
?>
<div>
-conditional content-
</div>
<?php
}
?>
One of the main things about PHP and other server-side languages is that once they render the page, they shut down, and that's it. There's nothing they can do after.
You need to resort to a client-side here, probably the simplest way being adding the values of PHP variables to the appropriate JavaScript variables and then taking it from there. You would also need to render all possible contents and only show what you need.
So, in your case, you could make a CSS class to denote hidden content and then use JavaScript to hide/show different parts of the markup. Please note that all the hidden code (rendered by PHP, but hidden by CSS) is still visible in the page source, so if you have anything sensitive in there you should definitely do it by either making AJAX calls to load partial content, or regular page redirection/navigation.
EDIT
Here is a super-simple example I made for you, to see how you can show/hide content:
HTML (parts can be rendered by PHP, of course)
<div id="content1" class="content">Hey</div>
<div id="content2" class="content hidden">There</div>
<div id="content3" class="content hidden">World</div>
<hr />
<button onclick="show(1)">Show 1</button>
<button onclick="show(2)">Show 2</button>
<button onclick="show(3)">Show 3</button>
JS
function show(id) {
// select all the content divs
var allDivs = document.getElementsByClassName('content');
// iterate over them and add a hidden class to each
for (var i = 0; i < allDivs.length; i++){
allDivs[i].classList.add('hidden');
}
// finally, remove the hidden class from the one we referenced
document.getElementById('content' + id).classList.remove('hidden');
}
See it in action here: http://jsfiddle.net/f0onk7bk/
You can try something out with this... While using HTML inside of the PHP
#item { display: block;}
#itme.active { display:none }
Something like this would work when the page was loaded/reloaded...
<?php
if(isset($_POST['dropdown_name_here']) && $_POST['dropdown_name_here'] == "specificParameter")
{
echo("<div id='condition_one_div'> ... </div>");
}
else
{
echo("<div id='condition_two_div'> ... </div>");
}
?>
... but JavaScript is what you would want to use for dynamic content I would think.
var div = document.getElementById('div_name_here');
var dropdown = document.getElementById('dropdown_name_here');
if(dropdown.value == "specificParameter")
{
//add/show content for div here
}
else
{
//hide content for div here
}
is this what you are looking for?
<select id='dropdown_name' onchange='if(this.value == "parameter"){ document.getElementById("div_name").style.display = "block"; }else{ document.getElementById("div_name").style.display = "none"; }' >
</select>
<button type="button" id="okButton" onclick="funk()" value="okButton">Order now </button>
<script type="text/javascript">
function funk(){
alert("asdasd");
<?php echo "asdasda";?>
}
</script>
When the button is pressed I want to execute PHP code (at this point to echo asadasda)
You could use http://phpjs.org/ http://locutus.io/php/ it ports a bunch of PHP functionality to javascript, but if it's just echos, and the script is in a php file, you could do something like this:
alert("<?php echo "asdasda";?>");
don't worry about the shifty-looking use of double-quotes, PHP will render that before the browser sees it.
as for using ajax, the easiest way is to use a library, like jQuery. With that you can do:
$.ajax({
url: 'test.php',
success: function(data) {
$('.result').html(data);
}
});
and test.php would be:
<?php
echo 'asdasda';
?>
it would write the contents of test.php to whatever element has the result class.
Interaction of Javascript and PHP
We all grew up knowing that Javascript ran on the Client Side (ie the browser)
and PHP was a server side tool (ie the Server side). CLEARLY the two just cant interact.
But -- good news; it can be made to work and here's how.
The objective is to get some dynamic info (say server configuration items) from the server into the Javascript environment so it can be used when needed - - typically this implies DHTML modification to the presentation.
First, to clarify the DHTML usage I'll cite this DHTML example:
<script type="text/javascript">
function updateContent() {
var frameObj = document.getElementById("frameContent");
var y = (frameObj.contentWindow || frameObj.contentDocument);
if (y.document) y = y.document;
y.body.style.backgroundColor="red"; // demonstration of failure to alter the display
// create a default, simplistic alteration usinga fixed string.
var textMsg = 'Say good night Gracy';
y.write(textMsg);
y.body.style.backgroundColor="#00ee00"; // visual confirmation that the updateContent() was effective
}
</script>
Assuming we have an html file with the ID="frameContent" somewhere,
then we can alter the display with a simple < body onload="updateContent()" >
Golly gee; we don't need PHP to do that now do we! But that creates a structure for
applying PHP provided content.
We change the webpage in question into a PHTML type to allow the server side PHP access
to the content:
**foo.html becomes foo.phtml**
and we add to the top of that page. We also cause the php data to be loaded
into globals for later access - - like this:
<?php
global $msg1, $msg2, $textMsgPHP;
function getContent($filename) {
if ($theData = file_get_contents($filename, FALSE)) {
return "$theData";
} else {
echo "FAILED!";
}
}
function returnContent($filename) {
if ( $theData = getContent($filename) ) {
// this works ONLY if $theData is one linear line (ie remove all \n)
$textPHP = trim(preg_replace('/\r\n|\r|\n/', '', $theData));
return "$textPHP";
} else {
echo '<span class="ERR">Error opening source file :(\n</span>'; # $filename!\n";
}
}
// preload the dynamic contents now for use later in the javascript (somewhere)
$msg1 = returnContent('dummy_frame_data.txt');
$msg2 = returnContent('dummy_frame_data_0.txt');
$textMsgPHP = returnContent('dummy_frame_data_1.txt');
?>
Now our javascripts can get to the PHP globals like this:
// by accessig the globals
var textMsg = '< ? php global $textMsgPHP; echo "$textMsgPHP"; ? >';
In the javascript, replace
var textMsg = 'Say good night Gracy';
with:
// using php returnContent()
var textMsg = '< ? php $msgX = returnContent('dummy_div_data_3.txt'); echo "$msgX" ? >';
Summary:
the webpage to be modified MUST be a phtml or some php file
the first thing in that file MUST be the < ? php to get the dynamic data ?>
the php data MUST contain its own css styling (if content is in a frame)
the javascript to use the dynamic data must be in this same file
and we drop in/outof PHP as necessary to access the dynamic data
Notice:- use single quotes in the outer javascript and ONLY double quotes in the dynamic php data
To be resolved: calling updateContent() with a filename and
using it via onClick() instead of onLoad()
An example could be provided in the Sample_Dynamic_Frame.zip for your inspection, but didn't find a means to attach it
You can't run PHP with javascript. JavaScript is a client side technology (runs in the users browser) and PHP is a server side technology (run on the server).
If you want to do this you have to make an ajax request to a PHP script and have that return the results you are looking for.
Why do you want to do this?
If you just want to echo a message from PHP in a certain place on the page when the user clicks the button, you could do something like this:
<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
alert("asdasd");
document.getElementById('resultMsg').innerHTML('<?php echo "asdasda";?>');
}
</script>
However, assuming your script needs to do some server-side processing such as adding the item to a cart, you may like to check out jQuery's http://api.jquery.com/load/ - use jQuery to load the path to the php script which does the processing. In your example you could do:
<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
alert("asdasd");
$('#resultMsg').load('path/to/php/script/order_item.php');
}
</script>
This runs the php script and loads whatever message it returns into <div id="resultMsg">.
order_item.php would add the item to cart and just echo whatever message you would like displayed. To get the example working this will suffice as order_item.php:
<?php
// do adding to cart stuff here
echo 'Added to cart';
?>
For this to work you will need to include jQuery on your page, by adding this in your <head> tag:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
Any server side stuff such as php declaration must get evaluated in the host file (file with a .php extension) inside the script tags such as below
<script type="text/javascript">
var1 = "<?php echo 'Hello';?>";
</script>
Then in the .js file, you can use the variable
alert(var1);
If you try to evaluate php declaration in the .js file, it will NOT work
put your php into a hidden div and than call it with javascript
php part
<div id="mybox" style="visibility:hidden;"> some php here </div>
javascript part
var myfield = document.getElementById("mybox");
myfield.visibility = 'visible';
now, you can do anything with myfield...
We can use php in JavaScript by creating a form element and put the action as a .php page.
Then we use JavaScript to submit that form.
EX:
<!doctype html>
<html>
<head>
<title>PHP Executed with JS</title>
</head>
<body>
<form action="phpCode.php" id="phpCode">.
</form> <!-- This is the form-->
<script>
function runPhp() {
var php =
document.getElementById("phpCode")
php.submit() //submit the form
}
</script>
</body>
The PHP file name would be phpCode.php.
In that file would be your PHP code.
May be this way:
<?php
if($_SERVER['REQUEST_METHOD']=="POST") {
echo 'asdasda';
}
?>
<form method="post">
<button type="submit" id="okButton">Order now</button>
</form>
If you do not want to include the jquery library you can simple do the following
a) ad an iframe, size 0px so it is not visible, href is blank
b) execute this within your js code function
window.frames['iframename'].location.replace('http://....your.php');
This will execute the php script and you can for example make a database update...
Use ajax to send request and echo the response
when successfully executed. Like this:
$.get("site.com/ajax", function(status,data){
alert(status);
});
This can be achieved with jquery library.
You could run PHP at the start of the Page and grap the results from inputs
<?php
c = a * b;
?>
<input type="hidden" name="c" value="<?php c ?>"/>
<button type="submit">Submit</button>
</form>
<script>
let cValue = $('input[name="c"]').val();
alert(cValue);
</script>
I am creating a drag and drop system using redips javascript.
This is my script using html and php to generate the data
<div id="base">
<table>
<tbody>
<?php
foreach($deviceID as $row)
{
echo '<tr><td><div class="drag">'.$row['description'].'<input type="hidden" id="bus" value="'.$row['description'].'"></div></td></tr>';
}
?>
</tbody>
</table>
</div>
This is the fragment of my javascript file.
var redips_init;
redips_init = function () {
// reference to the REDIPS.drag
var rd = REDIPS.drag;
// initialization
rd.init();
rd.drop_option = 'shift';
rd.animation_shift = true;
rd.myhandler_dropped = function () {
alert($('#bus').val());
}
};
I am not good with php but what i usually do in jsp is create a local index variable and append it to each of the ID attribute in the loop.
So your code would look something like this
<?php
$index=0;
foreach($deviceID as $row)
{
echo '<tr><td><div class="drag">'.$row['description'].'<input type="hidden" id="bus'.$index++.'" value="'.$row['description'].'"></div></td></tr>';
}
?>
In javascript, your dragAndDrop event should return an index location by which u can get appropriate value.
Now you can use this dynamic ID in your JavaScript to do whatever you want to do.
REDIPS.drag contains save_content() method to scan all DIV elements in a table and to return the result as Query string or JSON object. Input parameters are table id and type of returned result (default is query string). If this is not good enough, you can search for save_content() source and make customization. Method is simple and it uses several loops to scan table content.
On the other hand, if you need to know ID of dropped DIV element that can be written inside myhandler_dropped event hander. Here is code snippet:
rd.myhandler_dropped = function () {
// define DIV id
var id = rd.obj.id;
// write DIV id to the console
console.log(id)
};
Hope this answer will be helpful.
I have been a really big fan of stackoverflow(which led me to ask the question here and not anywhere else), anyway, without further ado...
While creating a shop system, I planned to implement an ajax which buys the item on the fly. Now This is how the loop for retrieving items looks like:
<?php
$shop_query = mysql_query("SELECT * FROM sector0_item WHERE 1");
$numrows = mysql_num_rows($shop_query);
While ($shop_fetch = mysql_fetch_array($shop_query)){
?>
<div id="shop_main">
<div class = 'item_img'>
<a><img src = "http://images.wikia.com/dofus/images/4/4e/Discovery_Potion.png" height = '100px'/></a>
</div>
<div class="item_buy">
<a><center>Price: <?php echo number_format($shop_fetch['item_price']);?></center><br /></a>
<a>Quantity: <input type = 'text' size = '9' id = 'itemquantity'/><br /></a>
<a><p>Point requirement: <?php echo number_format($shop_fetch['item_pt_req']);?></p></a>
<a><input type = 'button' id = 'buy' value = 'buy'/></a><span id = 'buy_status'></span>
</div>
<a><h3><?php echo $shop_fetch['item_name'];?></h3></a>
<a><p><?php echo $shop_fetch['item_desc'];?></p></a>
<a>Item Type: <font color = 'green'><?php echo $shop_fetch['item_class'];?></font></a>
</div>
<br />
<?php
}
?>
However, my ajax seems to act really weird. My implementation was to show a loading gif image.
Script:
<script type = 'text/javascript'>
$('#buy').click (function(){
var quantity = $('#itemquantity').val();
$('#buy_status').html('<img src = "http://www.antibodyresource.com/theme/js/ajax-loader.gif" height = 20px;/>');
});
</script>
The problem is, Only one button shows the circle when clicked. Does the position of the script cause this? Any help is appreciated.
You can only have one item with a given id. When you have multiple elements with the same id, it is indeterminate which one will be returned, but it will usually be the first item only.
If you want multiple buy buttons and want to assign them all the same jQuery event handler, then use a common class name instead of an id.
If you are loading content dynamically and you want event handlers to work for that content, then you need to use delegated event handling.
In jQuery, that is generally done with either .on() or .delegate(). The basic idea is that you pick a static parent object that is not dynamically loaded (perhaps the parent of show_main) and bind the event to that object and then pass the selector of the dynamic element like this (note, I've changed from an id to a class to identify the buy button):
$(staticParentSelector).on('click', '.buyButton', function() {
$(this).closest(".item_buy").find(".buy_status").html('<img src = "http://www.antibodyresource.com/theme/js/ajax-loader.gif" height = 20px;/>');
})
Two things:
It's hard to tell from the sample, but is there an iterator that creates a list of available items? If so, you shouldn't be using IDs which are meant to be unique. If there's really only one #buy then you're fine, though.
When content is updated with Ajax, you're going to lose bindings. Assuming the item related to the #buy button gets replaced with other items, you're better off with a delegated event:
// not in an inline script, but just once, ideally in your main JS file
$(document).ready(function() {
$('#wrapper').on('click', '#buy', (function(){
var quantity = $('#itemquantity').val();
$('#buy_status').html('<img src = "http://www.antibodyresource.com/theme/js/ajax-loader.gif" height = 20px;/>');
});
})
Where #wrapper is some ancestor higher up in the DOM tree that is never destroyed by the Ajax event.
id is unique value - on html page each id must have unique value. Use class instead.
You need to put your code inside $(document).ready(). So its:
$(document).ready( function() {
$('#buy').click( function(){
// do something here
});
});
Also, you may want to list to jfriend00's advice on IDs.