Make PHP and JAVASCRIPT work together. - php

I have a simple php if statement that checks for an error return on a form submit basically.
<?php if ($this->session->flashdata('error')): ?>
×
<div class="alert alert-error" id="error"><?php echo $this->session->flashdata('error'); ?></div>
<?php endif ?>
And I have this script that I want to put into this php so when the php is true the login box or account-container will shake.
$("#account-container").addClass("animated shake");
I tried echoing the script inside the php but all that was give me echo ; displayed on the page when the if was true.

Maybe you can use this script, I'm not at ease with jquery and you would have to adapt the code:
$(function(){
if ($("#error").length !== 0) {
$("#account-container").addClass("animated shake");
}
});
Place it in the header as javascript source or embedded in a script tag
The $().load hook the containing handler to the onload event in the page*
The function simply check if there is an element in the page with id error and
add the class to the #account-container element if is the case.
I won't use $().ready() as the dom can still be partially rendered
References:
http://api.jquery.com/ready/ Says to use .load() function for onload event and
alert that a <body onload="something"> tag is not compatible with the jquery event management
http://api.jquery.com/load/ Can be useful

I think that you are using Jquery for the javascript shake, you should call the javascript routine when the page is ready to load
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>shake demo</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<style>
#toggle {
width: 100px;
height: 100px;
background: #ccc;
}
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
</head>
<body>
<p>Click anywhere to shake the box.</p>
<div id="toggle">This is rendered by PHP</div>
<script>
$( document ).ready(function() {
$( "#toggle" ).effect( "shake" );
});
</script>
</body>
</html>
Note that the whole page is rendered by PHP, and the script will work when the document render is ready.

Related

How to use the jquery variable in script inside the PHP tag echo?

I am getting the issue
Warning: Use of undefined constant otherInput - assumed 'otherInput'
(this will throw an Error in a future version of PHP) Warning: A
non-numeric value encountered
I know there is some issue with the quote.
What I am doing is, I have to click on the anchor tag called Click me one and sending the data-id in the script. I am getting the id value in the script but I am getting the error on $(".showme'+otherInput+'").show();
I am using WordPress and I have to use the below code in the function.php so I have to use my script inside the PHP tag.
This is the screenshot of the code
Here is the code
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
.showme{display: none;}
</style>
</head>
<body>
<div class="clickme" data-id="1">Click me one</div>
<div class="showme showme1">this is example</div>
<?php
echo '<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(".clickme").click(function(){
var otherInput=$(this).data("id");
$(".showme'+otherInput+'").show();
});.
</script>';
?>
</body>
</html>
It looks like everything in your php block is all JQuery/Javascript.
Q: What do you even need the PHP block and the "echo" for?
Current:
<?php
echo '<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(".clickme").click(function(){
var otherInput=$(this).data("id");
$(".showme'+otherInput+'").show();
});.
</script>';
?>
Suggested change:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(".clickme").click(function(){
var otherInput=$(this).data("id");
$(".showme"+otherInput).show();
});.
</script>'
Just follow the regular js standard, and if you willing to implement your script inside the php code:
Replace your code with these changes:
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
.showme{display: none;}
</style>
</head>
<body>
<div class="clickme" data-id="1">Click me one</div>
<div class="showme showme1">this is example</div>
<?php
echo '<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(".clickme").click(function(){
var otherInput=$(this).data("id");
$(".showme"+otherInput).show();
//here otherInput js variable is just used as regular js variable inside the script, so no need to extra commas to call that js variable, just use it like you do in js files, and will work fine.
});
</script>';
?>
</body>
</html>

Show div using jquery in PHP file

Hiii everyone,
I just want to show one div if the database value is equal to some value.I tried like this
<?php echo $show['birth_certificate_available']=='Available') { ?>
<script type="text/javascript">
$(".birth").show();
</script>
<?php } ?>
But the div is not showing.I dont know why its not working.Kindly guide me to correct this issue.
Please modify the code accordingly :
<?php if($show['birth_certificate_available']=='Available') { // put a condition?>
<script type="text/javascript">
$(document).ready(function(){ // jQuery ready function
$(".birth").show();
});
</script>
<?php } ?>
Wrap it in ready() function as follows,
Assuming you have already imported the relevant jquery lib in your code.
<?php echo $show['birth_certificate_available']=='Available') { ?>
<script type="text/javascript">
$(document).ready(function(){
$(".birth").show();
});
</script>
<?php } ?>
I missed JQuery reference document so that its not worked.Now I added script document its working.Thanks all who helped me to fix this.
Solution
echo outputs data to the page. To write a condition, you would like to use if statements.
<?php if ($show['birth_certificate_available'] === 'Available'): ?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('.birth').show();
});
</script>
<?php endif; ?>
Note: if jQuery is already linked to your document, remove the <script src="..."></script> line. Otherwise, I suggest you to move the <script src="..."></script> line right before the </body> HTML closing tag to speedup HTML elements loading:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div class="birth" hidden="hidden">Foobar</div>
<?php if ($show['birth_certificate_available'] === 'Available'): ?>
<script>
$(document).ready(function() {
$('.birth').show();
});
</script>
<?php endif; ?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</body>
</html>
Note: I use the === equal assertion to force type testing. Whatever, be careful: testing is case-sensitive, whether it is == or ===
The div element must have the birth class, must exist and must be hidden in order to successfully show() it
Debug
$show variable
If this is not working, and in order to debug the $show variable, you may want to use var_dump() as so:
var_dump($show);
and ensure it is an array and has the birth_certificate_available index defined.
Javascript errors
Use the browser console to retrieve javascript errors (such as inexisting div elements...)

document.write() in a Fancybox 1 window

Probably I'm misunderstanding something about Fancybox v1 but have the following minor issue. First I'm calling fancybox via clicking a link:
$(document).ready(function() {
$(".href").click(function() {
$.fancybox.open({
href : $(this).attr("data-id"),
type : 'iframe'
});
});
});
This loads a simple PHP/HTML page with JS, to be populated into the Fancybox window:
<!DOCTYPE html><html><head><title></title></head>
<body>
<?php
# this is the fancybox content
echo "<script>var dcwrtext = 'random_text'; document.write(dcwrtext);</script> Some other content to show on fancybox.";
?>
</body></html>
The content appears without a problem, but the nuance is, the document.write value is echoed after the closing </script> tag: and this makes the content visible on the page, not the document.write() function. You can see this in the source code:
<body>
<script>var dcwrtext = 'random_text'; document.write(dcwrtext);</script>**random_text** Some other content to show on fancybox.
</body>
The problem seems to be with fancybox, if I use the document.write() on a standard HTML (not fancyboxed) page, as expected, it will correctly show 'random_text' on the page, inside <script></script> only. This is the source code:
<body>
<script>var dcwrtext = 'random_text'; document.write(dcwrtext);</script> Some other content to show on fancybox.
</body>
What I'd need is if I open the fancbox window, 'random_text' shouldn't appear literally after the closing </script> tag, but would be displayed only by the document.write() function.
This is how I tested:
main page:
<html>
<head>
<title></title>
<meta name="" content="">
<link rel="stylesheet" type="text/css" href="fancybox/source/jquery.fancybox.css?v=2.1.2" media="screen" />
</head>
<body>
<div data-id="fancy.php" class="href">open fancy</div>
<script src="http://code.jquery.com/jquery-1.9.0.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.js"></script>
<script type="text/javascript" src="fancybox/source/jquery.fancybox.js?v=2.1.3"></script>
<script>
$(document).ready(function() {
$(".fancybox").fancybox();
$(".href").click(function() {
$.fancybox.open({
href : $(this).attr("data-id"),
type : 'iframe'
});
});
});
</script>
<div id="theid" class="fancybox"></div>
</body>
</html>
and the page being opened in fancybox: fancy.php
<html>
<head>
<title></title>
</head>
<body>
<?php
$randomtext = "random_text";
echo "<script>var dcwrtext = '$randomtext'; document.write(dcwrtext);</script>Some other content to show on fancybox";
?>
</body>
</html>
[I had to include jquery-migrate-1.2.1.js because of an error [ Uncaught TypeError: Cannot read property 'msie' of undefined] when including newer versions of jquery with fancybox]

div sliding effect does not work with jQuery

I created this question before but in another way and got no answers. So today I wrote some simple code to share my problem in a clear way.
I used jQuery to call an image slideshow function.
The AJAX function in show.php will call get.php and print the results in a DIV.
My problem is that sliding (prev - next) inside the DIV supplied by get.php does not work in show.php. But if I call get.php directly in my browser, then it works.
I am confused, I guess I have an error in my div when calling AJAX.
My Files
show.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test </title>
<link rel="stylesheet" type="text/css" href="demo.css" />
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="newscript.js"></script>
<link href="themes/2/js-image-slider.css" rel="stylesheet" type="text/css" />
<script src="themes/2/js-image-slider.js" type="text/javascript"></script>
<link href="generic.css" rel="stylesheet" type="text/css" />
</head>
<body>
<?php
include("samiloxide.php");
$sql=mysql_query(" select * from section ");
while($r=mysql_fetch_array($sql)){
echo "<li><a onclick='loadpage($r[id])' >$r[section]</a></li>" ;
}
?>
<div id="pageContent"></div>
</body>
</html>
newscript.js
var section;
function loadpage(section){
var section = section.toString();
$.ajax({
type: "POST",
url: "get.php",
dataType: "script",
data: ({section : section}),
success: function(html){
$("#pageContent").empty();
$("#pageContent").append(html);
}
});
}
get.php
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<style type="text/css">
<!--
#gallery-wrap{margin: 0 auto; overflow: hidden; width: 732px; position: relative;}
#gallery{position: relative; left: 0; top: 0;}
#gallery li{float: left; margin: 0 20px 15px 0;}
#gallery li a img{border: 4px solid #40331b; height: 175px; width: 160px;}
#gallery-controls{margin: 0 auto; width: 732px;}
#gallery-prev{float: left;}
#gallery-next{float: right;}
-->
</style>
<script type="text/javascript">
<!--
$(document).ready(function(){
// Gallery
if(jQuery("#gallery").length){
// Declare variables
var totalImages = jQuery("#gallery > li").length,
imageWidth = jQuery("#gallery > li:first").outerWidth(true),
totalWidth = imageWidth * totalImages,
visibleImages = Math.round(jQuery("#gallery-wrap").width() / imageWidth),
visibleWidth = visibleImages * imageWidth,
stopPosition = (visibleWidth - totalWidth);
jQuery("#gallery").width(totalWidth);
jQuery("#gallery-prev").click(function(){
if(jQuery("#gallery").position().left < 0 && !jQuery("#gallery").is(":animated")){
jQuery("#gallery").animate({left : "+=" + imageWidth + "px"});
}
return false;
});
jQuery("#gallery-next").click(function(){
if(jQuery("#gallery").position().left > stopPosition && !jQuery("#gallery").is(":animated")){
jQuery("#gallery").animate({left : "-=" + imageWidth + "px"});
}
return false;
});
}
});
-->
</script>
<?php
include("samiloxide.php");
//if(!$_POST['page']) die("0");
$section = (int)$_POST['section'];
$sql=mysql_query(" select * from images where section='$section'");
echo "
<div id='gallery-wrap'>
<ul id='gallery'>
";
while($rr=mysql_fetch_array($sql)){
echo " <li><a href='$rr[image]'><img src='$rr[image]' alt='' /></a></li>";
}
echo "
</ul>
</div>
<div id='gallery-controls'>
<a href='#' id='gallery-prev'><img src='images/prev.png' alt='' />next</a>
<a href='#' id='gallery-next'><img src='images/next.png' alt='' />last</a>
</div>
";
?>
This is a bit complicated, and I am unable to provide a quick fix to your code that you could just copy, paste and verify.
In get.php, you load a document with a gallery, and you make it a working gallery from $(document).ready().
But in show.php, when you load the get.php file, $(document).ready() is not called. The $(document).ready() of show.php was already called long before, and your document is now in the interactive state. So when you load the layout, you do not automaticallly execute the code that makes that layout work.
You have to move the $(document).ready() code in your get.php into show.php, and then bind it to the AJAX call completion. Or unbind the code in get.php: just call it from the end of the HTML without wrapping it in $(document).ready().
This is not guaranteed in all browsers all the time, though, because while $(document).ready() is called properly on document being ready, in show.php what you do is you ask to load a HTML file.
And the HTML gets loaded, and so onLoad gets fired. You can't expect different.
Then that HTML asks to load other assets (such as images), but the browser did not know this. It has already fired the onLoad and so you already executed the gallery setup code. If the layout requires the images' SRC to be already loaded in order to style properly, then it will not always work. It might work the second time because the images are in the browser cache. It may work on fast connections and not on slow connections; it may work with small images, quickly loaded, and not with larger images. All these behaviours indicate that images being already loaded is necessary.
Again, a quick and dirty fix is to fire the setup after a suitable delay (but what is suitable? You can't know). Another possibility, if all the images are of known sizes, is to supply those sizes in HTML or CSS. After all, the layout usually requires images being loaded so that they occupy space on the page, but for that, you don't need images to be actually displayable. They might be empty spaces (maybe styled with a background).
A third possibility, more complicated but guaranteed to work in all browsers, is to save the image SRC's into another kind of tag (e.g. DIVs with a class of imageloading, by default hidden), and after the load() success to analyze these tags and convert them to IMGs attaching an onload to them. When all those onloads have fired, you know that it's OK to launch the gallery setup. While longer to describe (and code), this last method is actually much faster than the naive "quick fix: wait a bit and fire setup" one.

Inline javascript checks in PHP

I was trying to use <script> <noscript> checks inline with my PHP to render different form elements depending on weather or not someone has javascript enabled.
To display something to non enabled users only I can successfully use
<noscript> <?php ... ?> </noscript>
To display something to enabled users only I tried whats below but it does not work the same as above. Instead it allows all users to still see the PHP.
<script> <?php ... ?> </script>
How can I limit something to only those with javascript enabled without having two totally different pages?
You may be able to use something like this:
<script>
<?php
ob_start();
// ...
$scriptOnlyData = ob_get_clean();
?>
document.write(<?php echo json_encode($scriptOnlyData); ?>);
</script>
Javascript runs on the Client-side (in the browser), PHP runs on the Server-side (before the page is sent to the browser). So PHP does not know whether the browser does, or does not, have Javascript.
The simplest solution is to use Javascript itself to show/hide various elements within the browser, like so:
<!doctype html>
<html>
<head>
<title>Test Page</title>
<style>
.showWithJS {
display:none;
}
</style>
</head>
<body>
<div class="showWithJS">
This DIV, and anything with the class "showWithJS",
will only be seen when Javascript is enabled.
</div>
<div class="hideWithJS">
This DIV, and anything with the class "hideWithJS",
will not be seen when Javascript is enabled.
</div>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.showWithJS').show();
$('.hideWithJS').hide();
});
</script>
</body>
</html>
Another option would be to use Javascript to set a cookie (which can be read by PHP) to indicate whether that javascript is running. The downside of that, of course, is that, should the user switch javascript on/off mid-visit, the cookie will not update to reflect that change.
<?php
$javascriptOn = ( isset( $_COOKIE['javascript'] ) && $_COOKIE['javascript']=='on' );
?><!doctype html>
<html>
<head>
<title>Test Page</title>
</head>
<body>
<?php if( $javascriptOn ){ ?>
<div>
This DIV will only be seen when Javascript is enabled.
</div>
<?php } ?>
<?php if( !$javascriptOn ){ ?>
<div>
This DIV will not be seen when Javascript is enabled.
</div>
<?php } ?>
<script>
document.cookie = 'javascript=on';
</script>
</body>
</html>
The downside of this is that you need a pageload to set the cookie (it cannot be set and read by the same pageload), so you would need to refresh the page to see the changes.
Load the PHP in javascript and then insert when the DOM loads
JS:
function pageLoad(){
var text = "<?php ... ?>";
document.getElementById('scriptSpan').innerHTML = text;
}
html:
<span id="scriptSpan"></span>

Categories