How to use JQuery and PHP? - php

I am creating a PHP App and am using JQuery but have run into problems. For example, below is the code for a page i am writing, the alert() function calls when the pages loads but the second javascript Jquery code does not, I cannot see why one line works but the second does not?
help.php
<?php
echo "<script>";
echo "alert(\"Loaded\");";
echo "$(\"#newDiv\").draggable().resizable();";
echo "</script>";
echo "<div id=\"newDiv\">";
echo "</div>";
?>
The page calls the alert and creates the div but does not execute the jquery statement.
I think this may be due to have my page is structures and loaded. pages are loaded inside a div using Jquery and AJAX so the only page the user actually "loads" is an index.php page like so:
index.php
<html>
<head>
<title>BluePrintr Web Application.</title>
<link rel="stylesheet" type="text/css" href="public.css" />
<script type="text/javascript" language="javascript" src="jquery.js"></script>
<script type="text/javascript" language="javascript" src="myLibs.js"></script>
</head>
<body>
<?php
echo "<div id=\"web_Page\">";
//////////////////////////////////////////////////////
echo "<div id=\"web_Header\">";
require("public/templates/header.php");
echo "</div>";
//////////////////////////////////////////////////////
echo "<div id=\"web_Menu\" class=\"horizontalcssmenu\">";
require("public/templates/menu.php");
echo "</div>";
//////////////////////////////////////////////////////
echo "<div id=\"web_Content\">";
echo "</div>";
//////////////////////////////////////////////////////
echo "<div id=\"web_Footer\">";
require("public/templates/footer.php");
echo "</div>";
echo "</div>";
?>
The menu loads and then any page selected from this menu is then loaded into the "#web_Content" div. So when the help.php page is selected from the menu, it injects the script into the div.
Can anyone see why the javascript code will not execute on help.php?

You need to wrap the jquery to initialize only after the page loads
<?php
echo "<script type='text/javascript'>";
echo "alert(\"Loaded\");";
echo "$(function(){$(\"#newDiv\").draggable().resizable();});";
echo "</script>";
echo "<div id=\"newDiv\">";
echo "</div>";
?>`
The $(function(){}); will cause the code to wait until after the page has been completely loaded.. I'm assuming you are also loading jQuery UI as you are using .draggable()?

Do this:
<script type='javascript'>
$(document).ready (function() {
alert('Hi');
// Other initialization
});
</script>
Also, just write all of that as HTML. Use PHP like this:
<html>
<body>
<?php if ($var == true) {?>
<p>Hello</p>
<?php } ?>
</body>
</html>
If $var is false, the page is blank. This makes things much more readable.

your javascript may be executing before the page has finished rendering in the browser
have a look at the jquery ready function for examples
http://api.jquery.com/ready/

As mentioned, you need to wrap your jQuery code inside $(document).ready().
You should stop doing it the way you are now and use a templating system, with a proper MVC architecture for serving your pages. It's just gonna be hell for you if you keep doing it this way. You should never have PHP outputting javascript code, this should be written by you in seperate files in a functional way and then included in your HTML file.

There is another good way like below:
$alert = <<<LABEL
<script>
$(document).ready (function() {
alert('Hi');
// Other initialization
});
</script>
LABEL;
echo $alert;

Related

How to echo javascript code in php

I am having a problem with how to echo javascript in php. I have a form which on submit will execute itself and echo some text and will redirect to a page in 5secs. I am currently echoing this:
header("Refresh: 5;url=index2.php?ID=".$objResult["ID"]."");
echo '<html>';
echo '<head>';
echo '<title>Klant toevoegen</title>';
echo '<link rel="stylesheet" href="style.css" type="text/css" media="screen" />';
echo '</head>';
echo '<body>';
echo '<fieldset>';
echo ''.$Naam.' is added to the database, u will be redirected in a couple of seconds.<br><br>';
echo '</fieldset>';
echo '</body>';
echo '</html>';
The javascript I have is a countdown which counts down from 5 to 1. The code is this:
<script>
var countdownFrom = 5; // number of seconds
var countdownwin;
var stp;
function CountDownStart() {
stp = setInterval("CountDownTimer('CountDownTime')",1000)
}
function CountDownTimer(id)
{
if (countdownFrom==0) {clearInterval(stp); window.close(); }
else {
var x
var cntText = "Closing in "+countdownFrom+" seconds";
if (document.getElementById)
{
x = document.getElementById(id);
x.innerHTML = cntText; }
else if (document.all)
{
x = document.all[id];
x.innerHTML = cntText; }
}
countdownFrom--
}
</script>
<title>Untitled</title>
</head>
<body onload="CountDownStart()">
<Div id="CountDownTime"></div>
</body>
Now I would like to echo this countdown script to replace the <fieldset> in the html. I have tried several things like just add the whole code in 1 echo ''; and I tried to echo all the lines seperately but with both it crashes my whole script. If anyone knows how to do this it would be great!
I Wouldn't write all those echo's, instead, leave all the HTML and JS outside the PHP block
<?php
some php code
?>
HTML AND JS
<?php
More php if required
?>
And use
<?=$Naam?>
To inject your values where required
Alternatively you should look into template engines
Try to use
echo <<<EOT
/* some text here */
EOT;
You can put the script in a separate .js file and echo the script tag:
<? echo "<script type='text/javascript' src='path/to/script.js' ></script> ?>
Don't forget to remove any HTML tags from the JS file, like <body>, <head>, etc.

using jquery, ajax and php to laod content on your site without reloading the whole page

I am a newby in ajax and php and I would very much appreciate it if you could help me out. Seeing that I only know a little bit javascript and php I really don't know how to remedy this problem could you help me please! I've been hunting down a fix but couldn't find any, hopefully my search will stop here. I'll try my best to be clear in my explanation.
I would like this:
load html page called ducks
to load into the myDiv area an html page called ducks.html.
I would also like that when I click on on this:
load a list of html links
I would like it to load an html page with a list of links that when clicked will load into the myDiv area without reloading the whole page.
And lastly I would like to set up the myphpscript php file. To load a page with a list of links that will appear in the myDiv area and when I click on one of those links it will load likewise into the myDiv area.
This is my code
<!-- This is your PHP script... myphpscript.php -->
<?php
$contentVar = $_POST['contentVar'];
if ($contentVar == "con1") {
include 'con2.html';
} else if ($contentVar == "con2") {
echo "<a href='con2'>View</a>";
} else if ($contentVar == "con3") {
echo "Content for third click is now loaded. Any <strong>HTML</strong> or text you wish.";
}
?>
<!-- This is the rest of my code -->
<html>
<head>
<script type="text/javascript" src="jQuery-1.5.1.js"></script>
<script language="JavaScript" type="text/javascript">
<!--
function swapContent(cv) {
$("#myDiv").html('<img src="loader.gif"/>').show();
var url = "myphpscript.php";
$.post(url, {contentVar: cv} ,function(data) {
$("#myDiv").html(data).show();
});
}
//-->
</script>
<style type="text/css">
#myDiv {
width:200px; height:150px; padding:12px;
border:#666 1px solid; background-color:#FAEEC5;
font-size:18px;
}
</style>
</head>
<body>
<a href="#" onClick="return false"
onmousedown="javascript:swapContent('con1');">Content1</a>
<a href="#" onClick="return false"
onmousedown="javascript:swapContent('con2');">Content2</a>
<a href="#" onClick="return false"
onmousedown="javascript:swapContent('con3');">Content3</a>
<div id="myDiv">My default content for this page element when the page initially loads</div>
</body>
</html>
It sounds to me that if you want an external page to load when something is clicked, you need to perform an ajax GET or POST request, then print the results to the div:
http://api.jquery.com/jQuery.post/
If you just want to change the contents of the div to some other text, you can use something like jQuery.html: http://api.jquery.com/html/
<script>
$("#idForLink").click(function () {
var htmlStr = "The new text to show";
$('#myDiv').text(htmlStr);
});
</script>
Without using jQuery, your example above is sending self posts to echo contentVar which will always refresh the page.
See this fiddle for a jquery+css solution to your problem [NO PHP REQUIRED]: http://jsfiddle.net/bYNeg/
If you are simply grabbing HTML from another file I would use the load method, as its quick and easy:
$(document).ready(function(){
$('#myDiv').load("someFile.html");
});
For more extensive requests you can use Post and Get. They allow you to pass data with the URL request in order to affect the results that are returned. Obviously your requested URL would need to be PHP/ASP and handle the request in this case.
JAVASCRIPT:
<script type="text/javascript">
$(document).ready(function(){
// this is your mouse event (click) listener
$('.destination_div').on('click','a',function() {
var url = $(this).attr("href");
$('.destination_div').load(url);
return false;
});
});​
</script>
Make your HTML anchors simple, do not include inline javascript, because the on("click") handles it already.
HTML:
Your HTML with links

How to make a scroll news like Top Tweets in twitter homepage? (php)

I want to make a site use wp, and I want add a scroll news like Top Tweets in twitter homepage. when the custom post a new replys in every part of my page, the new topics will disply in this scroll news part. they all come from latest 10 items of database. How to do that? Thanks
Using Jquery you can make a div slide in and slide out of view.
http://docs.jquery.com/UI/Effects/Slide#overview.
Then you give each div a unique id each containing a comment from your database. Initialize div 0,1,2 as visible and 3-9 as hidden. Here the javascript structure:
echo <<<CONTENT
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js">
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript">
k=1;
setInterval("livefeed(k++)",1000);
function livefeed(i){
slide(i);
}
function slide(i){
addTop((i+3)%10);
removeBottom(i%10);
var j=((i-1)%10);
$('.livefeed').prepend($("#"+j));
}
function addTop(i){
var e=document.getElementById(i);
$("#"+i).fadeIn(1000);
}
function removeBottom(i){
$("#"+i).fadeOut(1000);
}
</script>
</head>
<body>
CONTENT;
echo "<div class='livefeed'>";
for($i=9;$i>=0;$i--){
if($i<4&&$i>0){
echo "<div id='".$i."' >This is comment $i from the database</div>";
}else{
echo "<div style='display:none' id='".$i."' >This is comment ".$i." from the database</div>";
}
}
echo "</div>";
THis updates every second.. which is a bit fast ... so you should set it to something like 7000 milliseconds.
demo

I can't get the alert to fire. What am I missing?

I can't get the alert to fire. What am I missing?
(the code below is inside a WP plugin)
<?php
wp_enqueue_script('jquery');
?>
<script type="text/javascript">
jQuery('#myTest').click(function(){alert('hi');});
</script>
<?php
echo "<div><input type='button' value='Test' id='myTest' /></div>";
?>
The script is processed before the element, so #myTest doesn't exist when you're assigning the handler. Swap them around:
<?php
echo "<div><input type='button' value='Test' id='myTest' /></div>";
?>
<script type="text/javascript">
jQuery('#myTest').click(function(){alert('hi');}));
</script>
Alternatively, you can use live() which allows binding events to elements that don't exist yet:
<script type="text/javascript">
jQuery('#myTest').live("click", function(){alert('hi');}));
</script>
<?php
echo "<div><input type='button' value='Test' id='myTest' /></div>";
?>
Or make use of jQuery's ready() handler, which will fire when all elements have been parsed:
<script type="text/javascript">
jQuery(document).ready(function ($) {
$('#myTest').click(function(){alert('hi');}));
});
</script>
<?php
echo "<div><input type='button' value='Test' id='myTest' /></div>";
?>
Note that in the last example, I'm aliasing the jQuery namespace in the $ argument that is passed to the function. This allows you to use $ for jQuery with WordPress instead of typing out jQuery all the time.
You're missing the document.ready handler, like this:
<script type="text/javascript">
jQuery(function() {
jQuery('#myTest').click(function(){alert('hi');});
});
</script>
By wrapping it like this, it'll wait until the element's loaded in the DOM and ready to be found by jQuery('#myTest').
The script executes before the content is loaded. When the script executes it is unable to find an element with an ID of myTest so it just ignores adding the event handler.
Either put the script after the event, or listen for an ( onload | document.ready ) event.
try this in your script tags:
$(document).ready(function() {
$('#myTest').click(function(){alert('hi');});
});

how to add script inside a php code?

How can I add script inside a php code? suppose i want to give an alert for a button click.. how can i do that??
You can just echo all the HTML as normal:
<?php
echo '<input type="button" onclick="alert(\'Clicky!\')"/>';
?>
<?php
echo"<script language='javascript'>
</script>
";
?>
You mean JavaScript? Just output it like anything else in the page:
<script type="text/javascript">
<?php echo "alert('message');"; ?>
</script>
If want PHP to generate a custom message for the alert dialog, then basically you want to write your JavaScript as usual in the HTML, but insert PHP echo statements in the middle of your JavaScript where you want the messages, like:
<script type="text/javascript">
alert('<?php echo $custom_message; ?>');
</script>
Or you could even do something like this:
<script type="text/javascript">
var alertMsg = '<?php echo $custom_message; ?>';
alert(alertMsg);
</script>
Basically, think about where in your JavaScript you want PHP to generate dynamic output and just put an echo statement there.
To avoid escaping lot of characters:
echo <<<MYSCRIPT
... script here...
MYSCRIPT;
or just turn off php parsing for a while:
?>
...your script here
<?php
You could use PHP's file_get_contents();
<?php
$script = file_get_contents('javascriptFile.js');
echo "<script>".$script."</script>";
?>
For more information on the function:
http://php.net/manual/en/function.file-get-contents.php
You mean you want to show a javascript alert when a button is clicked on a PHP generated page?
echo('<button type="button" onclick="alert(\'Alrt Text!\');">My Button</button>');
Would do that
You can insert script to HTML like in any other (non-PHP) page, PHP processes it like any other code:
<button id="butt">
→ Click ME! ←
</button>
<script>
document.getElementById("butt").onclick = function () {
alert("Message");
}
</script>
You can use onSOMETHING attributes:
<button onclick="alert('Message')">Button</button>
To generate message in PHP, use json_encode function (it can convert to JavaScript everything that can be expressed in JSON — arrays, objects, strings, …):
<?php $message = "Your message variable"; ?>
<button onclick="alert(<?=htmlspecialchars(json_encode($message), ENT_QUOTES)?>)">Click me!</button>
If you generate code for <script> tags, do NOT use htmlspecialchars or similar function:
<?php $var = "Test string"; ?>
<button id="butt">Button</button>
<script>
document.getElementById("butt").onclick = function () {
alert(<?=json_encode($var)?>);
}
</script>
You can generate whole JavaScript files, not only JavaScript embedded into HTML. You still have to name them with .php extension (like script.php). Just send the correct header.
script.php – The JavaScript file
<?php header("Content-Type: application/javascript"); /* This meant the file can be used in script tag */ ?>
<?php $var = "Message"; ?>
document.getElementById("butt").onclick = function () {
alert(<?=json_encode($var)?>);
}
index.html – Example page that uses script.php
<!doctype html>
<html lang=en>
<head>
<meta charset="utf-8">
<title>Page title</title>
</head>
<body>
<button id="butt">
BUTTON
</button>
<script src="script.js"></script>
</body>
</html>
Exactly the same way you add HTML tags. Echo it
One way to avoid accidentally including the same script twice is to implement a script management module in your templating system. The typical way to include a script is to use the SCRIPT tag in your HTML page.
<script type="text/javascript" src="menu_1.0.17.js"></script>
An alternative in PHP would be to create a function called insertScript.
<?php insertScript("menu.js") ?>
To add javascript inside a PHP code you can do this
<?php
echo "<script>alert('message');</script>";
?>
Better this
<?php
echo "<script src='myScript.js'></script>";
?>
And this for WordPress function.php file
<?php
$script= get_template_directory_uri() . '/myScript.js';
echo "<script src=".$script."></script>";
?>
In your php file you can do something like this :
<?
//Your php code
?>
<script type="text/javascript">
//Your javascript code
</script>
<?php //Your php code

Categories