How can I parse html that includes javascript code [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Server side browser that can execute JavaScript
Execute javascript in PHP
How can I parse HTML that includes JavaScript code, preferably with PHP script if possible.
As an example:
link
should be replaced by the appropriate value the JavaScript function returns, e.g.
link
A more complex example would be a saved facebook html page which is littered with loads of javascript code.
Summarized:
Return a DOM for a page with html+javascript

You could just give this link an ID. Not that this solution is javascript, jQuery.
So give the link an Id, or class.
$('.link').each(function() {
var functionName = 'link';
var start = $(this).attr('href');
remove = start.replace('javascript:', ''),
get = remove.replace(new RegExp('^'+functionName+'\(((.+\,?)+)\)\;?', 'g'), function(a, b, c) {
return c.replace(/[()']/g,'')
}), args = get.split(",");
//read settings
var firstArgument = args[0];
$(this).attr('href', firstArgument)
});​
Please note this is just an example.
Usage:
​<a class="link" href="javascript:link('http://facebook.com')"​>Hi</a>​​​​​​​​​​​​​​​​​​
That would make the actual link http://facebook.com.
Adding new arguments this way is difficult though and its not really professional.
But this should do what you want, I just didn't know what your link function actually doesnt so I didnt add the argument with the boolean. Of course this could get far more complex and you could write a function that could do this too but I just wrote this for your really quick.
Check out the example.

You can't. When clicked, javascript: URIs just call the function and let it do whatever it wants (which MIGHT include navigating somewhere); they don't expect or use a return value. In many use cases, the function may not cause any navigation at all.

DomDocument can be used to parse HTML in PHP including JS: http://php.net/manual/en/class.domdocument.php
You can "render" the JS with the HTML by merely echoing out the output of a cURL or wget (or whatever you use) without escaping the HTML characters. For external JS you are going to need to build a crawler which will crawl the DomDocument script tags and fetch the appropiate URL and load it into a position that is accessible unless you use it directly from their servers but I don't think they will be too happy about that.
Edit: My new answer after some comments is: no

Related

Using RGraph to poll data from a Postgres DB and update using AJAX/JSON

I'm a bit out of depth on this one so I hope someone has some insight. :)
I'm attempting to update a div using AJAX. The AJAX call sends a dropdown selection's value to a PHP file, which will be performing a pgsql query to grab some data. I've read in the RGraph tutorials that this data needs to be formatted to a JSON format so that RGraph can interpret it, and then fed to the JS that runs the RGraph views.
This question might actually be 2 separate questions, but I'll ask anyway:
Is there a standard way to grab the query's results in PHP and output them into a JSON format?
Where would I want to trigger the JS that uses the JSON data? I've tried hardcoding some initial data but the graphs don't seem to show up. However, I know the jQuery is performing the AJAX calls correctly because I see the div update (with an in-between "Loading..." message and then back to blank, indicating to me a null response), so I think I'm just not scoping this properly.
P.S. No, this time I'm not making a $_POST/$_GET mistake.
Any help would be appreciated. Thanks!
EDIT 1: Got this one. It was actually way easier than I thought. Still not scoping properly, however. Any help with how RGraph grabs a JSON object and displays it as a graph, and how to use AJAX to refresh the div with a new graph?
There's some SVG based AJAX demo pages here:
There was a bunch of links to the SVG basic AJAX demos here, but now the demos are no longer online - they are in the download archive. So download it here: https://www.rgraph.net/download.html#stable
There's a JSON documentation page here:
https://www.rgraph.net/svg/docs/the-svg-ajax-functions.html
And the code example from it is this:
<script>
GLOBALS = {};
function draw()
{
RGraph.SVG.AJAX.getJSON('/ajax/getdata.html?json', function (json)
{
if (GLOBALS.bar) {
RGraph.SVG.clear(GLOBALS.bar.svg);
}
GLOBALS.bar = new RGraph.SVG.Bar({
id: 'chart-container',
data: json.data,
options: {
// Add your own options to configure the chart
}
}).draw();
});
}
draw();
</script>
If you follow this example, create a page on your website that gets the data from your database and outputs it like this page does:
https://www.rgraph.net/getdata.html?json
Note that there's no HTML output by that page - just the JSON.
Then you can fetch that page using the RGraph.SVG.AJAX.getJSON() function like the code above does - from your webpage that has the chart on it - eg foo.html
So the foo.html is what would contain that RGraph code above.
And if you wanted it to repeat then you could add a timer so that subsequent fetches update it:
setTimeout(function ()
{
draw();
}, 1000);
I think that covers everything. I've probably left something out though.

html object to call php and return string

I want to call a php script (with args) from HTML and to process the returned data
I tried various flavours of :
<object id=test1 data="object.php" type="text/plain">
where object.php just returns a string, like
<?php print "firstText:Hello World";?>
I can't work out how to retrieve the returned string.
I was hoping to find it in something like
document.getElementById("test1").firstText
But no joy
Why am I doing this, you ask?
I'd like to get the page working interactively between the user and the server, avoiding the repainting of the browser window that comes with re-submitting with POST/GET.
Thanks for your responses.
I'm not happy using JQuery - another layer beyond my control
I have eventually found the returned text in
document.getElementById("test1").contentDocument.body.firstChild.textContent
which I can then work with.
Thanks
Use AJAX. Here's an example using jQuery:
$.get('yourpage.php', function(response){
// response contains the string returned by your PHP page.
});
PaulPros idea is probably your best method. Don't forget to include jQuery.
Is there any reason you could not just make the .HTML a .php file and include your script?

Joomla: Extract javascript documentReady callback functions on AJAX success

I'm building a plugin for Joomla that ajaxifies the front-end. I've been using a script from balupton's balupton's history js page, and it works fine, except any javascript using the .ready() function will not execute, as the DOM has already been loaded.
What I would like to do is somehow search the scripts being requested, and then strip out the functions that use ready(), and then execute them.
In the script, we already grab all the scripts referenced in each html file, and we have access to the text inside each js file:
// Add the scripts
$scripts.each(function(){
var $script = $(this), scriptText = $script.text(), scriptNode = document.createElement('script');
scriptNode.appendChild(document.createTextNode(scriptText));
contentNode.appendChild(scriptNode);
});
I am considering doing a simple string replace, but then again, I'm not sure if there's a better way of going about doing this, as it will of course require regex due to the possibilities of varying callback functions.
Thanks in advance.
I don't think that changing the JS is the correct way. Have you tried simply firing the ready function manually?
jQuery.ready();

how to pass variable from php template to javascript [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I have a page where I want to display some points on map. I have small templates (like Smarty, but lighter) and there in template I have variable $points, that consists of coordinates of points I need. I need to pass them to javascript (because only javascript can render that map with points).
I have 3 variants of doing it. Can you tell, what is best?
1th way: (Template inserting javascript-tags with global variable)
tpl.php file:
<script>
MAP_POINTS = <?php echo json_encode($this->points); ?>;
</script>
.js file
function renderMap(){
var points = MAP_POINTS; // using global. Is it really bad? or who cares? =))
}
2nd way: (Passing variable through the HTML element)
tpl.php.file
<input type="hidden"
value="<?php echo json_encode($this->points); ?>"
id="map_points_container">
.js file
function renderMap(){
// without globals, but needed to be parsed on local side
var points = $.parseJSON ( $( "#map_points_container" ).val() );
}
3rd way: (AJAX-way)
I don't pass $this->points from template file at all. I have another .php file that handles all my AJAX requests:
Ajaxing.php
function get_map_points($params){
// some operations
return json_encode ($map_points);
}
And than on local side I'll have something like this:
.js file
$.post ( 'ajaxing.php', params,
function(points){
renderMap(points);
}, 'json');
The third way is usual, but if I already pass some values from template to local page, then I can pass and map points too. In fact, I don't need to make another request for only this map points (that's why I don't like third way)
But may be you can advise me another way? a better way?
The way I choosed:
1th way with little remarks. All my 'map-rendering' code is in another file and it's like:
$(function(){
MAP_APP = {};
MAP_APP.some_prop = null; // some properties
MAP_APP.some_method = function(){}; // some methods
});
So in template file I only have to extend my MAP_APP object:
<script>
MAP_APP.points = <?php echo json_encode($this->points); ?>;
</script>
Yes, global variable. But it's like namespace of whole application.
Thanks to everybody.
The first way is definitely the least complicated and fastest.
The second one adds an additional processing step (the parseJSON()) that isn't necessary.
The third way is good if you're dealing with lots of data that is optional (i.e. is needed only if the user requests it, and it isn't 100% sure whether that will happen) or dynamic. It creates a new request though, and is not going to be immediately available.
If you don't want to use globals, you could e.g. wrap your JavaScript functions into an object, and populate an object property from PHP:
<script>
MyObject.MAP_POINTS = <?php echo json_encode($this->points); ?>;
</script>
There is another funky way of passing variables in a js external file :)
Your PHP file:
<script type='text/javascript' src='script.js?id=0&some=<?php echo $whatever?>'></script>
and inside your script.js you can retrieve those values:
var scripts = document.getElementsByTagName('scripts');
// get your current script;
for (var i=0,l=scripts.length;i<l;i++){
if(scripts[i].src.indexOf('script.js') !== -1) { // or your script name
var query = scripts[i].src.substr(scripts[i].src.indexOf('?')+1);
// now you can split the query and access the values you want
....
}
}
The first one is most efficient and fastest. The second one is funky. The third one is also fine.
The first because it does not require any other requests. The second one is a bit odd, I would not use that kind of constructs, but that does not mean you can't. The third one is also fine, but you should think about if AJAX is the way to go. If you application requires multiple requests for points for different locations, then it might be the most efficient way to go.
I would go with your second method since you don't want to use AJAX for it (and it seems odd to use AJAX for something you already have in the current page). You want to limit the number of global variables in your JavaScript because everything in your JavaScript will create an instance of each global variable and thus decrease your performance.
I forgot the name of the person, but the man who was heading on optimization at Yahoo! and then went to work for Google gave a lecture about JavaScript optimization, and this was one of his points.
EDIT: Found the link: http://sites.google.com/site/io/even-faster-web-sites
Speed wise 1st way is the best way.
But the best way is to create an XML output from PHP and loading that xml into Javascript via Ajax. The best example of this is article given on google maps documentation - http://code.google.com/apis/maps/articles/phpsqlajax_v3.html
Another way:
In script_that_defines_renderMap.js:
function renderMap(points) {
// take "points" as an argument
}
And then:
<script src="script_that_defines_renderMap.js"/>
<script>
var mapPoints = <?php echo json_encode($this->points); ?>;
renderMap(mapPoints);
</script>
No global variable, no problem.

jQuery: print_r() display equivalent? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript data formatting/pretty printer
I am getting a bit tired of looking at unformatted json blobs in FireBug.
Does anyone know an equivalent to PHP's print_r() for jQuery?
Something that would recursively make a display string from an object or array, that I could display on the page for quick debugging?
Thanks!
console.log is what I most often use when debugging.
I was able to find this jQuery extension though.
You could use very easily reflection to list all properties, methods and values.
For Gecko based browsers you can use the .toSource() method:
var data = new Object();
data["firstname"] = "John";
data["lastname"] = "Smith";
data["age"] = 21;
alert(data.toSource()); //Will return "({firstname:"John", lastname:"Smith", age:21})"
But since you use Firebug, why not just use console.log?
How about something like:
<script src='http://code.jquery.com/jquery-latest.js'></script>
function print_r(o){
return JSON.stringify(o,null,'\t').replace(/\n/g,'<br>').replace(/\t/g,' '); }
You can also do
console.log("a = %o, b = %o", a, b);
where a and b are objects.
$.each(myobject, function(key, element) {
alert('key: ' + key + '\n' + 'value: ' + element);
});
This does the work for me. :)
I've made a jQuery plugin for the equivalent of
<pre>
<?php echo print_r($data) ?>
</pre>
You can download it at https://github.com/tomasvanrijsse/jQuery.dump
Top comment has a broken link to the console.log documentation for Firebug, so here is a link to the wiki article about Console. I started using it and am quite satisfied with it as an alternative to PHP's print_r().
Also of note is that Firebug gives you access to returned JSON objects even without you manually logging them:
In the console you can see the url of
the AJAX response.
Click the triangle to expand the response and see details.
Click the JSON tab in the details.
You will see the response data organized with expansion triangles.
This method take a couple more clicks to get at the data but doesn't require any additions in your actual javascript and doesn't shift your focus in Firebug out of the console (using console.log creates a link to the DOM section of firebug, forcing you to click back to console after).
For my money I'd rather click a couple more times when I want to inspect rather than mess around with the log, especially since keeps the console neat by not adding any additional cruft.
Look at this: http://phpjs.org/functions/index and find for print_r or use console.log() with firebug.

Categories