Integrating JQuery into php file - php

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

Related

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>

executing jquery code from php

$("#bt-potrdi").click( function(e) {
e.stopPropagation();
$("#belina").css({"z-index":200}); $("body").addClass("ext");
$("#vpisok_frame").css({"z-index":250}).fadeIn(200);
});
when i click on button this jquery code is executed and works fine. Can i execute this code without click event?
I want to execute this code from php when some data is executed successfully like for example
if ($ok) {
?>
//execude ajax code
e.stopPropagation();
$("#belina").css({"z-index":200}); $("body").addClass("ext");
$("#vpisok_frame").css({"z-index":250}).fadeIn(200);
<?php
}
is this possible? PHP is server side code so i didn't find any good example if this is possible
Similar to the other suggestions, but this doesn't rely on having 2 copies of the same code...
if ($ok) {
?>
<script type="text/javascript">
$(function() {
$("#bt-potrdi").trigger("click");
});
</script>
<?php
If you ever change the click event handler, this will still work. This means that you won't need to make any future changes in 2 places.
If I understand the question, you want to execute some javascript on page load if $ok is true. To do that, you should be able to do something like:
if ($ok) {
?>
<script type="text/javascript">
//execute ajax code
$("#belina").css({"z-index":200}); $("body").addClass("ext");
$("#vpisok_frame").css({"z-index":250}).fadeIn(200);
</script>
<?php
}
EDIT: Also, e.stopPropagation(); is not going to work because e is not defined anywhere.
What happens is when your PHP script is executed, if $ok evaluates to true, then your jquery code is included in the generated document, and is omitted if it doesn't. But at this point, there is no event, so the following line will not work.
e.stopPropagation();
However, as jdwire suggested, you can wrap your javascript in a script tag, and have it executed that way, without being triggered by an event. So... like this:
<?php
if ($ok) {
?>
<script type="text/javascript">
$("#belina").css({"z-index":200}); $("body").addClass("ext");
$("#vpisok_frame").css({"z-index":250}).fadeIn(200);
</script>
<?php
}
?>
I would design my code so that i could add classes and set z-indexes straight up when html is rendered, but if you want to do those with jquery, jsut wrap them in <script> and $(document).ready(function({}); so they will be executed when dom is ready.
eg.
if ($ok) {
?>
//execude ajax code
<script>
$(document).ready(function{
$("#belina").css({"z-index":200}); $("body").addClass("ext");
$("#vpisok_frame").css({"z-index":250}).fadeIn(200);
});
</Script>
<?php
}
edit
Okay i assumed e.stopPropagation(); is set somewhere before since it was in questions example aswell. removed it for now.
You can echo out the code in <script/> tags and it will be run as JavaScript, or with the code you have, just place it between tags and it should be fine :)
But you cannot do this "live". Only when the page is requested ONCE.
You can also do it this way to pass PHP variables over to javaScript. I think it's a lot cleaner.
$check = 1;
?>
...
<script type="text/javascript">
var check = <?= $check; ?>;
...
if (check)
{
$("#bt-potrdi").trigger("click");
}

Jquery Hide Function in PHP

I have a while statement that is echoing about 10 different stories. Every story has a user comment. When clicking the button edit I want one of the functions to hide the user comment. Here is the code I wrote to try and make it happen. Let me know if you think of why this wouldn't work.
<script>
$(".edit_<?php echo $story_id ?>").click(function () {
$(".comment_<?php echo $story_id ?>").hide("fast");
});
</script>
<?php
if (!empty($user_comment))
echo "
<p class='user_comment comment_$story_id'><strong>$user_comment</strong> <a class='edit_story_comment edit_$story_id'>Edit</a></p>";
else
echo "<p id='user_comment_$story_id'><span id='edit_no_story_comment'>Edit</span></p>";
?>
so im gonna ges its becuse of the ankertag is being defined after you are
hocking upp the event with jquery
use jquerys on load event to get around this
$(function() {
$(".edit_<?php echo $story_id ?>").click(function () {
$(".comment_<?php echo $story_id ?>").hide("fast");
});
});
hope this help
(mixing php html and jquery and string concatenation is beautiful btw :D)

Help with jquery tabs

I need to know how to link (via a regular href anchor on a different page) to content that is inside a tab that is not the default tab. Can this be done? My code will explain hopefully what I require:
My Code:
The following is my profile_edit.php page:
The javascript:
<script src="Javascript/jquery-1.4.js" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8">
$(function () {
var tabContainers = $('div.tabs > div');
tabContainers.hide().filter(':first').show();
$('div.tabs ul.tabNavigation a').click(function () {
tabContainers.hide();
tabContainers.filter(this.hash).show();
$('div.tabs ul.tabNavigation a').removeClass('selected');
$(this).addClass('selected');
return false;
}).filter(':first').click();
});
$(function () {
var tabs = [];
var tabContainers = [];
$('ul.tabs a').each(function () {
// note that this only compares the pathname, not the entire url
// which actually may be required for a more terse solution.
if (this.pathname == window.location.pathname) {
tabs.push(this);
tabContainers.push($(this.hash).get(0));
}
});
// sniff for hash in url, and create filter search
var selected = window.location.hash ? '[hash=' + window.location.hash + ']' : ':first';
$(tabs).click(function () {
// hide all tabs
$(tabContainers).hide().filter(this.hash).show();
// set up the selected class
$(tabs).removeClass('selected');
$(this).addClass('selected');
return false;
}).filter(selected).click();
});
</script>
The html and PHP (a portion):
<div class="tabs">
<ul class="tabNavigation">
<li>Account</li>
<li>Password</li>
<li>Favorites</li>
<li>Avatar</li>
</ul>
<div id="account_div">
<?php include("personal_info_edit.php"); ?>
</div>
<div id="change_password_div">
<?php include("change_password.php"); ?>
</div>
<div id="favorites_div">
<?php include("favorites.php"); ?>
</div>
<div id="avatar_div">
<?php include("avatar.php"); ?>
</div>
</div>
The following is contained in my change_password_submit.php page:
$update_pass= ("Password changed successfully.");
header("location:profile_edit.php?update_pass=$update_pass#change_password_div");
exit();
By default, whenever profile_edit.php is loaded, the personal_info_edit div is shown and the others are hidden. What do I need to change in the code so that I can reference the 2nd div (ie. change_password div and hide the rest after someone changes their password?
Any help will be greatly appreciated.
This is perhaps not the most elegant solution, but it should work.
You can have PHP sniff your url variables for the existence of a particular variable. I'd probably call this something like 'selectedTabId' or something like that. Then, if that variable exists, you can have jQuery invoke the click action on that tab. You'll want to use switch/case for this rather than just sending through whatever happens to be in the URL, as people can put nasty things there that you don't want your jQuery to run. I won't do that in my example below, for expediency's sake.
This is a notional example...
<?php
if( array_key_exists('selectedTabId',$_GET) ){
$selectedTabId = $_GET['selectedTabId'];
echo "<script type=\"text/javascript\">";
echo "jQuery(document).ready(function(){'#$selectedTabId').click()});";
echo "</script>";
}
?>
Give that a shot and see if it works for you.
I use this thinger: http://flowplayer.org/tools/tabs/index.html
It does that for you. It also does a whole lot on top. It maybe worth implementing instead of your custom solution?
Here's an example of it in action: http://www.estanciaboerne.com/amenities#TAB2entertainment
(This doesn't actually teach you anything, but it is a solution to your problem, so I'm sorry and you're welcome all in one.)

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