Extracting inline javascript var in html source to a PHP array - javascript

There is some data that I need to get from a local crawled page. It's inline javascript like this:
<script type="text/javascript">
//<![CDATA[
var graph_data = {"query":{"cid":["13908"],"timestamp_from":1402531200,"timestamp_till":1402531200,"views":1138942,"data":
etc, the variable is very long but you get the idea. I want to put "graph_data" into an array called $data. What is the best way to do this? I should add this is all being done by me locally & I don't need to execute any javascript code, just extract the data.

I have make a suggestion purely as an idea with some code worth trying!
As suggested, the DOM Document may provide this much easier, but here's another possible solution for extracting...
I'm guessing that the var graph_data is a JSON string that you want to extract from the HTML page so that you can store as a PHP var. The problem is that your code doesn't show how the variable ends but I'm going to assume that a new line break would be the way to identify the end of the variable being set. It may be a semi-colon though and if it is, instead of "\r\n" try ";"
// Assuming your html code is stored in $html...
preg_match("/var graph_data[^\{]*?(\{[^\r\n]+?)/is",$html,$match);
print "<pre>";
print_r($match);
print "</pre>";
This should result in $match[1] storing the part you need.
You can try passing that into json_decode() but that's touching some wood with crossed fingers.
Good luck...

Related

How to concatenate a variable in a document.location.href path?

I have a php $_SESSION passing the name of a target directory, that is different from situation to situation. I have a javascript function to execute a file with the same name but in several different directories, depending on the string passed with $_SESSION. My code is:
<?PHP
$where = $_SESSION["where"];
?>
<script>
var where = "<?php echo $where;?>";
function goToThere() {
document.location.href = where + "/file_to_execute.php";
}
</script>
<body>
<button class="buttongreen" onclick="goToThere()">proceed</button>
</body>
Say the content of $where is "dir_a". Then clicking on buttongreen might launch function goToThere, thus going to page "dir_a/file_to_execute.php". The problem is that the goToThere function simply does not do anything. I've tried different sequences to concatenate the variable and the string, with various combinations of quotation marks, without success.
What am I doing wrong?
As stated, your code is applicable to what you are trying to do. The issue lies in the "$_SESSION['where']"
Either...
(1) You have a forward slash at the end of $_SESSION['where'] and you are adding another forward slash when concatenating.
(2) You are not doing "session_start();"
(3) The script code is not being incorporated into the body nor header (I'm not quite sure about this, but as I see it, the script code really is in no man's land so maybe???)
(4) The $_SESSION['where'] is simply not being saved
(5) The $_SESSION['where'] is simply empty
As it stands though, your code is valid as a proof-of-concept for what you are aiming to do

Converting href perl variables to normal scalar variables

I have these two variables that I am trying to compare. They both have the same value, however, one is a href variable - meaning, it's being read from a file like this
<a href=http://google.com>Variable</a>
It's read like this, but displayed as an anchor tag in the browser, so when I go to compare a value using print "$collect_zids{$key} --> $temp";I see in the browser as
Variable --> Variable
How it appears in the browser. One text another link.
I'm assuming these two values are different hence why this code does not run
if($collect_zids{$key} eq $from_picture){
print "<h1>Hello</h1>";
}
Is there a way I can convert the href variable into a normal scalar variable so that I can compare them?
Thanks!
P.S. I think Javascript might be the only way, however, I don't have any experience with it.
There is no such thing as an "href variable". You have two scalar variables. One contains plain text and the other contains HTML. Your task is to extract the text inside the HTML <a> tag from the HTML variable and to compare that text with the text from the plain text variable.
One way to do that would be to remove the HTML from the HTML variable.
my $html = '<a href=http://google.com>Variable</a>';
my $text = 'Variable';
$html =~ s/<.+?>//g;
if ($html eq $text) {
say "Equal";
} else {
say "Not Equal [$html/$text]";
}
But it cannot be emphasised enough that parsing HTML using a regular expression is very fragile and is guaranteed not to work in many cases. Far better to use a real HTML parser. HTML::Strip is made for this very purpose.
#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
use HTML::Strip;
my $html = '<a href=http://google.com>Variable</a>';
my $text = 'Variable';
my $parser = HTML::Strip->new;
$html = $parser->parse($html);
if ($html eq $text) {
say "Equal";
} else {
say "Not Equal [$html/$text]";
}
It's also worth pointing out that this is answered in the Perl FAQ
How do I remove HTML from a string?
Use HTML::Strip, or HTML::FormatText which not only removes HTML but
also attempts to do a little simple formatting of the resulting plain
text.
Update: In a comment, you say
I have no way of using these methods since I am not explicitly defining the variable.
Which is clearly not true. How a variable is initialised has no bearing whatsoever on how you can use it.
I assume your HTML text is in the variable $from_picture, so you would strip the HTML with code like this:
my $parser = HTML::Strip->new;
my $stripped = $parser->parse($from_picture);
if($collect_zids{$key} eq $stripped){
print "<h1>Hello</h1>";
}
I have no idea where you got the idea that you couldn't use my solution because I was directly initialising the variables, where you were reading the data from a file. An important skill in programming is the ability to see through complex situations and extract the relevant details. It appears you need to do some more work in this area :-)
I found the answer using the Perl module HTML::FormatText;
use HTML::FormatText;
my $formatter = HTML::FormatText->new();
my $string = HTML::FormatText->format_file("path_to_the_file"); #$string variable to hold the result and the path must be for a file.
After using the HTML::FormatText module, I was able to get the raw string that was being read, instead of it being interpreted as HTML. So, I was getting <a href=http://google.com>Variable</a> returned, instead of just Variable. After getting the raw string, I could use regex to extract the parts that I needed.
Credit to - https://metacpan.org/pod/HTML::FormatText

Add more GET data for Javascript

I am using the javascript below to send information from one website to another, but I don't know how to add more data. ?url is fine. I'm not sure how to add more data to the javascript. I would like to add an ?img, a ?title ... i tried a few times but no luck. Help please.
JavaScript
onclick="window.open('http://mysite.com/submit.?url='+(document.location.href));return false;"
PHP
$url = $_GET['url'];
Separate the parameters with &.
http://mysite.com/submit?param1=value1&param2=value2&param3=value3
You should also encode your values with encodeURI().
You wouldn't add ?moreParm...etc, you use an ampersand (&) to add additional parameters.
var url = `http://mysite.com/submit.?url=' + document.location.href;
url += '&anotherParam=foo`;
// etc.
You need to escape all parameter values accordingly.
I'd also recommend moving it into a function so your embedded JS doesn't become impossible to read.

Populate multiple fields based on select value from JSON

I am trying to populate multiple form fields with JSON data after a user makes a choice from a select box. I am very new to jquery so sorry if I am getting something elementary wrong. I don't want to include the JSON in my html because it will be changing often and it is a very large file. Here is what I have:
<script type="text/javascript">
$.ajax({
url: '../includes/json/data/abbc.json',
success: function(data) {
$("#rig").html("<option >--select--</option>");
$.each(rigdetaillist.rigs,function(){
var rigName=this.rig;
$("#rig").append("<option value=" +rigName + ">" +rigName + "</option>");
});
$("#rig").change(function(){
var rigValue=$(this).val();
$.each(rigdetaillist.rigs,function(i){
var rigName=this.rig;
if (rigName==rigValue){
$(".rigdetail").val("");
$.each(rigdetaillist.rigs[i].rigdteails,function(i){
var rigdetailName=this.rigdetail
$(".rigdetail").eq(i).val(rigdetailName);
});
}
});
});
}
});
</script>
There are a few things here that you want to consider, one of the major things being that you want to do as little DOM manipulation as possible, as its one of the major causes of performance issues.
Unfortunately, I don't have the time to rewrite your code and give you what you should write. Although I do have the time to explain to you what you need to consider and hopefully it'll lead you down the right path :-)
(1) Your data var in success: function (data) { isn't being used. I'm assuming you mean it to be used for the rigdetaillist, most likely something like var rigdetaillist = data['rigdetaillist']; depending on your JSON. In either case, data is your json return value, of which you aren't referencing at all...which you probably need to. :-)
(2) As I said earlier, you want to do as little DOM manipulation as possible. So you probably will want to either pull out the #rig and cache it in javascript (to be put back into the DOM later), or create a new $(<script>) obj and then copy its html into $('#rig')'s when you are done. I would suggest creating the new script tag as detaching is a very nice feature of jquery, but can have its problems (such as when you go to append it back in, it appends at the bottom of the container instead of where you originally had it).
(3) The change function is being created on every json request. There is more than likely a way to globalize that so you don't have to create a new change function every time. You could possibly store the necessary information in a global variable and just reference that variable in change function, or I'm sure you could do some other really cool scope tricks, but that would be the simplist.

What's the best practice to transfer a variable value to javascript from server?

I'm developing a pet project with jQuery. Now the application requires some variable value is transferred to client javascript when the page is loaded. I'm wondering what's the best practice to do it.
I can image to do it in two ways. First, render it to be a javascript variable in the page.
<script> <?php echo "var maxid = $maxid;"?> </script>
Which means the client will see
<script> var maxid = <somevar>; </script>
Second, assign it to be an attribute of one element.
<div maxid="<php echo $maxid >" />
Which approach is better? Is there any other way to do it?
For the sake of valid html I'd go with the first method, though it really doesn't matter as long as it gets the job done.
<script>
$(function() {
var max_id = <?php echo $max_id;?>;
});
</script>
I use JSON string to pass values to client
Take a look at this example http://blog.reindel.com/2007/10/02/parse-json-with-jquery-and-javascript/
I rarely have to pass just one variable ... I tend to have a whole set of information, in which case I use:
var myAwesomeStuff = <?php echo json_encode($myArrayOfAwesomeInformation); ?>
No round trip to the server, as mentioned earlier with JSON.
-- Edit:
Just so it's clear, your "question" is asking something totally different than your "code". You'll need to clarify, my post below talks about the "question".
-- Old:
I generally return the complete HTML to be rendered, in the pages that the ajax calls to.
The reason for this is that I don't have to duplicate layout logic in JavaScript, and it ends up being generally useful for just keeping the JavaScript trivial, and of the form of setting HTML/text content of relevant placeholders.
It comes at the cost of transferring more data, but for me, I'm happy to make this trade-off.
I would render it to be a javascript variable (your first alternative). This seems to be a common approach.
First method is better because you will consume less memory and CPU with a simple variable. Going the DIV way, you will consume a DOM element and a DOM node search to read the value.

Categories