Scriptaculous highlight effect on php print - php

I want this effect when php print gets called . How can i do it?
I have tried with
print "<span id=\"highlight\" onLoad=\"Effect.Highlight(highlight);\"><em>Your post was successfully added.</em></span>"."<hr>";
but this is not working. Help!

if it does not need to be in the php itself then use (advise against using short tags to open and close):
?>
<span id="highlight" onLoad="Effect.Highlight(this.id);"><em>Your post was successfully added.</em></span><hr>
<?php
and continue your script.
alternatively,
<head>
...
object.onload="SomeJavaScriptCode";
...
</head>
--EDIT--
Javascript would look like:
<script type="javascript/text">
body.onload=Effect.Highlight(getElemenyById('highlight'));
</script>
-- EDIT --
Javascript, I believe, (thanks to comments) will look like:
document.addEventListener('DOMContentLoaded', function () {
Effect.Highlight(getElemenyById('highlight'));
}, false);

onload=""
Does only work inside of a <body>, <frame>, <frameset>, iframe, <img>, <input type="image">, <link>, <script> or <style> Tag.

if you are using javascript why not print in your script section?
in your body you can have the notice hidden,
and after the post is added to the database you can show and highlight the alert.
are you using Ajax?
an example:
<span id="hightlight" style="display:none"><em>Your post was successfully added.</em></span>
<scrpt type="text/javascript">
<?php
print "$('highlight').show(); Effect.Highlight('highlight')";
?>
</script>

Related

Integrating JQuery into php file

I am trying to tweak a website so users will be able to swipe through the photo galleries on their mobile devices. I tried doing this by using JQuery. The website was not written by me, so I can't really explain the choices the previous programmer made regarding their code.
Currently, users can change pictures by clicking (tapping) on the current picture. The code for this is found in a php file called home.php. This is it:
<?php
...
$main_content .= "\n <div class='main_image'>
<a href='$next_slideURL' style='display:block'>
<img src='$root/$item_path/$slideFile' alt='$slideCaption from $projectTitle\n [xxxxxxxxxxxxx]' style='max-width:832px; max-height:500px' title='$projectTitle: $slideCaption. \nclick for next slide ($next_slideCaption). '></a>
</div>\n";
...
?>
To add swiping capabilities, I added the following code right after the one above:
echo "<script type='text/javascript'>";
echo "(function(){
$(\"div.main_image\").on(\"swipeleft\", swipeleftHandler);
$(\"div.main_image\").on(\"swiperight\", swiperightHandler);
function swipeleftHandler(event){
$.mobile.changePage(\"$next_slideURL\", {transition: \"slideleft\", changeHash: false});
}
function swiperightHandler(event){
$.mobile.changePage(\"$previous_slideURL\", {transition: \"slideright\", changeHash: false});
}
});";
echo "</script>";
While I'm not sure exactly why this isn't working, I have a few possible reasons (which might all be true unfortunately).
1) Since the div class='main_image' is done as a variable declaration, the JQuery line "div.main_image" doesn't have a reference (i.e. it doesn't know what main_image is). I'm not sure why the div is created as a variable declaration ($main_content keeps being added on throughout the php file, and in the end it's echoed along with a bunch of other variables).
2) I need to include the following code for JQuery but I have it in the wrong place:
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css">
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
right now I have it in the header section of index.html file. Is this wrong?
3) I've never used JQuery before, so any number of things might be wrong about the short script I wrote.
Sorry about the long post, I'm not sure how to explain this in a simpler way.
I'd appreciate it if anyone could help me either with this approach, or propose a different one.
Cheers!
Use $ while writting ready function
<?php
echo "$(function(){
// ---^--- use $ here
....
....";
echo "</script>";
?>
If $ conflicts then your can use jQuery like,
Full Code:
<?php
echo "<script type='text/javascript'>";
echo "jQuery(function(){
jQuery('div.main_image').on('swipeleft', swipeleftHandler);
jQuery('div.main_image').on('swiperight', swiperightHandler);
function swipeleftHandler(event){
$.mobile.changePage('".$next_slideURL."', {transition: 'slideleft', changeHash: false});
}
function swiperightHandler(event){
$.mobile.changePage('".$previous_slideURL."', {transition: 'slideright', changeHash: false});
}
});";
echo "</script>";
?>
Looks like you need to put your javascript in the $main_content variable, like the other code.
But to be honest you should seperate your javascript from the html/php.
Best way is to break out of php tags
and change this (function () to $(function ()
<?php
//php code
?>
<script type='text/javascript'>
$(function () {
$("div.main_image").on("swipeleft", swipeleftHandler);
$("div.main_image").on("swiperight", swiperightHandler);
function swipeleftHandler(event) {
$.mobile.changePage("$next_slideURL", {
transition: "slideleft",
changeHash: false
});
}
function swiperightHandler(event) {
$.mobile.changePage("$previous_slideURL", {
transition: "slideright",
changeHash: false
});
}
});
</script>;
<?php
//php code
?>

Jquery use php var and pause

My php page has at the top of the page before any jquery a php variable called $pause.
The value assigned to this is read from a database.
What I'm trying to do using jquery is show a div, then delay for the $pause value then hide the div.
This shows and hides the div, how do I add the delay ?
$("#div1").show();
$("#div1").hide();
Thanks
If you can parse php inside of your js, you can echo it:
var pause = <?php echo $pause; ?>
If not, attach the value to an element such as a hidden input so that you can access the value with jquery.
Then you could do:
$('#div1').show().delay(pause).hide(0);
Note: You need to pass the duration to hide() in order for delay() to work:
When a duration, a plain object, or a "complete" function is provided, .hide() becomes an animation method
Here's a fiddle
add $pause to a HTML Element...for example body:
<body data-pause="<?=$pause?>" >
</body>
and js:
$("#div1").show();
setTimeout(function () {
$("#div1").hide();
}, parseInt($('body').attr('data-pause'), 10));
If you would like to keep your javascript Inline write this at the end of your html before
<script>
$("#div1").show(0).delay(<?php echo $pause; ?>).hide(0);
</script>
if you don't want to keep your code inline you can add an attribute to your element and use that:
For example:
<div id="div1" delaytime="<?php echo $pause; ?>">Hello World</div>
And finally use the javascript below:
$("#div1").show(0).delay(jQuery(this).attr('data-pause')).hide(0);

Calling a javascript function by using onClick in a hyperlink

I have been looking online, but I have failed to find a direct answer to my question:
Can you use onClick for a tags?
In other words can you do this (note echoed through php)?
echo "\n";
I tried to run this, but when I click on the link, my counter function is not being called.
The rest of my code snippet:
echo "<script type=\"text/javascript\" src=\"src\jquery\jquery.js\">\n";
echo "function counter(){\n";
echo "alert(\"HELLO WORLD!\");\n";
echo "}\n";
echo "</script>\n";
echo "\n";
Although that should work, it's better practice not to bind events inline. I would suggest looking into addEventListener and for older versions of IE, attachEvent. More information on these can be found in a topic here: Correct usage of addEventListener() / attachEvent()?
If you wait for the window to be ready, you ensure that the element is on the page and defined for you to access it.
window.onload = function(){
//add any event listeners using the above methods in here
}
Example:
<script>
window.onload = function(){
var t = document.getElementById("test");
t.addEventListener("click", sayHi, false);
function sayHi(){
alert("Hi");
}
}
</script>
<div id="test">test</div>​
According to your above echo statements, if you are determined to make it work that way then you can try this:
echo "<script type='text/javascript' src='src/jquery/jquery.js'></script>\n";
echo "<script>\n"
echo "function counter(){\n";
echo "alert('HELLO WORLD!');\n";
echo "}\n";
echo "</script>\n";
echo "<a href='#' id ='loginbutton' onClick='counter()'></a>\n";
notice that I closed the script tag including jQuery and added a new opening tag right below it.
EDIT:
Script tags that reference external resources (via the src attribute)
are no longer able to execute script embedded within the tag itself.
Read more here
Made a little Demo code, Note that the function fires and then the href is followed. You can turn this off with JS by returning false.
<script type="text/javascript">
function counter() {
alert("do something here")
var FollowHref_Or_Not = false;
// true would simply follow the href after the function is activated
return FollowHref_Or_Not;
}
</script>
Test Link
To add more context to the comments above, here's a working example. Where I put the HTML comment about simulating an echo, just put your PHP echo line. Also note that I added a return false; This prevents the default link click behavior from executing. Since your href is "#" it would modify your URL to put "#" in the URL so if you used your browser back button you'd still be "stuck" on the same page.
http://jsfiddle.net/6pEbJ/
<html>
<head>
<script type="text/javascript">
function connect()
{
alert('connected!');
}
</script>
</head>
<body>
<!-- simulated echo result here -->
Testing
</body>
</html>

How to execute PHP code within JavaScript

<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>

Jquery error "u is undefined"

Why am I getting an error in Firebug "u is undefined"?
My page consists of a display of photos and photo gallery as a special separate section in the PHP code divided using the "break".
Photos and photo galleries are displayed using the "Fancybox.js".
The first time when I try to open a photo, everything works fine but when I do it again after I refresh the page the Firebug display error "u is undefined".
The Jquery for the menu that I'm using for display these separate part of the page:
$(document).ready(function(){
$(".menu_rfr").bind('click', function() {
$("#main").html('<img src="img/spin.gif" class="spin">');
location.replace($(this).attr('rel'));
});
$(".menu_clickable").bind('click', function() {
$("#main").html('<img src="img/spin.gif" class="spin">');
$("#main").load($(this).attr('rel'), function(event) {
});
$(".menu_clickable").unbind("click");
});
});
The simplified PHP code looks like:
<?
if (!isset($a)) $a = '';
switch($a)
{
case 1:
default:
?>
<div class="menu_clickable prof_link" id="prof_info" rel="?a=2">Photos</div>
<div class="menu_clickable prof_link" id="prof_info" rel="?a=3">Gallery</div>
<div id="main"></div>
<?
break;//photos
case 2:
?>
<script type="text/javascript">
$("a.group").fancybox({
'titlePosition' : 'over',
'overlayShow':false
});
</script>
<?
<img src="tmb/1.jpg" border="0">
<?
break;
case 3: // photo gallery
?>
<script type="text/javascript">
$("a.groupg").fancybox({
'titlePosition' : 'over',
'overlayShow':false
});
</script>
<?
<img src="tmb/2.jpg" border="0">
<?
break;
}
?>
As I said this is a simplified code, and probably there are some errors in it. I just wanted to show where and how I'm using Fancybox.
Is there a conflict between the jquery code for the menu at the top of the page and this for fancybox or there is some other reason why I keep getting an error in Firebug "u is undefined" after opening the other part of the PHP page and attempts to re-opening photos?
View your HTML source and make sure you don't have FancyBox declared twice. I just had the exact same error pop up in firebug and this is what I found in my source:
<script language="javascript" type="text/javascript" src="./ext_scripts/jquery.fancybox-1.3.1/fancybox/jquery.fancybox-1.3.1.pack.js"></script>
<link rel="stylesheet" href="./ext_scripts/jquery.fancybox-1.3.1/fancybox/jquery.fancybox-1.3.1.css" type="text/css" media="screen" />
<script language="javascript" type="text/javascript" src="./ext_scripts/jquery.fancybox-1.3.1/fancybox/jquery.fancybox-1.3.1.pack.js"></script>
Not sure exactly why it happened, but if you nest your include and require_onces in your PHP like I unfortunately did, you can wind up with some very funky Javascript references.
You probably have the fancybox.js script included twice which is causing the issue. Please check all your files and remove the the ones that are not required.
I have this same bug as well - I think it is due to the the 'loading' divs being reset by the cleanup code. I have a VERY nasty fix:
Change:
if ($("#fancybox-wrap").length) {
return;
To: (To skip the multiple-init check)
if (false && $("#fancybox-wrap").length) {
And add:
$.apzFancyboxInit = fancybox_init;
after 'fancybox_init = function() {'
What this does is allow us to call the initialisation routine multiple times; and saves the function pointer to this routine in a global variable. All we have to do now is make sure we call the $.apzFancyboxInit function every time a fancybox is closed. The best place to do this is in the onClosed function handler; so (in my case), my calls look like this:
$.fancybox(
{
'showCloseButton' : true,
'type' : 'ajax',
'onClosed' : function()
{
$.apzFancyboxInit();
},
If you are using a "ripped" template you may find that there are the fancybox generated div written in tho the html template right above the </body> tag.
check if your html output has a div with the id of fancybox-wrap if you have JavaScript disabled, and remove that.

Categories