is it possible to achive similiar results in JavaScript ? My aim is to not write static html within string literals.
<?php
if (someCondition) {
?>
I'm here, because PHP allows it.
<?php
}
?>
For example:
<script>
if (someCondition) {
</script>
I'm here, because JavaScript allows it.
<script>
}
</script>
I am aware of the following solution:
<p id = "variable">I'm here, because JavaScript allows it.</p>
<script>
var p = document.getElementById('variable');
if (!someCondition) {
p.parentNode.removeChild(p);
}
</script>
Nice thought, but it's not possible in the way you want it.
Every <script> element is evaluated as a JavaScript independent program, which will throw a syntax error in your case.
You'll have to generate the <p> element inside of your JavaScript.
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}
});
<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>
how can use JS variable in PHP like this ?
<script>
x = document.getElementById(1).value;
var listOf = <?php echo $listOf[x]; ?>;
</script>
this doesn't work :(
And rightfully so. PHP is executed on the server, while JavaScript is executed in the client's browser. Those are two different contexts and the variables from one are not visible in the second.
You need to have your PHP script output a JavaScript version of the array and then use this one in your script. Something like this:
<?php
echo "listArray = new Array();\n";
foreach ($listArray as $key => $value) {
echo 'listArray[', $key, '] = ', $value, ";\n";
}
You can't use it directly like this.
You'll have to use AJAX to send the value from client side to server side and only then PHP can see it.
Using jQuery it can become really simple though:
x = document.getElementById(1).value;
$.get("mypage.php?x=" + x, function(result) {
alert("response from PHP: " + result);
});
And in the PHP read the x from querystring and send proper output.
it is not possible because both are different languages so you cant use javascript varible
in php inside javascript
This is not possible. PHP is executed serverside, even before its output reaches your browser. JS is executed clientside, in the browser. You can't do this, unless you call some other PHP script with this variable x.
You can't. JavaScript is run in your browser while PHP gets run on the server. The only way for JavaScript to communicate with PHP is by using AJAX (XMLHttpRequest), separating the JavaScript from the PHP.
like this
if you put php in any single or double quotes than it work
<script type='text/javascript'>
x = document.getElementById(1).value;
var listOf = "<?php echo $listOf[x]; ?>";
</script>
This will convert javascript variable to php variable.
<script>
function sud(){
javavar=document.getElementById("text").value;
document.getElementById("rslt").innerHTML="<?php
$phpvar='"+javavar+"';
echo $phpvar.$phpvar;?>";
}
function sud2(){
document.getElementById("rslt2").innerHTML="<?php
echo $phpvar;?>";
}
</script>
<body>
<div id="rslt">
</div>
<div id="rslt2">
</div>
<input type="text" id="text" />
<button onClick="sud()" >Convert</button>
<button onClick="sud2()">Once Again</button>
</body>
Demo: http://ibence.com/new.php
I have this jquery code in a foreach loop. Basicaly the variable $perf gets a new value with every loop. How can I use jquery to display the different $perf value with each loop? Is it possible?
foreach ($perfs as $perf):
<script type="text/javascript">
$(document).ready(function(){
var performerName = $(".transparency").data('title');
var divcontent = $(".transparency").html();
if ( divcontent == ' ' ){
$(".transparency").html(''+performerName+'');
}
});
</script>
<div class="transparency" data-title="<? echo $perf; ?>"> </div>
endforeach;
You should do it like this:
<?
foreach ($perfs as $perf):
?>
<script type="text/javascript">
$(document).ready(function(){
var $perf = "<? echo $perf; ?>"; //Get from php
alert($perf); //Show it
//Here goes the rest of your script
var performerName = $(".transparency").data('title');
var divcontent = $(".transparency").html();
if ( divcontent == ' ' ){
$(".transparency").html(performerName);
}
});
</script>
<div class="transparency" data-title="<? echo $perf; ?>"> </div>
<?
endforeach;
?>
That's it. It works.
(I tried to modify your code at least as possible, cause I don't know if I can remove parts)
PS: There would be more 'elegant' solutions, do you want one? or this is enough?
Can you please describe what you are trying to do? I'm about 90% sure there is zero reason for any javascript, jQuery or otherwise.
Why not just do this?
<?php
foreach($perfs as $perf)
{
echo "<div class='transparency' data-title='$perf'>$perf</div>";
}
?>
Unless there is something more you are trying to do, you don't need javascript at all. And even if you do need javascript, take the function out of the loop and call it once each iteration. you dont need the exact same function defined multiple times.
I suggest you look into the relationship between server and client-side scripting. For starters - take a look at the HTML source generated by your PHP and see if thats anything close to what you want. Also, read up about ajax. It seems that you are trying to do combine PHP/javascript in such a way that it needs additional HTTP Requests (ajax calls)
It is impossible to have PHP and javascript interact directly without AJAX, and it is difficult to answer the question without more knowledge of what, exactly, you want to happen.
If you want a different transparacy div for each value of $perfs you can use:
<?php foreach ($perfs as $perf) { ?>
<div class="transparency" data-title="<?php echo $perf; ?>"> </div>
<?php } ?>
And they you can use the jquery .each() to iterate over the divs
$(".transparency").each( function() {
var performerName = $(this).data('title');
// do stuff //
});
If all you want is to pass the values in $perfs to you javascript function you can use
var perfs = <?php echo json_encode($perfs); ?>;
OK I think I see what you are trying to do now. You'll want something like this:
<script type="text/javascript">
$(document).ready(function(){
var perfs = <?php echo json_encode($perfs); ?>;
$.each( perfs, function( index, value ) {
$( ".transparency" ).append( value+'<br>' );
} );
} );
</script>
<div class="transparency"></div>
This will output each value of $perfs inside of the transparency div.
Using JQuery each and append.
You will never want to wrap an entire script in a foreach loop, as that will create a separate script for each element in the array. Using json_encode you will change the PHP array into a javascript object & you can do whatever you want to with it.
Remember javascript is only able to access elements written to the page using echo or something similar. Whatever you can see when you look at 'view page source' in your browser is all your script will be able to use.
I want to dynamically tell a javascript which <div> to hide, but I dont know how to send the request to the javascript as it is a client side script.
for eg:
<?
$divtohide = "adiv";
?>
<script language="javascript">
function hidediv($divtohide) {
................
}
</script>
Assuming $divtohide actually contains the ID of a <div> element and not a JavaScript variable name, write your JavaScript function as normal:
function hidediv(divtohide) {
// Your code may differ here, mine's just for example
document.getElementById(divtohide).style.display = 'none';
}
And print out the PHP variable only when you're calling it, within a pair of quotes:
hidediv("<?php echo addslashes($divtohide); ?>");
addslashes() ensures that quotes " in the variable are escaped so your JavaScript doesn't break.
as BoltClock wrote, use php to pass the variable.
but you can do it by most simple way, just write hidediv("<?=$divtohide?>")
<script type="text/javascript">
function hidediv() {
divobj = document.getElementById('<?= $divtohide ?>');
divobj.style.display = 'none';
}
</script>