php function on page load - php

I have 2 functions that makes menu links active/inactive:
function disableCtrl() {
echo 'style="background: #999999;" onclick="return false;"';
}
function enableCtrl() {
echo ' ';
}
I'm using them like this:
<li><a href="#" <?php if (#$_POST['submit']){disableCtrl();} if (#$_GET['guest'] == "add") {enableCtrl();} ?> >MenuButton</a></span></li>
The only problem I have is that menu links must be disabled by default (when the page is loaded).
When I tried to write <?php disableCtrl(); if (#$_POST['submit'])..., the button became perma-disabled.
Is there a way to make it work, maybe with JavaScript or something else?

you need to put the 'guest' check as if and the default(disabled)mode as else.
<li><a href="#" <?php if ($_GET['guest']== "add"){enableCtrl();} else {disableCtrl();} ?>>MenuButton</a></li>
Or with a ternairy (= short if/else-> [condition ? ifTrue : ifFalse] )
<li><a href="#" <?php $_GET['guest']=="add" ? enableCtrl() : disableCtrl() ?>>MenuButton</a></li>
In combination with disabled (which is made for this exact situation):
<li><a href="#" <?=($_GET['guest']=="add" ? 'disabled="disabled"' : '')?>>MenuButton</a></li>

If you want something to vary, say, with every load of a page, use a server-side technology such as php. If you want it to vary within one page load, I.e. in response to user interaction, use a client-side technology I.e. JavaScript.
To attempt to answer the original question, or at least give you some pointers, you want something a bit like:
<ul id="menu" style="display: none;"><li>...</li>...</ul>
<a id="btn" href="#">disable menu</a>
<script>
document.getElementById('btn').addEventListener('click', function() {
document.getElementById('menu').setAttribute('style', 'display: block');
}
</script>
That's not perfect (in practice, for one thing, you don't want to just point your link to "#" since that won't do anything for those with javascript disabled) but it's a pointer in the right direction. The jQuery equivalent would be something like:
<script>
$('#btn').click(function() { $('#menu').hide(); });</script>
</script>
if that's more appealing, check out jQuery.

Keep in mind that php is server side so you can use printf to put your javascript into your page.
printf("<script>Here is my javascript code</script>");
I do this a lot with the mapping services.
For example reading in locations from a database and making markers:
public function MarkerGoogle($s)
{
$str = sprintf("\r\n var amkr%d = new google.maps.Marker();\r\n", $s);
// More php code here …

Related

Dynamic CSS classes

My website has a simple navigation using a styled <ul> list, with the current page's link highlighted. Currently, I do this by giving the <a> object a CSS class like this:
<ul class="bd-nav">
<li>Home</li>
<li>Contact</li>
</ul>
with the corresponding CSS:
.bd-nav-active {
background-color: #563a64;
}
This works perfectly. However, I would like to build the website with PHP and have a seperate file for the header/navigation and then just <?php include ?> that file on every other page.
Is there a way to dynamically set the class of the navigation links, depending on which page you're on? What would be the best approach here?
Solved after some fiddling! I simply put the class attribute into a variable like this: (make sure to escape the quotation marks!)
<?php
$nav_active = "class=\"bd-nav-active\""
?>
Then used that variable in my navigation like this:
<ul class="bd-nav">
<li><a href="index.html" <?php if ($pid == 1) echo $nav_active; ?>>Home</a></li>
<li><a href="contact.html" <?php if ($pid == 2) echo $nav_active; ?>>Contact</a></li>
</ul>
And then on the respective pages, I simply set the $pid variable:
<?php $pid = 1; ?>
Works perfectly! Thanks for the helpful answers!
#Arrabidas92 had a nice way to automatically do this by getting the page URL, but I think I'll be doing it like this to have better control over how the navigation looks.
The menu needs to be dynamically generated and each page needs to have a unique id or something at the top of the page.
When you dynamically generate the menu, insert and if clause that will echo the active class if generated menu item is the same with current page.
I have not coded in php for some time now but i use to do something like this, in each page give a unique file name at the top. For example in the home page:
<?php
$file_name = "index.php";
?>
and then in the included file apply a logic like this:
<?php
if($file_name == "index.php"){
//Your navigation for the home page
}
else if($file_name == "about.php"){
//Your navigation for the about page
}
?>
Alright so I will give you some tips. First, to know on wihch page of your website you are you can use in PHP a superglobal called $SERVER with this attribute : $_SERVER['REQUEST_URI'].
By calling this, PHP is going to return the parts of the url after your domain.com. For example, if the current url was domain.com/home, echo will return only '/home'.
Then, you can place your logic about highlighting your links :
if($_SERVER['REQUEST_URI' == '/home') {
//Add active class to the link HOME
}...
You can try this one, but this is a Jquery, just put the CDN in your file.
$(document).ready(function(){
if(window.location.href === "index.php") {
$(".bd-nav").addClass("active-bgRed");
}
else if(window.location.href === "about.php") {
$(".bd-nav").addClass("active-bgBlue");
}
else if(window.location.href === "contact.php") {
$(".bd-nav").addClass("active-bgGreen");
}
});
// CSS
.active-bgRed{
background-color: red;
}
.active-bgBlue{
background-color: blue;
}
.active-bgGreen{
background-color: green;
}
// JQuery CDN
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

Send multiple dynamic arguments to jquery event functions

I want to send multiple arguments to JQUERY event functions.For sending one data i put it in value attr in html code.
<li id="<?php echo 'v'.$value['vehicleid'] ?>" value="<?php echo $value['vehicleid']; ?>" >
And get data in JQuery event function with $(this).val() But i don't know how can i pass multiple php data to JQuery event function!
these data are dynamic and produced by php code.
I came across something similar the other day.
Try using the html5 custom data attribute.
John Resig (the king of jquery and general javascript ninja) first posted about it here.
so:
<li id="vehicle<?php echo 'v'.$value['vehicleid'] ?>" data-vehicle="<?php echo $value['vehicleid']; ?>" >
Then access it using the jquery .data function. see http://api.jquery.com/data/.
If you have a lot of data you want to add I recommend using an object literal
{ vehicleId: <?php echo 'v'.$value['vehicleid'] ?>,
vehicleName: <?php echo 'v'.$value['vehicleName'] ?>}
as in the example on the jquery website.
You cannot use val() on an li it is supposed to be used on form elements like input for which there is a valid attribute called value
For an li you can use data attributes
<li id="<?php echo 'v'.$value['vehicleid'] ?>" data-vehicleid="<?php echo $value['vehicleid']; ?>" >
and use:
var vehicleId = $(this).data('vehicleid');
For passing multiple data you can seperate each id with some char like "-":
<li id="<?php echo 'v'.$value['vehicleid'] ?>" data-vehicleids="<?php echo $value['vehicleid1']. '-' .$value['vehicleid2']; ?>" >
which should produce something like:
<li id="1234" data-vehicleids="1234-3456-5678" >
then do
var vehicleIdsArray = $(this).data('vehicleids').split('-');
just make sure charachter used for seperation is not used for vehicle ids
This should help you:
<ul id="list">
<li data-vehicleid="1234" data-vehiclename="renault" data-vehicle-color="silver">Renault</li>
</ul>
$(document).ready(function(){
$('ul#list li').click(function(e){
var vehicleId = $(this).attr('vehicleid');
var vehicleName = $(this).attr('vehiclename');
var vehicleColor = $(this).attr('vehiclecolor');
return false;
});
});
Quote from Resig:
I think what is most enticing about this whole specification is that
you don't have to wait for any browser to implement anything in order
to begin using it. By starting to use data- prefixes on your HTML
metadata today you'll be safe in knowing that it'll continue to work
well into the future. The time at which the HTML 5 validator is
integrated into the full W3C validator your site will already be
compliant (assuming, of course, you're already valid HTML 5 and using
the HTML 5 Doctype).
I am not one hundred percent sure which kind of event are you pertaining to. But you can pass multiple arguments inside the function(..HERE..). It should be separated by commas. Its like this.
$('selector').change(function(arg1,arg2,arg3){
alert(arg1+arg2+arg3);
});
In this example i am using change event for the selector 'selector'.
I think you have to create a function to handle the event
function handleEvent(data-vehicleid,data-vehiclename,data-vehiclename)
{
alert(data-vehicleid + data-vehiclename + data-vehiclename);
}
Then on your li,
<li onmouseover="handleEvent(<?php echo $variable1;?>,<?php echo $variable2;?>,<?php echo $variable3;?>)">Renault</li>

Adding classes with PHP echo, not replacing them

First of all, I know this is simple but I'm not a PHP developer by trade so I apologize if this is dumb for everyone. That being said, I've spent the last 3 hrs searching and can't find a way to do this without re-inventing my wheel so to speak. I use a simple command to mark the navigation on websites when the page is "current".
<li><a <?php if (strpos($_SERVER['PHP_SELF'], 'page')) echo 'class="current"';?> href="page.php" class="tp">Page</a></li>
Works great in most cases. However in this case, I need to concatenate the class string, not overwrite it with current. I've tried
...echo'class=" "."current".'
and several variations and can't get it to simply add the class not overwrite it. Thank you
Is the <li> not in a loop?
Ideally your menu would come from a table array through which you would loop. If that is the case; try this:
foreach(..){
$class = strpos($_SERVER['PHP_SELF'], 'page') ? " current" : "";
echo "<li>Page</li>";
}
Overall, for readability, I would recommend to not put if statements inline in the HTML.
But based on your code:
<?php
$class = strpos($_SERVER['PHP_SELF'], 'page') ? " current" : "";
?>
<li>Page</li>
What about something like this :
<li>
<a href="page.php"
class="<?php if (strpos($_SERVER['PHP_SELF'], 'page')) {echo 'current ';} ?>tp">
Page
</a>
</li>
This way, you'll always have at least class="tp", and, if the condition is met, a 'current ' (note the space at the end of this string : it's important and required so the two classes are separated by a space and not considered as one) will be inserted just before the 'tp', inside the class="..."

Go Link thru iFrame

I have problem and I tried click link then it doesn't work to open link using target: name of iFrame. i dont want use href because im going make show/hide div.
Javascript:
<script type="text/javascript">
<!--//
function godirect(url, targetname)
{
document.getElementById(targetname).src = url;
//frame[targetname].location.href = url;
}
//-->
</script>
in HTML and PHP:
$a=0;
echo 'Click Me!';
echo '<iframe class="iframe_url" id="iframe_url'.$a.'"></iframe>';
How about
<script type="text/javascript">
function godirect(url, targetname) {
window.frames[targetname].location = url;
//OR
//window.open(url,targetname);
return false;
}
</script>
<?PHP
$a=0;
?>
Click Me!
<iframe class="iframe_url" name="iframe_url<? echo $a; ?>" id="iframe_url<? echo $a; ?>"></iframe>
You have to quote strings in JavaScript. You are trying to get the id of the element by passing in a variable which you haven't defined.
You are also using the same quote characters to delimit your HTML attribute value as you are using to delimit your JS strings.
To use the approach you are using, while making the minimum number of fixes to make it work:
echo 'Click Me!';
Using JS for this is a very silly idea in the first place though, and your implementation fails to have any kind of fallback for when JS is not available (which is odd, since you are taking steps to stop browsers which don't recognise the script element from rendering the JS as content text).
You can do this with plain HTML:
<a href="http://www.google.com"
target="iframe_url<?php echo htmlspecialchars($a); ?>">
Click Me!
</a>
i dont want use href because im going make show/hide div.
You can do that as well as having a normal, functioning link. Build on things that work.
Try this:
echo 'Click Me!';
echo '<iframe class=\"iframe_url\" id=\"iframe_url'.$a.'\"></iframe>';

jquery - find last element with a certain class and pass it to php?

Basically, I have a list:
<li class="list">fruit</li>
<li class="list">vegetables</li>
<li class="list">protein</li>
And, I want to find the last list item, get the text from it, and then assign it to a php variable, so that:
<?php
$variable = 'protein';
?>
I'm fuzzy on how to get it into a php variable?
The JavaScript / jQuery Side:
$.post("script.php", { value: $(".list:last").text() }, function (result) {
alert(result); // alerts whatever comes from the php script
});
The PHP Side
print strtoupper( $_POST["value"] );
There is a fundamental difference between Javascript and PHP: PHP runs on the server side, and produces the page's code. JavaScript runs on the client side, after PHP has run and served the content. So you can't pass something "back" from JQuery to PHP. You would have to make an AJAX call to do that. More on how to do that with JQuery here.
But what you're trying to do sounds easy enough to achieve in JQuery alone. Why the PHP?
$.post("script.php", { value: $(".list:last-child").text() }, function(result){
// Your Code
});
if the php is creating all the html, then each time you are printing the list item you could set a variable to the content.
<li class="list"><?PHP echo $var; ?></li><?PHP $yourvar = $var; ?>
<li class="list"><?PHP echo $var; ?></li><?PHP $yourvar = $var; ?>
<li class="list"><?PHP echo $var; ?></li><?PHP $yourvar = $var; ?>
Once the list is finished you will have the last content in a variable.
If you are returning the results from a database then a little more efficient would be finding out how many rows you have returned. then testing that number with the number of the row you are on as you loop through it. You will be able to find the last row then too

Categories