Add margin-left, script inside php - javascript

The problem is. I want to inset margin-left: 20%; to maincontent, when the user is logged in.
No i dont have a problem with syntax, i can get it done in js, but im told to use php.
So i also added a class in css and to my body.
<?php
if ($_SESSION['username']){
include("/view/leftmenu.php");
}
?>
How do i activate css in php?

As revealed by the syntax highlighting, you're trying to put a single quote inside a single-quoted string.
Your options are:
Escape the single quotes with \'.
Use double quotes instead.
Use ?> ... <?php instead of echo.
Don't do this with JavaScript at all! You control the server side; why not just add a class to the body like logged-in, and have a CSS rule like body.logged-in #maincontent { margin-left: 20%; }?
(For what it's worth your JavaScript is invalid too; you need to quote the 20%. Percentages aren't legal JS.)

Put your JavaScript in double quotes, with single quotes inside. You may want to run your include first as well. include does not need (). Your code could look more like:
<?php
session_start(); // has to be run before any headers are sent
if(isset($_SESSION['username'])){
include '/view/leftmenu.php';
echo "<script type='text/javascript'>$('#maincontent').css('margin-left', '20%');</script>";
}
?>
The better solution however would look more like:
<?php
session_start(); $marginLeft = '0'; // $marginLeft should be your default
if(isset($_SESSION['username'])){
$marginLeft = '20%';
include '/view/leftmenu.php';
}
echo "<!DOCTYPE html><html><head><style type='text/css'>".
"#maincontent{margin-left:$marginLeft;}</style></head><body>".
"<div id='maincontent'>content</div></body></html>";
?>
A better approach yet, would look like:
<?php
session_start(); $className = 'withoutMargin'; // $marginLeft should be your default
if(isset($_SESSION['username'])){
$className = 'withMargin';
include '/view/leftmenu.php';
}
?>
<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
.withoutMargin{
margin-left:0;
}
.withMargin{
margin-left:20%;
}
</style>
</head>
<body>
<?php echo " <div class='$className'>"; ?>
<!-- your content here -->
</div>
</body>
</html>
Note: Your code above does not have to look exactly like this. This just illustrates concept. You would have more code testing for submit to be set and so forth. Also, with the second example, which I recommend, I would use external CSS, so it is cached by the user's Browser.

20% needs to be in quotes:
$('#maincontent').css('margin-left', '20%');
This also applies to px, em, pt, and any other form of CSS unit of measurement.

Related

Adding header script to an html page using php "required" from a different page

I have a template.html page that has a header <>and body <>. By default the html header doesnt have anything in it. However, from a php page, i would like to require the html page and add script to the header of the html page. The following is an example.
<<<.?php
/require("index.html");
echo "
<header>
<script>
</script>
</header>
";
?.>>>>
This would probably be the easiest way. Change your include file to include string. If that string is defined, include it in the header.
<php
$script = "<script src='myfile'></script>";
include("header.php");
?>
PHP Include File
<html>
<head>
...
// if $script is defined, include it
<?php if( isset($script) ){ echo $script; } ?>
</head>

Passing a PHP variable into Javascript returns NULL

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); ?>";

Facing trouble to insert php variable in javascript code

I'm trying to insert php variable in a javascript code but unable to get the result. Code is:
<?php $twitterusername = get_option_tree( 'twitter_name', '', 'true' );?>
<script type="text/javascript">document.write(unescape("%3Cscript src='http://twitterforweb.com/twitterbox.js?username=$twitterusername&settings=0,1,2,248,279,ffffff,0,c4c4c4,101010,1,1,336699' type='text/javascript'%3E%3C/script%3E"));</script>
Actually my text editor is not marking $twitterusename inside the script as valid php code. Please help me out.
Try this:
<script type="text/javascript">document.write(unescape("%3Cscript src='http://twitterforweb.com/twitterbox.js?username=<?php echo $twitterusername;?>settings=0,1,2,248,279,ffffff,0,c4c4c4,101010,1,1,336699' type='text/javascript'%3E%3C/script%3E"));</script>
As it's a PHP variable, you need to echo it out with PHP, not javascript.
So you need to replace
$twitterusername
with
<?php echo $twitterusername; ?>
Even though it's inside the <script> tags, it's going to echo out whatever $twitterusername is as long as it's in PHP tags.
If your server supports shortcode, you could use
<?=$twitterusername;?>
making it slightly shorter.
<script type="text/javascript">document.write(unescape("%3Cscript src='http://twitterforweb.com/twitterbox.js?username=<?=$twitterusername;?>settings=0,1,2,248,279,ffffff,0,c4c4c4,101010,1,1,336699' type='text/javascript'%3E%3C/script%3E"));</script>
It is not valid php code, you need to mark it as so using <?php echo $twitterusername; ?>.
Your final code would look like:
<?php $twitterusername = get_option_tree( 'twitter_name', '', 'true' );?>
<script type="text/javascript">document.write(unescape("%3Cscript src='http://twitterforweb.com/twitterbox.js?username=<?php echo $twitterusername; ?>&settings=0,1,2,248,279,ffffff,0,c4c4c4,101010,1,1,336699' type='text/javascript'%3E%3C/script%3E"));</script>
You need to use php tags (<? ?>) to insert variable.
<script type="text/javascript">document.write(unescape("%3Cscript src='http://twitterforweb.com/twitterbox.js?username=<?=$twitterusername?>&settings=0,1,2,248,279,ffffff,0,c4c4c4,101010,1,1,336699' type='text/javascript'%3E%3C/script%3E"));</script>
It's because you are using your PHP variable outside PHP tags.

Strategy for moving javascript to the bottom in CodeIgniter?

On my site I have one global Javascript file which includes jQuery and code for the drop down menu among other things. Many pages also have custom Javascript for minor page-specific interactions, tables etc.
My current set up on each view is a header.php file, basically covering everything from the doctype through to start of the content, the view file for the specific page, and a footer.php closing out the page.
Currently global.js is linked from the <head>. For performance we should put JS at the very bottom of the page, but I can't figure out a good way to do this. I could add the full script line for global.js with the custom script block, but that means I must add it on every page, even when there is no other Javascript. Any better way to move the JS right to the bottom?
You could put the custom JS in a regular variable or nowdoc (php 5.3.0+), and then echo the variable along with script tags in the footer if it exists. Nowdoc might be preferable because you can use both double quotes and single quotes in your JS and PHP won't parse/escape the text.
someview.php:
<?php
$custom_js = "
alert('custom js ran');
";
?>
<?php
$custom_js = <<<'CUSTOM_JS'
alert("custom js ran (i'm in a nowdoc!)");
CUSTOM_JS;
?>
footer.php:
<?php if(isset($custom_js)) { ?>
<script><?php echo $custom_js; ?></script>
<?php } ?>
Edit 2:
If you don't want to have the javascript in a string, you could have the javascript in a seperate file and then use PHP's file_get_contents() to load it into the $custom_js variable as a string.
Edit:
This is just an aside, but you might look into using the Carabiner library for loading JS and CSS. It's an excellent library. It might not necessarily help with your current problem, but if your global.js is quite large, you could split it up and use Carabiner to compress/concatenate on load. I currently use it to select which JS and CSS gets loaded for logged in and logged out users on my current CI project.
Carabiner on Github
Carabiner on Sparks
Carabiner documentation
Perhaps I missed something - but why cant you just load another view, which only contains the js code?
Your template:
$this->load->view("header.php");
$this->load->view("content.php", $data);
$this->load->view("footer.php", $load_js);
Then inside footer.php:
// start of footer stuff here
$this->load->view($load_js);
</body>
</html>
Then inside page1.php:
<script>
// Your scripts here
</script>
OR:
Your template:
$this->load->view("header.php");
$this->load->view("content.php", $data);
Then inside each "content.php" file:
// Content goes here
$data['load_js'] = "page1.php";
$this->load->view("footer.php", $data);
Then inside single "footer.php" file:
// start of footer stuff here
$this->load->view($load_js);
</body>
</html>
Then inside page1.php:
<script>
// Your scripts here
</script>
The second method is probably more what you want. It does mean you need to call the footer in each content file - but it is literally one line - so your not really repeating yourself - but it gives you complete control inside the content file to specifically any js files to load.
You can expand this an make the $load_js variable an array of js files to load.
I use a set of layouts, which are views that provide the basic structure of the site. Every controller calls a layout and passes into it the content specific for that controller method.
For example, say you have a single layout:
<html>
<head>
<title><?php echo $page->title ?></title>
<?php if (count($page->css)): ?>
<?php for ($i=0; $i < count($page->css); $i++): ?>
<link rel="stylesheet" href="<?php echo $page->css[$i] ?>"/>
<?php endfor; ?>
<?php endif; ?>
</head>
<body>
<?php $this->load->view('header.php'); ?>
<?php $this->load->view($content); ?>
<?php $this->load->view('footer.php'); ?>
<?php if (count($page->js)): ?>
<?php for ($i=0; $i < count($page->js); $i++): ?>
<script src="<?php echo $page->js[$i] ?>"></script>
<?php endfor; ?>
<?php endif; ?>
</body>
</html>
Each page passes in a $page object that contains an array of css and js files. For files that are global, like global.js, you can just hardcode that in at the bottom (same with global CSS at the top). Or, you can set a parent controller that all controllers inherit from. This way you can set up the $page object with default settings (including adding global.js). Then, each controller/method can remove global.js if it's not needed.
Each page also passes in a $content variable with the location of the main view for the page.
You can extend this even further by having multiple layouts and moving some of the HTML into the layout (e.g. 1 column, 2 column, 3 column layouts). In those cases, you may pass in multiple view locations for each column, etc. It's really up to you.
Of course, to keep all JS at the bottom you'd need to move all your page-specific custom JS into JS files. That's actually the best way to go, considering external JS can be cached.
Make a helper function; and load a view where you include that global.js script. Anytime you need global.js to be located at the bottom of the page, just call that helper function.
Another option is to use a template library.
I use this one by Williams Concepts.
It allows you to add JS (and CSS for that matter) for individual class/method calls.
For example:
class foo exends Controller {
public function bar() {
$this->template->add_js('js/jquery.js');
$this->template->add_js('alert("Hello!");', 'embed');
$data = $this->some_model->get_data();
$this->template->write_view('content', 'user/profile', $data;
$this->template->render();
}
}
Using this you can either add the JS as and when required, or add it into the template for the site.
In your case, I would either add the global.js in the footer of the template or define a region in the footer of the template when you can add any JS required.
Controller / add function
public function add()
{
$data['page_title'] = 'Test | Add Details';
$data['js'] = array('details','details2');
$this->load->view('template/header',$data);
$this->load->view('details/add');
$this->load->view('template/footer',$data);
}
in your footer template load all the common scripts that are needed, like jquery.min.js, bootstrap.min.js and so on. later add the below code
footer
<!-- Jquery Core Js -->
<script src="<?= base_url() ?>assets/plugins/jquery/jquery.min.js"></script>
<!-- Bootstrap Core Js -->
<script src="<?= base_url() ?>assets/plugins/bootstrap/js/bootstrap.js"></script>
<?php
if(isset($js) && count($js) > 0)
{
for($i=0;$i<count($js);$i++)
{
?>
<script src="<?= base_url() ?>assets/js/custom/<?= $js[$i] ?>.js"></script>
<?php
}
}
?>
</body>
</html>
pass all the js files to be loaded in the array.
If you have a footer.php file that's included on everypage, why can't you just put your js code in that file?

how move javascript to bottom footer in drupal

for performance issue in drupal
how move javascript to bottom footer in tpl file??
In your theme's page.tpl.php, move the print $scripts; line to the footer. Some modules' JS code doesn't like this, but I've had it work with most.
http://groups.drupal.org/node/8399
I just answered a similar question on Drupal Answers: https://drupal.stackexchange.com/questions/46202/move-aggregated-js-file-to-the-footer/89590#89590
I'm copy pasting the answer below for quick reference.
Also, I'm not sure if the question should be migrated to Drupal Answers or merged or else so if anyone has an idea please execute this or advise on how to do it. Thanks.
Found this excellent code snippet for Drupal 7: https://gist.github.com/pascalduez/1418121
It offers a way to have $script and $head_scripts so that you can specify which JS files need to go in the head. Example, Modernizr should go into the head scripts.
I'm copy pasting below the solution in the link to future proof the answer.
Cheers.
html.tpl.php
<!DOCTYPE html>
<html<?php print $html_attributes; ?>>
<head>
<?php print $head; ?>
<title><?php print $head_title; ?></title>
<?php print $styles; ?>
<?php print $head_scripts; ?>
</head>
<body<?php print $body_attributes;?>>
<?php print $page_top; ?>
<?php print $page; ?>
<?php print $scripts; ?>
<?php print $page_bottom; ?>
</body>
</html>
template.php
// Used in conjunction with https://gist.github.com/1417914
/**
* Implements hook_preprocess_html().
*/
function THEMENAME_preprocess_html(&$vars) {
// Move JS files "$scripts" to page bottom for perfs/logic.
// Add JS files that *needs* to be loaded in the head in a new "$head_scripts" scope.
// For instance the Modernizr lib.
$path = drupal_get_path('theme', 'THEMENAME');
drupal_add_js($path . '/js/modernizr.min.js', array('scope' => 'head_scripts', 'weight' => -1, 'preprocess' => FALSE));
}
/**
* Implements hook_process_html().
*/
function THEMENAME_process_html(&$vars) {
$vars['head_scripts'] = drupal_get_js('head_scripts');
}
The fastest way to move all Drupal's JS to the footer is by moving $scripts just before the closing body tag AND before $closure.
Within the Drupal 6 core there is no option oder interface which you can easily check. But under admin/settings/performance there are an option to compress JS Files. Recommended for production use.
To put your JS Files to the bottom go to your page.tpl.php file and look for <?php print $scripts;?> or something similar. Then look for $closure; and change it:
<!-- other theme code above -->
<?php print $scripts; ?>
<?php print $closure; ?>
</body>
</html>
I think this should move over to https://drupal.stackexchange.com/questions/3171/add-javascript-at-the-bottom-of-a-page/101025#101025
Where there is a duplicate discussion.
I've found that moving print $scripts at the bottom rarely works. Most of the time, you would need a solution that allows to keep some of the scripts in the header, whilst others can be moved in the footer.
Personally, I use drupal_add_js in template.php taking advantage of the scope option.
From Drupal docs:
scope: The location in which you want to place the script.Possible values are 'header' or 'footer'.If your theme implements different regions, you can also use these.Defaults to 'header'.

Categories