I'm a PHP phr34k addicted to JavaScript on the quest for some knowledge. If one were to include php code in their scripts, what would be the best method? I have provided some sample code as an example on how I would go about including PHP in my scripts.
Is this a valid method?
index.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>PHP with JavaScript?</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="test.js.php"></script>
</head>
<body>
</body>
</html>
test.js.php
<?php
$foo = 'bar';
?>
$(document).ready(function() {
var foo = '<?php echo $foo; ?>';
alert(foo);
});
Thanks again!
Also set the content type header in test.js.php
header('Content-Type: text/javascript');
You can also define foo inline like
<!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>PHP with JavaScript?</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
var foo = '<?php echo $foo;?>';
</script>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
</body>
</html>
test.js
$(function(){
alert(foo);
});
I've seen people use the PHP interpreter to combine multiple JS source files before serving them to the client. That way the JS developers can benefit from having multiple files for more organized development but avoid sending multiple JS files (thus multiple HTTP requests) to the client.
However, these days there are several build scripts just for JavaScript. Sprockets, for example, allows you to automate building JavaScript files. Before that I considered it best practice to "compile" the JavaScript dependencies before hand. I wrote a simple Python script, for example, that would look for #include comments in JS source and order includes by their order of need. Probably better than wasting server time in exchange for a slight development convenience.
EDIT: Just take special care that you dump your variable data into the JavaScript properly. For example, if $foo is a string then you need to make sure that it's surrounded by double quotes. As is that code is going to go looking for a JavaScript variable called bar.
Unless you have a very bizarre situation, what you've described isn't really possible. PHP is evaluated on the server, while Javascript is sent to the user agent and executed by its Javascript engine (on the client side).
No user agents that I know of contain a PHP engine, so there's no way to have PHP executed on the client side. Besides, unless you're use some heinous escapes, the PHP will be executed by the server anyway before the Javascript is sent to the client.
In the latter example you give, the PHP gets evaluated on the server and the client is sent a Javascript file that looks exactly like:
$(document).ready(function() {
var foo = 'bar';
alert(foo);
});
So there's no PHP contained within the Javascript; rather, you're dynamically generating (normal) Javascript via PHP.
If this latter is what you intended, then yes - this works fine. The PHP engine doesn't know anything about Javascript, and just generates some text that happens to have a particular meaning to a JS-parsing client. So the presence of Javascript doesn't change anything on the PHP side, and since it's processed out, the (previous) presence of PHP doesn't change anything on the Javascript side.
(If you wanted your Javascript to execute some PHP on the client, however, that's fundamentally not possible.)
Related
I found a Webpage saved as something.php. But the source code tells me <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
I also found out that PHP code does not work on the webpage.
What is the need for making the file extension PHP if HTML is used?
(Not exactly HTML, but XHTML)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
What is the need for making the file extension PHP if HTML is used?
(Not exactly HTML, but XHTML)
Considering your comments so far, particularly you stated there is no PHP; you can just change the file extension to XHTML. You can always change it back.
I wonder what other PHP files exists where you "found" this page and why. Assuming someone before you developed the site, there is probably a reason they used PHP file extensions.
Unless your host doesn't support PHP, then you should be able to run php code anywhere on that page by placing it inside "" tags. The 'Content-type' isn't relevant to whether PHP can run or not. Try adding the following code somewhere in your page:
<?php echo "Hey there, I'm a friendly PHP string!"; ?>
add this <?php echo "Hello!"; ?> in your page to test, and make sure that your server is running, and normally it works
Are you using a wamp/mamp server? Have you tried to turn it on?
These code are meta tags
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
and it has nothing to do with php unless you have included a php script to it.
Html/XHtml will run even though you are not using a php server. All php files has a .php file extension and will run only if you use a server like wamp for windows or mamp for mac.
You can still use html/xhtml code in a .php file.
For example I have an <h1>This is h1</h1> tag and you want to make it dynamic, you can put <?php ?> inside the tag and echo it out to display, <h1><?php echo "This is h1"; ?></h1>.
In case you want to put html code inside a php script, you can do it like this
<?php echo "<h1>This is h1</h1>"; ?>
You can learn more about php and other programming languages by the help of google. Just take your time, relax and enjoy learning. Don't pressure yourself, remember learning is not a medicine that when you take it, it will work in a few minutes. Learning takes time and practice. Enjoy coding.
Is there any method to cache an HTML-code of ExtJS components with further initializing it (binding events and so on) so that I can send it by PHP inside one solid HTML file?
In other words I want server to send already pre-rendered page.
If your idea is to capture the memory state of the client application that seems like a bold project, to say the least. See this other question.
If what you want is to have all you application embedded in one single HTML file, that is possible. Just concatenate all you Javascript (including Ext's code) and put it in a script tag, and do the same with the CSS and wrap in into a style tag.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>title</title>
<style>
/* All your CSS here */
</style>
<script>
// All you javascript here
</script>
</head>
<body>
<!-- page content -->
</body>
</html>
Obviously, if you care about the maintainability of you code, you should automate this procedure...
I have a php based website. As in, all of the pages html is output via php.
Here is a simple example:
<?php
ob_start();
$pageStart = '
<!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>MY WEBSITE PAGE</title>
</head>
<body>
<p>CONTENT</p>
</body>
</html>
';
echo $pageStart;
exit;
?>
What i would like to do is make use of some jquery in this page.
So naturally my first attempt was to include the script inside of the php variable like so:
<?php
ob_start();
$pageStart = '
<!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>Untitled Document</title>
<script type="text/javascript">
var datefield=document.createElement("input")
datefield.setAttribute("type", "date")
if (datefield.type!="date"){ //if browser doesn't support input type="date", load files for jQuery UI Date Picker
document.write('<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />\n')
document.write('<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"><\/script>\n')
document.write('<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"><\/script>\n')
}
</script>
<script type="text/javascript">
if (datefield.type!="date"){ //if browser doesn't support input type="date", initialize date picker widget:
jQuery(function($){ //on document.ready
$('#birthday').datepicker();
})
}
</script>
</head>
<body>
<p>CONTENT</p>
</body>
</html>
';
echo $pageStart;
exit;
?>
Now, I use dreamweavers code editor, which due to the syntax highlighting feature, will point out the masses of syntax errors produced in this.
So i at first attempted to slash out these errors. This failed.
So i tried changing the "s to 's, and visa versa, until the errors were gone. This failed too as it seems the script will not validate in this manner.
So i read a few tutorials, and found this one:
JavaScript and PHP may each bring great potential to any Web development effort, but they don't always play nice together. Read about the problems.
And the way I understand it, is that you'd need to include the js rather than have it as part of your php directly.
So have a file called page.php and another called jquery.php. So I decided to try and modify this idea to suite my problem.
So i started with something like this - index.php:
<?php
ob_start();
$pageStart = '
<!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>MY WEBSITE PAGE</title>
'. include $_SERVER['DOCUMENT_ROOT'] . '/../../path/to/include/datepicker.php'.'
</head>
<body>
<p>CONTENT</p>
</body>
</html>
';
echo $pageStart;
exit;
?>
And - datepicker.php:
<script language="Javascript">
var datefield=document.createElement("input")
datefield.setAttribute("type", "date")
if (datefield.type!="date"){ //if browser doesn't support input type="date", load files for jQuery UI Date Picker
document.write('<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />\n')
document.write('<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"><\/script>\n')
document.write('<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"><\/script>\n')
}
</script>
<script language="Javascript">
if (datefield.type!="date"){ //if browser doesn't support input type="date", initialize date picker widget:
jQuery(function($){ //on document.ready
$('#birthday').datepicker();
})
}
</script>
Now there are no syntax errors in either page, great... So I try it, half expecting things to finally just work...
Nope... Fatal Error: failed to open stream: No such file or directory blah blah. This error relates to the include that i added. So okay, even though the file is there, it is not being validated as php because there are no opening and closing php tags.
So I add them... Annnd... A page full of syntax errors again!
So my question is this:
Could some please share some knowledge and explain to me roughly how this process actually works. Whats the deal with all the syntax errors, and how are you supposed to go about a task like this?
I believe it is possible, and yes it would ceratinly be easier if i was not outputting the entire html via php. But this is a simple example and my actual design is alot more complex. It requires for the different parts of the page to be broken up into variables, in order to place those bits and peices when needed, dynamically.
Any input, suggestions, or insight would be greatly appreciated; and any links to pages or tutorials that cover this would also be greatly appreciated.
Thank You!!
All you need to do to use jQuery with PHP is to include the jQuery javascript file in your HTML document in the head tag. I actually use PHP along with jQuery all the time. And this is how I do it. In your code above, it looks like you have some escaping issues with your code. And it also looks like you want to hold the header of the page in a PHP variable then print it out. You don't have to do all that. Just put the plain text in your PHP file without any php tags and it will work. Also, you are using an old version of jQuery. Should probably use the latest version. But, if you need it stored in a PHP variable so that you can print it out, do this:
SO, here is some code to get you started.
<?php
$pageStart = '<!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>MY WEBSITE PAGE</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e) {
$("#date").datepicker();
});
</script>
</head>
<body>
<input type="text" id="date" name="date" />
</body>
</html>';
print $pageStart;
?>
<head>
<script type="text/javascript"
src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// javascript & jquery code
// even better would be if you would put client code in separate file!!!
});
</script>
</head>
<body>
<?php
echo "bla bla bla";
?>
</body>
and +1111 to # Heera's comment
You're missing the basics's.
Use Heredoc. Thousands of syntax errors will be gone.
See the heredoc version of your pages,
http://pastie.org/3412925
http://pastie.org/3412929
http://pastie.org/3412935 // Here you have used include to contact. include does not return anything. It just includes. So Its changed differently.
I think it should be
. (include ($_SERVER['DOCUMENT_ROOT'] . '/../../path/to/include/datepicker.php')) .
otherwise php will try to include all the stuff after until the l is reached (tags will be interpreted as part of the file name).
also, in terms of the php code, after the file is included (on success), the include statement translates into 1 as a number, instead of the content of the file.
use
<? $abc <<<qwerty
...
...
...
qwerty;
return qwerty;
?>
for all the files that you want to include
I currently have a webpage that's taking a while to load. The php side of the page does a lot of data processing and computation, and that's (unfortunately) unavoidable. I would like to display something on the page while the php is processing. Unfortunately, the majority of the page depends on the php computation.
The current solution I have is the following:
The HTML/PHP (beginning):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title id="title">Loading</title>
<link href="style.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="preLoading.js"></script>
</head>
<body onload="onLoad()">
<?php
flush();
?>
<?php
// computation.
?>
The javascript:
document.write('<span id="loading">Please wait... Loading and processing data.</span>');
function onLoad() {
if (document.getElementById) {
var loading = document.getElementById("loading");
loading.style.display="none";
}
}
It works well in the sense that while the page is rendering, there's a little waiting message displayed while the page renders. But it does not work in the sense that the page still waits for all the data to be received before rendering anything. How can I accomplish the latter?
One thing of note: the blank line before the doctype contains 1024 spaces, because I read in some places (including StackOverflow) that browsers wait until reading a certain number of characters before attempting to render anything.
Any ideas would be appreciated. Browsers are filled with arcane tricks and hacks that mystify me.
A better choice would be to have only the page's skeleton sent out, and then fetch the computational expensive data via AJAX calls. That way you can put up a placeholder page and fill in things as they become available.
The upside of this is that you're not dependent on flushing buffers - which do not guarantee that the data will actually be sent to the client, only that the next higher layer in the software stack should get everything that's available right now.
The downside is that now you'll have at least two HTTP requests to generate the page - one to fetch the page's skeleton, and at least one or more for the AJAX request(s) to fetch the "fill in the blanks" data.
Try this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title id="title">Loading</title>
<link href="style.css" rel="stylesheet" type="text/css"/>
<script type ="text/javascript" src="jquery.js"> </script>
<script type="text/javascript">
$(document).ready(function(){
$.get('data.php',
function(output) {
$('#dataDiv').html(output).fadeIn(250);
});
});
</script>
</head>
<body>
<div id="dataDiv"> Please wait while loading... </div>
<?php
// computations placed in data.php file
?>
Please note this requires the use of jQuery and you to move your php computations to the "data.php" file.
Try using
flush(); ob_flush();
as stated in the php manual. This brings the output as close to the browser as possible.
More information about pushing the buffer to the browser can be read in the php manual for flush();
For the beginning try placing the loader message straight after body tag. This way browser should display it asap.
Check configuration for not having compression (e.g. gzip) on by default.
Don't use tables. They are not rendered before fully loaded.
Load the content that takes forever with an Ajax call.
You need to turn output buffering off and implicitly flush output as your PHP process does its job.
You might want to checkout Output Buffering. Also note that flushing the buffer is dependent on the browser and how much it expects before it shows output.
A related question that you might find useful.
i am new to .php. I would like to know what are all the ways we can create User Controls (How we do it in asp.net). This found with include in php, but i need to pass parameters to it and use those parameters in that php include file.
I would strongly encourage you to use a php framework for web development. Standalone php is too generic and unstructured to be effective in development.
To answer your question, if you decide to use a framework such as Symfony you will find it comes equipped to handle "User Controls" using "Partials", "Components", and "Widgets".
See http://www.symfony-project.org/book/1_2/07-Inside-the-View-Layer for more information.
--
If you decide not to use a framework, then your best bet would be to put the HTML code, in an include file (e.g. myControl.inc.php) and then include it manually in your main layout using:
Again, I'd strongly discourage anyone from developing a php application without a framework.
I remember I did an experiment to mimic ASP.NET behaviour using PHP + JavaScript.
A vague example:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Strict (jaFramework-Edition)//EN//"
"http://www.joelalejandro.com/ja-xhtml/ja-xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ja="http://www.joelalejandro.com/ja-xhtml/" xml:lang="en" lang="en">
<head>
<title></title>
<script type="text/javascript" src="jaXHTML.js"></script>
</head>
<body>
<ja:MySQLServer
id="MySQL1"
ConfigFile="mysql1.conf">
</ja:MySQLServer>
<ja:Grid
id="Grid1"
UsingConnection="MySQL1"
DataSource="urminute_com.mp_songs">
</ja:Grid>
<script>
alert(window.Grid1.DataSource);
</script>
</body>
I took XHTML 1.0 Strict's definition file and added the "ja:" tags. Then, using Javascript DOM and AJAX, I replaced the tags with the content that I was required to deliver.
I don't know exactly how efficient the solution is, yet is XHTML-compliant.
Just my two cents on the subject.
Can't this be achived using "get" parameters in the include call? Something like:
include 'control.php?param1=value1';