in PHP we can put HTML between codes like this:
<?php
if (condition) {
?>
<p>True</p>
<?php
} else {
?>
<p>True</p>
<?php
}
?>
can we do this in javascript ? like this ?
<script language='JavaScript'>
if (condition) {
</script>
<p>True</p>
<script language='JavaScript'>
} else {
</script>
<p>True</p>
<script language='JavaScript'>
}
</script>
There's something like this that has the effect you posted (maybe not your intention though, it's hard to say), but I wouldn't do it.
<script type="text/javascript"> //language == deprecated!
if (condition) {
document.write('<p>True<\/p>');
} else {
document.write('<p>True<\/p>'); //maybe False here?
}
</script>
But again this is just a demonstration of the effect, try to avoid document.write (it' a blocking operation) whenever possible.
Update: Edited based on comments below to make this example you shouldn't use! valid, but you shouldn't be copy/pasting it in the first place...
No. Browsers will output things in order that it sees them, without considering any conditions of other media on the page.
This works in PHP because the PHP interpreter interprets your code before sending the output to the client browser window. In other words, the actual HTML document being sent to the client is parsed and computed before being sent to the requesting browser. With Javascript mostly being a client-side scripting language this method is not possible, since you already have your HTML document generated from a server-side language such as PHP. You can manipulate the document in other ways using Javascript, with technologies such as Ajax and the DOM.
not that i know of, but for php do this instead
<?php if (condition): ?>
<p>True</p>
<?php else: ?>
<p>False</p>
<?php endif; ?>
=)
Related
I have a javascript widget, but the widget should only be seen by logged in users.
<script>
window.fwSettings={
'widget_id':77000003788
};
!function(){if("function"!=typeof window.FreshworksWidget){var n=function(){n.q.push(arguments)};n.q=[],window.FreshworksWidget=n}}()
</script>
<script type='text/javascript' src='https://euc-widget.freshworks.com/widgets/77000003788.js' async defer></script>
I have tried to use a php function, but it didnt work:
<?php
if(is_user_logged_in()) {
echo '<script>
window.fwSettings={
'widget_id':77000003788
};
!function(){if("function"!=typeof window.FreshworksWidget){var n=function(){n.q.push(arguments)};n.q=[],window.FreshworksWidget=n}}()
</script>
<script type='text/javascript' src='https://euc-widget.freshworks.com/widgets/77000003788.js' async defer></script>';
}
?>
I placed the code in my footer.php file right before the body-closing tag as the widget should be placed there.
Any help is appreciated! (and yes, I'm very new to coding)
Your code has a quoting problem. You are starting a string with a single quote, ', but then you including additional single quotes inside the string. Make sure to turn on both WordPress and PHP error reporting when debugging, it will warn you about this. The easiest solution is to break out of PHP and switch back to HTML mode.
<?php if(is_user_logged_in()): ?>
<script>
window.fwSettings={
'widget_id':77000003788
};
!function(){if("function"!=typeof window.FreshworksWidget){var n=function(){n.q.push(arguments)};n.q=[],window.FreshworksWidget=n}}()
</script>
<script type='text/javascript' src='https://euc-widget.freshworks.com/widgets/77000003788.js' async defer></script>
<?php endif; ?>
Let's say I have:
<body class="hello">
How can we do something like the following?
if($("body").hasClass("hello")) {
<script src="/demo_js/ion.rangeSlider.min.js"></script>
}
I was wondering if maybe doing something like:
if($("body").hasClass("hello")) {
document.write('<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></'+'script>');
}
That looks fine but it's a mixup of jQuery and JS and I am not sure if that's the correct way anyway.
It'd be even better if this could be done via the backend in php but I am not sure how to check if an element has a class in php neither how to tell it to include a script if it does.
How would you approach it?
One trick in php I thought is the following but then again, is there any better way?
<?php
$hello = "hello";
if($hello) { ?>
<script...
<?php } ?>
<body class="<?php echo $hello; ?>">
The jQuery function for this is $.getScript.
https://api.jquery.com/jQuery.getScript/
$.getScript( "/demo_js/ion.rangeSlider.min.js" )
Something like the below does not work:
<?php $nojs = false; ?>
<noscript>
<?php $nojs = true; ?>
</noscript>
As the PHP is executed regardless if JS is enabled or not. But is there a way to get a similar effect? I'm trying to set a flag if JS is disabled and then display parts of the page accordingly.
PHP is executed before javascript, so you cannot do this. You can do something such as executing a basic ajax request and storing hasjs in a session variable once the ajax page is successfully queried. You wouldn't know if it's just the fact that the ajax request wasn't successful due to something else, or if they have Javascript disabled.
Lets give this a shot anyway:
The jquery script in your head tags
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$( document ).ready(function() {
$.get( "hasjs.php", { hasjs: "1"} );
});
</script>
The PHP file (hasjs.php)
<?php
if(isset($_GET['hasjs']))
{
session_start();
$_SESSION['hasjs'] = 1;
}
?>
Then you can access the session variable to determine if they have JS based off the ajax query. Nothing stopping the user from visiting that page though if they don't have JS installed.
I am trying to include some JavaScript to just one single page of a WordPress based website. Basically, what I've done is in the header.php of the theme, I've put the following:
<?php if( is_page('17')) { ?>
<!--Start of Zopim Live Chat Script-->
<script type="text/javascript">
window.$zopim||(function(d,s){var z=$zopim=function(c){z._.push(c)},$=z.s=
d.createElement(s),e=d.getElementsByTagName(s)[0];z.set=function(o){z.set.
_.push(o)};z._=[];z.set._=[];$.async=!0;$.setAttribute("charset","utf-8");
$.src="//v2.zopim.com/?2pL2gooCVnWNWjh0QB7IVqRgAiarsW4o";z.t=+new Date;$.
type="text/javascript";e.parentNode.insertBefore($,e)})(document,"script");
</script>
<!--End of Zopim Live Chat Script-->
<?php }
<?php endif; ?>
When I add this, it breaks the entire site, nothing loads anywhere. I've tried it with and without the
<?php endif; ?>
at the end, thinking that it may be duplicating with the
<?php }
I actually have two different conditional statements I need to add, each for a different page. I don't want to use the plugin that allows PHP & JavaScript in the pages themselves for security reasons, which is what I used to use.
Can anyone tell me what I'm doing wrong, and/or how to add this particular JavaScript to only page #17 (which I'm guessing will also show me how to add a PHP statement and link to single-use stylesheet that I need on a different page)?
It's hard to give a definite answer without seeing the rest of the page code but in my opinion you don't need the <?php endif; ?>.
Simply replace
<?php }
<?php endif; ?>
with
<?php } ?>
and it should work.
I know there are a lot of questions covering something similar, but I've tried the answers without any luck.
Snippet of PHP:
$usernum_query = "SELECT numPersonID FROM tbllogins WHERE txtUserName='$currentuser'";
if(!$usernumber = $db1->query($usernum_query)){
die('There was an error running the usernumber query [' . $db1->error . ']');
}
while($row = $usernumber -> fetch_assoc()) {
$userIDnum = $row['numPersonID'];
$userIDnum = utf8_encode($userIDnum);
}
Snippet of Javascript:
$(function(){
$("#0").click(function(){
var userIDnum = <?php echo json_encode($userIDnum); ?>;
alert(userIDnum);
The most common answer I've come across says to UTF_encode my variable, which I think I've done correctly. I've also tried:
var userIDnum = <?php echo $userIDnum; ?>;
Which doesn't work.
In my HTML outside of the script,
<?php echo json_encode($userIDnum); ?>
return "90" (with the quotes)
<?php echo $userIDnum; ?>
returns 90 (without the quotes).
Within the script, I get null and no alert box, respectively.
Any ideas as to why the variable isn't passed into the script? Thanks!
edit: tried with quotes and got the same result
[Taken from comments as requested]
If I can make a recommendation, put your value in a data-attribute in the HTML (e.g. <body data-user-id="<?php echo $userId ?>">. This keeps you from mixing code languages together which is hard to read, and would allow your external script to run correctly without making it a PHP page.
As far as IE9, I'll take a quick look. You might want to see how jQuery manages the data attributes. You should, at the least, have access to
domObject.getAttribute('data-user-id').
Yep, just did a quick lookup, and even IE10 doesn't support the dataset feature. So, you'll need to use getAttribute for IE <= 10.
A solution based on a suggestion by calamari:
In the HTML:
<!DOCTYPE html>
<!--[if lt IE 11 ]> <html class="ie10orless"> <![endif]-->
<head>
... more code here ...
And in the script:
var oldIE;
if ($('html').is('.ie10orless')) {
oldIE = true;
}
if (oldIE) {
var x = document.getElementsByTagName("div")[0].getAttribute("data-number");
alert("in IE");
alert(x);
} else {
var userinfo = document.querySelector('#user');
alert("NOT in IE");
alert(userinfo.dataset.number);
}
Hope this helps someone else. Thanks everyone for the other suggestions as well.
There are couple of things to check. Lets say this is your script:
<?php $htmlString= 'testing'; //Lets say this is a snippet of your php
?>
<html>
<body>
<script type="text/javascript"><!-- And this is the snippet of your JS -->
// notice the quotes around the ?php tag
var htmlString="<?php echo $htmlString; ?>"; //Make sure there's double
//quotes around your php
alert(htmlString);
</script>
</body>
</html>
Make sure you have PHP and JS in a file called .php. If its an external .js file, php inside it will not work (you can rename the JS file to a .php extension if you have it set up that way)
Also make sure you have the html, php and js setup the way above. There has to be double quotes around php, for example:
var userIDnum = <?php echo json_encode($userIDnum); ?>;
change this to below:
var userIDnum = "<?php echo json_encode($userIDnum); ?>";