Building html structure in php or javascript? - php

I've been doing a lot of ajax calls and using the returned data to build html with javascript. However, I've noticed some people are returning the constructed html in the ajax calls since they're doing it all in php.
What is the preferred method? I have a bunch of stuff already using javascript, so I guess I would prefer not changing everything to use just php. But, I'm assuming php would be more "secure."?
The following is what I've been doing:
$main_frag = $("<div class='order-container'/>");
$contact_frag = $("<div class='group'><div class='line-data'>Name: "+data.name+"</div><div class='line-data'>Email: "+data.email+"</div><div class='line-data'>Phone: "+data.phone+"</div></div>");
$address_frag = $("<div class='group'><div class='line-data'>Address 1: "+data.address_one+"</div><div class='line-data'>Address 2: "+address2+"</div><div class='line-data'>City: "+data.city+"</div><div class='line-data'>Province: "+data.province+"</div><div class='line-data'>Postal Code: "+data.postal+"</div></div>");
etc..
I just want to hear the opinions of the community.

Look at some Javascript template solutions, such as Underscore.js (http://underscorejs.org/). Which is just an example, there's many. This should give you more separation and flexibility than just JQuery.
Also for more complex Javascript logic, you should consider to start using some Javascript MVC framework, such as Backbone.js (http://backbonejs.org/). Again there's many.
For browser / server communication, you can use JSON.

I don't think that retrieving them in parts or as a whole structure will have difference. both of them can be changed either via MITB ( Man in The Browser ) or even simple using developr tools that let you modify JS and HTML in the Browser..

IMO mustache is a good choice: http://coenraets.org/blog/2011/12/tutorial-html-templates-with-mustache-js/
with mustache you can use templates within your javascript to generate the markup

Related

Post into a textarea and then get the result from another textarea

Let say I have this JS code:
function plus2(){
print (2+2);
};
So I want to post this code into textarea#input at http://dean.edwards.name/packer/ and then get the result back from textarea#output.
Can use PHP Curl, Shell Curl or JQuery to do the job?
P.S.: By the way, there is bug in PHP Packer port and that's whay I am not using it.
PHP implementation of JSMin works well for me. Also, if you have server-side JS interpreter you can use UglifyJS, it's fast and provides a good compression.
Not really, no. It would need to be passed to a JavaScript engine at some point, so PHP/cURL is not going to be enough.
I recommend using an alternative server-side implementation of packer, or perhaps even YUI Compressor.

How can I take a snapshot of a wep page's DOM structure?

I need to compare a webpage's DOM structure at various points in point. What are the ways to retrieve and snapshot it.
I need the DOM on server-side for processing.
I basically need to track structural changes to a webpage. Such as removing of a div tag, or inserting a p tag. Changing data (innerHTML) on those tags should not be seen as a difference.
$html_page = file_get_contents("http://awesomesite.com");
$html_dom = new DOMDocument();
$html_dom->loadHTML($html_page);
That uses PHP DOM. Very simple and actually a bit fun to use. Reference
EDIT: After clarification, a better answer lies here.
Perform the following steps on server-side:
Retrieve a snapshot of the webpage via HTTP GET
Save consecutive snapshots of a page with different names for later comparison
Compare the files with an HTML-aware diff tool (see HtmlDiff tool listing page on ESW wiki).
As a proof-of-concept example with Linux shell, you can perform this comparison as follows:
wget --output-document=snapshot1.html http://example.com/
wget --output-document=snapshot2.html http://example.com/
diff snapshot1.html snapshot2.html
You can of course wrap up these commands into a server-side program or a script.
For PHP, I would suggest you to take a look at daisydiff-php. It readily provides a PHP class that enables you to easily create an HTML-aware diff tool. Example:
<?
require_once('HTMLDiff.php');
$file1 = file_get_contents('snapshot1.html');
$file2 = file_get_contents('snapshot1.html');
HTMLDiffer->htmlDiffer( $file1, $file2 );
?>
Note that with file_get_contents, you can also retrieve data from a given URL as well.
Note that DaisyDiff itself is very fine tool for visualisation of structural changes as well.
If you use firefox, firebug lets you view the DOM structure of any web page.

PHP in HTML <Script>

I was viewing a Appcelerator Titanium Video Tutorial and I saw they used syntax like
<script type="text/php">
...
global $window, $document;
mysql_connect(...) or die $window->alert('...');
$document.getElementById('xxx');
...
</script>
so I have a few questions. Is it any difference if I use <?php ?>
without setting $window and $document - won't they be "unset" variables?
I guess I can use (basic, not jQuery for example) Javascript functions like alert and getElementById() in PHP too?
In this case, they can only be "undefined", not "unset". However, they have "global" prefix, so there is a chance they are defined in some other code, possibly even outside your file.
$window->alert(...) probably outputs HTML that reads as javascript alert or a similar function.
You cannot use javascript alert() in PHP, because it is not PHP function.
As far as PHP is concerned, there is no JavaScript — only text.
$window and $document are just variables defined elsewhere in the PHP. $window appears to be an object with some methods that output text (text that happens to include JS syntax) while $document appears to be a string.
They will be undefined if they haven't been defined already.
You can write any JS function you like as normal text. If you want to use an object to generate it, then you need to have an object that is aware of that function.
For a regular web app, the code you're showing makes no sense whatsoever, because PHP runs on the server and JavaScript runs on the client. PHP is used to build the HTML code which forms the DOM tree on which JavaScript functions like getElementById() operate, so it's completely impossible to use them meaningfully within PHP code.
However, a cursory investigation reveals that Appcelerator Titanium is a sort of runtime that is meant to run applications using web technology completely on the client. In such a runtime, it is possible that the PHP code is running in the context of an already complete HTML DOM and interacts with it via JavaScript-like bridge functions. But that's completely different from how PHP normally works.

What are the advantages to putting your Javascript in a .php file?

I occasionally come across pages where some Javascript is included via a PHP file:
<html>
<head>
<script type="text/javascript" src="fake_js.php"></script>
</head>
<body onload="handleLoad();">
</body>
</html>
where the contents of fake_js.php might look something like this:
<?php header('Content-type: text/javascript') ?>
function handleLoad() {
alert('I loaded');
}
What are the advantages (or disadvantages) to including Javascript like this?
It makes it easy to set javascript variables from the server side.
var foo = <?=$foo?>
I usually have one php/javascript file in my projects that I use define any variables that need to be used in javascript. That way I can access constants used on the server-side (css colors, non-sensitive site properties, etc) easily in javascript.
Edit: For example here's a copy of my config.js.php file from the project I'm currently working on.
<?php
require_once "libs/config.php";
if (!function_exists("json_encode")) {
require_once "libs/JSON.php";
}
header("Content-type: text/javascript");
echo "var COLORS = ". json_encode($CSS_COLORS) .";\n";
echo "var DEBUG = ". ((DEBUG == true) ? "true" : "false").";";
?>
If you don't need it, don't use it:
The first thing you need to keep in
mind is YAGNI. You Ain't Gonna
Need It. Until a certain feature,
principle, or guideline becomes useful
and relevant, don't use it.
Disadvantages:
Added complexity
Slower than static files.
Caching problems (server side)
Scalability issues (load balancers offload static files from the heavy PHP/Apache etc processes)
Advantages:
User specific javascript - Can be achieved by initializing with the right variables / parameters in the <head> </head> section of the HTML
Page specific javascript - JS could also be generalized to use parameters
JSON created from database (usually requested via AJAX)
Unless the javascript is truely unique (i.e. JSON, parameters/variables) you don't gain much. But in every case you should minimize the amount of JS generated on the server side and maximize the amount of code in the static files. Don't forget that if it's dynamic, it has to be generated/downloaded again and again so it's not wanted for it to be a heavy process.
Also:
This could also be used to minimize the amount of server configuration (for example if the web server doesn't serve file.js with the correct content type)
There's no benefit for the example you gave above (beyond peculiar deployment scenarios where you have access to .php files and not .js files, which would be insane but not unheard of).
That said, this approach allows you to pass the JS through the php parser - which means you can generate your JS dynamically based on server variables.
Agree with tj111. Apart from what tj mentioned, I also found php-generated javascripts a great weapon to fight the browser's caching tricks. Not that long ago I was cursing the whole javascript for its being constantly cached by the browser. Refreshing the page helped me not, had to clear the whole cache in order to force the browser to reload the javascript files. As soon as I built a php wall in front of my javascripts:
fake_js.php:
<?php
header('Content-type: text/javascript')
include('the_real_javascript.js');
?>
A fresh new javascript would always show up at the client side. However this approach is obviously only good in the development phase, when it can save the developer quite some headache to have the correct javascript loaded in the browser. Of course when connecting to localhost, the penalty of repeatedly loading the same file is not as big.
In a live web application/site client-side caching is welcome to reduce network traffic and overall server load.
Advantage (not PHP specific - I used this technique in EmbPerl and JSP) would be the ability to dynamically generate or tweak/customize the JavaScript code on the server side.
An example usage would be population of an array based on the contents of a DB table.
Or application of localization techniques.
If you don't have full server access and can't turn on gzip encoding then it's pretty useful to put the following in your javascript file (note: will need to be renamed to file.js.php or parsed as PHP through .htaccess directive):
<?php
ob_start( 'ob_gzhandler' );
header("Content-type: text/javascript");
?>
// put all your regular javascript below...
You could also use it for better cache control, visitor tracking, etc in lieu of server-controlled solutions.
Absolutely none, IMHO. I use a js framework that I wrote to handle the setting of whatever server-side variables I need to have access to. It is essentially the same as embedding PHP in JavaScript, but much less ambiguous. Using this method allows you to also completely separate server-side logic and html away from javascript. This results in much cleaner, more organized and lowly-coupled modular code.
You could do something like this in your html:
<script type="text/javascript">
registry = {
myString : '<?php echo $somePhpString; ?>',
myInt : <?php echo $somePhpInteger; ?>
}
</script>
And then do something like this in your js:
if (registry.myInt === 1) {
alert(registry.myString);
}

Scraping Library for PHP - phpQuery?

I'm looking for a PHP library that allows me to scrap webpages and takes care about all the cookies and prefilling the forms with the default values, that's what annoys me the most.
I'm tired of having to match every single input element with xpath and I would love if something better existed. I've come across phpQuery but the manual isn't much clear and I can't find out how to make POST requests.
Can someone help me? Thanks.
#Jonathan Fingland:
In the example provided by the manual for browserGet() we have:
require_once('phpQuery/phpQuery.php');
phpQuery::browserGet('http://google.com/', 'success1');
function success1($browser)
{
$browser->WebBrowser('success2')
->find('input[name=q]')->val('search phrase')
->parents('form')
->submit();
}
function success2($browser)
{
echo $browser;
}
I suppose all the other fields are scrapped and send back in the GET request, I want to do the same with the phpQuery::browserPost() method but I don't know how to do it. The form I'm trying to scrape has a input token and I would love if phpQuery could be smart enough to scrape the token and just let me change the other fields (in this case username and password), submiting via POST everything.
PS: Rest assured, this is not going to be used for spamming.
See http://code.google.com/p/phpquery/wiki/Ajax and in particular:
phpQuery::post($url, $data, $callback, $type)
and
# data Object, String which defines the data parameter as being either an Object or a String. POST requests should be possible using query string format, e.g.:
$data = "username=Jon&password=123456";
$url = "http://www.mysite.com/login.php";
phpQuery::post($url, $data, $callback, $type)
as phpQuery is a jQuery port the method signature is the same (the docs link directly to the jquery site -- http://docs.jquery.com/Ajax/jQuery.post)
Edit
Two things:
There is also a phpQuery::browserPost function which might meet your needs better.
However, also note that the success2 callback is only called on the submit() or click() methods so you can fill in all of the form fields prior to that.
e.g.
require_once('phpQuery/phpQuery.php');
phpQuery::browserGet('http://www.mysite.com/login.php', 'success1');
function success1($browser) {
$handle = $browser
->WebBrowser('success2');
$handle
->find('input[name=username]')
->val('Jon');
$handle
->find('input[name=password]')
->val('123456');
->parents('form')
->submit();
}
function success2($browser) {
print $browser;
}
(Note that this has not been tested, but should work)
I've used SimpleTest's ScriptableBrowser for such stuff in the past. It's part of the SimpleTest testing framework, but you can use it stand-alone.
I would use a dedicated library for parsing HTML files and a dedicated library for processing HTTP requests. Using the same library for both seems like a bad idea, IMO.
For processing HTTP requests, check out eg. Httpful, Unirest, Requests or Guzzle. Guzzle is especially popular these days, but in the end, whichever library works best for you is still a matter of personal taste.
For parsing HTML files I would recommend a library that I wrote myself : DOM-Query. It allows you to (1) load an HTML file and then (2) select or change parts of your HTML pretty much the same way you'd do it if you'd be using jQuery in a frontend app.

Categories