Get JavaScript var value from a web page - javascript

In a php program, I have a web page in $page variable.
...
$page = file_get_contents("http://www.autostrade.it/autostrade-gis/gis.do", false, $context);
$dom = new DOMDocument;
$dom->loadHTML($);
$xpath = new DOMXPath($dom);
...
In this page there are some javascript and I want to take the json data contained in the variable called "evtsVar".
...
<script ...>
...
</script>
<script ...>
...
var evtsVar = {json data}
...
</script>
Use Xpath query is the right method? How can I do to take this variable value?
Thank you all and sorry for my English.

This is a very specific question about a certain page. I've analyzed the page you have provided the link. There is a variable within a script tag. You want to get that in JSON.
I've used jquery for the solution, strongly recommended for you too.
Get the page first:
<?
$page = file_get_contents("http://www.autostrade.it/autostrade-gis/gis.do", false, $context);
?>
Then get the page in a javascript variable:
var page = <?php echo json_encode( $page ) ?>;
Now we have the page, we should find the string starting with "var evtsVar = ", ending with ";":
var preString = "var evtsVar = ";
var postString = ";";
var preIndex = page.indexOf( preString );
var searchIndex = preIndex + page.substring( preIndex ).indexOf( postString );
var evtsString = page.slice( preIndex + preString.length , searchIndex );
Now get parse the string to a json object and print:
var evtsVar = JSON.parse( evtsString );
console.log( evtsVar );
Tested, works.

Related

PHP 5.4.16 DOMDocument removes parts of Javascript

I try to load an HTML page from a remote server into a PHP script, which should manipulate the HTML with the DOMDocument class. But I have seen, that the DOMDocument class removes some parts of the Javascript, which comes with the HTML page. There are some things like:
<script type="text/javascript">
//...
function printJSPage() {
var printwin=window.open('','haha','top=100,left=100,width=800,height=600');
printwin.document.writeln(' <table border="0" cellspacing="5" cellpadding="0" width="100%">');
printwin.document.writeln(' <tr>');
printwin.document.writeln(' <td align="left" valign="bottom">');
//...
printwin.document.writeln('</td>');
//...
}
</script>
But the DOMDocument changes i.e. the line
printwin.document.writeln('</td>');
to
printwin.document.writeln(' ');
and also a lot of others things (i.e. the last script tag is no longer there. As the result I get a complete destroyed page, which I cannot send further.
So I think, DOMDocument has problems with the HTML tags within the Javascript code and tries to correct the code, to produce a well-formed document. Can I prevent the Javascript parsing within DOMDocument?
The PHP code fragment is:
$stdin = file_get_contents('php://stdin');
$dom = new \DOMDocument();
#$dom->loadHTML($stdin);
return $dom->saveHTML(); // will produce wrong HTML
//return $stdin; // will produce correct HTML
I have stored both HTML versions and have compared both with Meld.
I also have tested
#$dom->loadXML($stdin);
return $dom->saveHTML();
but I don't get any things back from the object.
Here's a hack that might be helpful. The idea is to replace the script contents with a string that's guaranteed to be valid HTML and unique then replace it back.
It replaces all contents inside script tags with the MD5 of those contents and then replaces them back.
$scriptContainer = [];
$str = preg_replace_callback ("#<script([^>]*)>(.*?)</script>#s", function ($matches) use (&$scriptContainer) {
$scriptContainer[md5($matches[2])] = $matches[2];
return "<script".$matches[1].">".md5($matches[2])."</script>";
}, $str);
$dom = new \DOMDocument();
#$dom->loadHTML($str);
$final = strtr($dom->saveHTML(), $scriptContainer);
Here strtr is just convenient due to the way the array is formatted, using str_replace(array_keys($scriptContainer), $scriptContainer, $dom->saveHTML()) would also work.
I find it very suprising that PHP does not properly parse HTML content. It seems to instead be parsing XML content (wrongly so as well because CDATA content is parsed instead of being treated literally). However it is what it is and if you want a real document parser then you should probably look into a Node.js solution with jsdom
If you have a <script> within a <script>, the following (not so smart) solution will handle that. There is still a problem: if the <script> tags are not balanced, the solution will not work. This could occur, if your Javascript uses String.fromCharCode to print the String </script>.
$scriptContainer = array();
function getPosition($tag) {
return $tag[0][1];
}
function getContent($tag) {
return $tag[0][0];
}
function isStart($tag) {
$x = getContent($tag);
return ($x[0].$x[1] === "<s");
}
function isEnd($tag) {
$x = getContent($tag);
return ($x[0].$x[1] === "</");
}
function mask($str, $scripts) {
global $scriptContainer;
$res = "";
$start = null;
$stop = null;
$idx = 0;
$count = 0;
foreach ($scripts as $tag) {
if (isStart($tag)) {
$count++;
$start = ($start === null) ? $tag : $start;
}
if (isEnd($tag)) {
$count--;
$stop = ($count == 0) ? $tag : $stop;
}
if ($start !== null && $stop !== null) {
$res .= substr($str, $idx, getPosition($start) - $idx);
$res .= getContent($start);
$code = substr($str, getPosition($start) + strlen(getContent($start)), getPosition($stop) - getPosition($start) - strlen(getContent($start)));
$hash = md5($code);
$res .= $hash;
$res .= getContent($stop);
$scriptContainer[$hash] = $code;
$idx = getPosition($stop) + strlen(getContent($stop));
$start = null;
$stop = null;
}
}
$res .= substr($str, $idx);
return $res;
}
preg_match_all("#\<script[^\>]*\>|\<\/script\>#s", $html, $scripts, PREG_OFFSET_CAPTURE|PREG_SET_ORDER);
$html = mask($html, $scripts);
libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadHTML($html);
libxml_use_internal_errors(false);
// handle some things within DOM
echo strtr($dom->saveHTML(), $scriptContainer);
If you replace the "script" String within the preg_match_all with "style" you can also mask the CSS styles, which can contain tag names too (i.e. within comments).

PHP file ouputs the javascript code itself and not running

I'm trying to create an Edit Modal. Provided that I have the html code for this, I write this javascript/jquery code:
<script type='text/javascript'>
$(function() {
<?php
$q = $db->query("select * from tblUnit where unitStatus <> '2'");
while($r = $q->fetch(PDO::FETCH_ASSOC)){
echo " <script type'text/javascript'> alert('1');</script>";
$unitID = $r['unitID'];
$unitStatus = $r['unitStatus'];
$unitNumber = $r['unitNumber'];
$floorNumber = $r['floorCode'];
$unitType = $r['unitType'];
$t = $db->query("select floorLevel, floor_buildingID from tblFloors where floorLevel = '$floorNumber'");
while( $u = $t->fetch(PDO::FETCH_ASSOC)){
$floorLevel = $u['floorLevel'];
$floor_buildingID = $u['floor_buildingID'];
$w = $db->query("select unitTypeName from tblUnitType where unitTypeID = $unitType");
while($x = $w->fetch(PDO::FETCH_ASSOC)){
$unitTypeName = $x['unitTypeName'];
?>
$("#editModal<?php echo $unitID; ?>").click(function(){
$("#editUnitNumber").val("<?php echo $unitNumber;?>");
$("#editUnitType").val("<?php echo $unitType; ?>").material_select('update');
$("#editFloorNumber").val("<?php echo $floorNumber; ?>");
});
<?php }}}?>
});
The code above is used to write the data from the modal, but instead it output this:
$("#editModal5").click(function(){ $("#editUnitNumber").val("12002"); $("#editUnitType").val("4").material_select('update'); $("#editFloorNumber").val("12"); }); });
How do I solve that? What causes this?
Use json to pass data from php to javascript, instead of echoing everything out in one place. It may seem an overkill but it's readable, and is more beneficial on the long run.
The code below is not tested, but it should give you a general idea on how to approach these things. I did not include the second and third queries within the first while loop. You can nest the results from those queries in the $unit array and access the relevant data via additional loops in javascript.
Also, ideally you wouldn't just echo out the decoded array right after the php, a better solution would be to call a function in the footer, that would generate a script tag with all data that is used by javascript. Another approach is to use AJAX and get a json response only when you need it, then you would feed that same json to the loop.
<?php
$q = $db->query("select * from tblUnit where unitStatus <> '2'");
$units = [];
while($r = $q->fetch(PDO::FETCH_ASSOC)){
$unit = [
'unitID' => $r['unitID'],
'unitStatus' => $r['unitStatus'],
'unitNumber' => $r['unitNumber'],
'floorNumber' => $r['floorCode'],
'unitType' => $r['unitType']
];
$units[] = $unit;
}
$units_json = json_encode($units);
?>
<script type='text/javascript'>
$(function() {
var units = '<?php echo $units_json ?>';
var units_array = JSON.parse(units);
// do some validation here
for (var i = 0; i < units_array.length; i++) {
// do some validation here
$("#editModal" + units_array[i].unitID).click(function(){
$("#editUnitNumber").val(units_array[i].unitNumber);
$("#editUnitType").val(units_array[i].unitType).material_select('update');
$("#editFloorNumber").val(units_array[i].floorNumber);
});
};
});
</script>

How to do Onclick Javascript Session a part of variable from for loop and reposting through ajax

First let me apologize for the confusing heading, i am not very sure on how to phrase it with my situation, it is a little complex.
The situation explained with an image.
1.) First i have a while loop of JSON data coming in from php( it contains multiple userid etc).
2.) Ajax picks up those data and place them into html with a button to each id.
3.) When the button on click, it sends out that specific id to another php.
I have no idea how to get the data[i].userid and data[i].listingid from the ajax and send it out again.
Thanks for your time
Image
First php
$result=mysqli_query($con,"SELECT * FROM list WHERE Listingid = '$Listingid' AND Status ='Bird'");
while($row = mysqli_fetch_array($result))
{
$output[] = $row;
}
if (!empty($output)){
echo json_encode( $output );}
else{
echo json_encode( [] );
}
Javascript
<script>
function gup( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return null;
else
return results[1];
}
var frank_param1 = gup( 'Listingid' );
$("#display12").append(frank_param1);
console.log(frank_param1)
$.ajax({
type: "POST",
url: "list.php",
data: {"data":frank_param1},
dataType:'json',
success: function(data){
for(var i=0; i<data.length; i++) {
console.log(data)
var html1 = "<div class=two> Listingid : " + data[i].Listingid + "User id : " + data[i].userid + "</div>" +
"<a id =newListing class=btn btn-success btn-lg1 type=button style=width:140px; href=#noteform data-toggle =modal >"+"submit "+"</a>"
;
$('#display12').append(html1);
}}
});
</script>
Well the data-variable in the success-callback should contain the data from PHP. You have JSON encoded the data in PHP, so you will have to decode that JSON if you want to print the actual data or something. If you just wanna forward it to some other script - you can make a new ajax-request in the success-callback and just stuff the encoded data in there without decoding it.
After decoding the JSON string, it should come out as the $output-array in JavaScript and you can just loop through it.
As for PHP, I don't exactly remember if $output[] = $row means pushing the rows in to the array, but regardless I would use array_push()-function to do it.

jquery post variable shows in html but not php

I'm not sure if it's just me or what but this seems really odd. When I click a button I have jquery send out javascript variables to a php site to be handled there. However on the php site they come up as undefined indexes. The weird part, is that they show on the html page through php's echo. NOTE: The html button is an input type="button", not a submit because I don't want to reload the page.
jquery:
var timestampst = $(timestamp).val();
var objNamest = $(objInst).val();
$.post("sendCalc.php", {
postobjNamest:objInst,
posttimestampst:timestamp},
function(data){
$("#divResult").html(data);
});
php:
//used for troubleshooting, returns Array() on the php page and Array ( [posttimestampst] => 1399973296 [postobjNamest] => test2-1
print_r($_POST);
//when the if and else are used it the php page always echos Not Working, meaning that the $_POST is not set somehow. However, the html page shows the echoed variables in the "divResult" as it should.
//when I try the code without the if and else, the php page returns Undefined Index: posttimstamp/postobjNamest. However, the html page still shows the echoed variables.
if(isset($_POST["posttimestampst"])){
$timestamp = $_POST["posttimestampst"];
echo $timestamp;
echo "<br>";
$objName = $_POST["postobjNamest"];
echo $objName;
echo "<br>";
}
else{
echo "Not Working";
}
Any help is greatly appreciated!
EDIT:
//gets selected object from a dropdown menu
selectedObj = document.getElementById("selectObj").value;
//objName in javascript taken from $objName var in php that is and the beginning of the html page.
objName = <?php echo json_encode($objName); ?>;
//objInst takes the value of the dropdown menu and assigns it as the [] in objName array
objInst = objName[selectedObj];
//timestamp is set in php and imported to java
var timestamp = <?php echo $timestamp; ?>;
EDIT 2:
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js""> </script>
</head>
<h3>Optionen und Berechnen</h3>
<form name="myForm" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<div id="divCalc">
</div>
<input id="addObject" type="button" onclick="addObj()" value="Add Object">
<br>
<br>
<div id="divAddObj" hidden="true">
</div>
<br>
<div id="divCalc">
</div>
<div id="divResult"></div>
</form>
<script type="text/javascript" name="addObject">
var objName;
var selectedObj;
var objInst;
var timestamp = <?php echo $timestamp; ?>;
//Start select dropdown
var select_element = document.createElement("select");
select_element.setAttribute("id", "selectObj");
select_element.setAttribute("name", "selectObject");
options = new Array();
objName = <?php echo json_encode($objName); ?>;
for ( var i = 0; i < (<?php echo $arrayNum; ?>); i++ ){
options.push(new Option(objName[i], i, false, false));
}
options[0].selected = true;
for ( var option in options ){
select_element.appendChild(options[option]);
}
//End select dropdown
//check selected object
selectedObj = document.getElementById("selectObj").value;
objInst = objName[selectedObj];
var timestampst = $(timestamp).val();
var objNamest = $(objInst).val();
$.post("sendCalc.php", {
postobjNamest:objInst,
posttimestampst:timestamp},
function(data){
$("#divResult").html(data);
});
</script>
Change your code to:
objNamest = objInst.value;
timestampst = timestamp.value;
$.post("sendCalc.php", {
postobjNamest: objNamest,
posttimestampst: timestampst },
function(data){
$("#divResult").html(data);
});
You are missing the data parameter of $.post().
From the docs about post():
data
Type: PlainObject or String:
A plain object or string that is sent
to the server with the request.
Your params postobjNamest & posttimestampst do not exist for the $.post() method
It should be
$.post("sendCalc.php", {
// An "on-the-fly" created JavaScript object, which is valid
data: {
postobjNamest: objInst,
posttimestampst: timestamp
},
function(data){
var content = $.parseJSON(data);
window.console.log(content.postobjNamest);
window.console.log(content.posttimestampst);
}
});
From the docs about parseJSON():
Description: Takes a well-formed JSON string and returns the resulting
JavaScript object.
And in the PHP:
$objName = $_POST['postobjNamest'];
$timestamp = $_POST['posttimestampst'];
// Returning your values to client
// Don't echo them in PHP
echo json_encode(array(
'postobjNamest' => $objName,
'posttimestampst' => $timestamp
);
From the docs about json_encode():
json_encode — Returns the JSON representation of a value
The Javascript Object:
// Declaration
var Obj = {
propertyOne: 'value', // string
propertyTwo: 52.3654, // float
methodOne: function () {
// your function code
},
methodTwo: function () {
// your function code
}
}
//Instances
var objOne = new Obj();
objOne.methodOne();
objOne.propertyTwo;
var objTwo = new Obj();
objTwo.methodOne();
objTwo.propertyTwo;

Send Variable Data from Action Script 3 to JavaScript

Since my AS3 and Php/Java knowledge is not good I got stuck on this problem.
I have a AS3 function that sends bitmap data to PHP file to save some image, and in this function I also added some other arguments and that new argument should give me a string value that i need.
private function saveImageForFacebook(evt:MouseEvent)
// Sends the Bitmap data to php
{
var bitmapData:BitmapData=new BitmapData(wheelCanvas.width, wheelCanvas.height);
bitmapData.draw(wheelCanvas);
var jpgEncoder:JPGEncoder = new JPGEncoder(80);
var byteArray:ByteArray = jpgEncoder.encode(bitmapData);
var header:URLRequestHeader = new URLRequestHeader ("Content-type", "application/octet-stream");
var jpgURLRequest:URLRequest = new URLRequest ("http://www.someurl.com/flash-test/saveimg.php");
jpgURLRequest.requestHeaders.push(header);
jpgURLRequest.method = URLRequestMethod.POST;
jpgURLRequest.data = byteArray;
navigateToURL(jpgURLRequest, "_blank");
// Creates the string value that I need to use in saveimg.php
var suffixUrl:String = "";
for(var i:int=0; i < customizedColorArr.length; i++)
{
if(customizedColorArr[i] != "")
{
suffixUrl += "&" + customizedPartValueArr[i] + "=" + customizedColorArr[i];
}
}
suffixUrl = wheelName + "&variant_name=" + variantName + suffixUrl;
trace(suffixUrl);
}
Somehow I need to trace "suffixUrl" value in my saveimg.php file, but i don't know how.
This is how my php file looks and where suffixUrl need to go.
<?php
if ( isset ( $GLOBALS["HTTP_RAW_POST_DATA"] )) {
$uniqueStamp = date(U);
//$filename = "temp_image.jpg";
$filename = $uniqueStamp . ".jpg";
$fp = fopen( $filename,"wb");
$result = fwrite( $fp, $GLOBALS[ 'HTTP_RAW_POST_DATA' ] );
fclose( $fp );
}
?>
<meta property="og:image" content="http://www.someurl.com/flash-test/src_server/<?php echo $filename ; ?>" />
<SCRIPT LANGUAGE="JavaScript">
function redirect () {
window.location.href = "http://www.facebook.com/sharer.php?u=http://www.someurl/flash-test/Main3D.html?"+suffixUrl, '_self';
}
</SCRIPT>
<BODY onload="redirect()">
You will see "suffixUrl" in my javascript function. That's where I'm trying to treace that value.
You don't want to send a variable to Javascript; you want to send a variable to PHP.
Move the suffix generation code block above the Bitmap sending part, and then change this line.
var jpgURLRequest:URLRequest = new URLRequest ("http://www.someurl.com/flash-test/saveimg.php?suffixUrl=" + suffixUrl);
Then, in the PHP
window.location.href = "http://www.facebook.com/sharer.php?u=http://www.someurl/flash-test/Main3D.html?" + <?php echo $_GET['suffixUrl'] ?>, '_self';
This will work, but you will also have to sanitize the input for security.
Assuming your "php file" is the one that's embedding your Flash, you can use ExternalInterface to call your redirect function from Flash.
Flash :
ExternalInterface.call("redirect", suffixUrl);
Note : You need to import flash.external.ExternalInterface;
JavaScript :
function redirect (suffixUrl) {
window.location.href = "http://www.facebook.com/sharer.php?u=http://www.someurl/flash-test/Main3D.html?" + suffixUrl;
}

Categories