I am trying to pass HTML using QueryPath. I would like to get the value of a Javascript variable in the HTML. Like this:
<script type="text/javascript">
var base_url = "http://www.exampleurl.com/";
var room_id = "357"; //I want to get the value of room_id
var selected_room_button = "";
</script>
I want to get value of Javascript variable *room_id* which is 357
How can I achieve this?
Even if not using QueryPath, are there any other HTML parsers that can enable me to do this kind of parsing?
You can use a regular expression. This code will return the room id in your example.
<?php
$html = '
<script type="text/javascript">
var base_url = "http://www.exampleurl.com/";
var room_id = "357"; //I want to get the value of room_id
var selected_room_button = "";
</script>';
$pattern = '/var room_id = "(.*)";/';
preg_match($pattern, $html, $matches);
$room_id = $matches[1];
But there is no general solution as a variable may have been defined twice, or have been defined in different scopes.
If you don't need to extract other content beside the row_id I would see no reason for using a HTML parser. It would just slow down things. Also please expect the HTML parser not being a Javascript parser! The HTML parser would just being used to extract the unparsed content between <script> </script> tags - as a string. You would need a regex again to extract the row_id.
Related
I have an array being passed from php which looks like:
$resultsArr[123]['A']='q';
$resultsArr[123]['B']='d';
$resultsArr[113]['C']='s';
$resultsArr[113]['A']='ss';
$resultsArr[113]['B']='sd';
$resultsArr[111]['C']='sds';
$resultsArr[111]['A']='vv';
$resultsArr[111]['B']='vv';
i need to access certain values frmo this array using jquery.
i am trying to access it like
keyVal = 123; //dynamically generated
var pri = '~$results['keyVal']['B']`'
but i am getting a blank value in variable 'pri'
How can this be solved?
Could you not convert it to a JSON Array and then use it directly in Javascript, rather than picking out individual elements of the array?
<script>
var myArray = <?php echo json_encode($resultsArr); ?>;
</script>
Then use jQuery each to read the array.
This would give you greater flexibility in the long term of what was available to javascript for reading and manipulation.
EDIT
You can read a specific element like so, this will alert "vv":
<script>
var myVar = myArray[111].A;
alert(myVar);
</script>
In php use :
$ResultsArr = json_encode($resultsArr);
$this->jsonResultsArr = $ResultsArr; //its seems u r using smarty.
In javascript
jsonResultsArr = "~$jsonResultsArr`";
requireValue = jsonResultsArr[111].A;
I want extrat node value from following java script part.The java script is contained in html head section.I want to do it with PHP html dom or regex.
<script>
*****************************************
**********************************
document.loginform.action ="../Login1.action";
document.loginform.submit();
}
</script>
I want get the text between the document.loginform.action ="I want to get this text"; the two quotes.
please help me.
You can try with this:
Get the <script> node from the HTML like this:
x=document.getElementsByTagName("script");
str = x[0].innerHTML;
This will get you the entire script content between your <scrip> and </script> nodes.
Split the str'
var arr = str.split(":");
This will get you an array with all the lines.Now group all document.loginform strings in the array and proceed further.You need to check a string that contains an 'action' preferably.That will help you to get more accurate results.
Hope this will help you.
To do exactly whay you've asked, you can use a regular expression and the text property of each script element, however I don't think you'll find it very robust or practical.
window.onload = function() {
var script, scripts = document.scripts;
var re = /document\.loginform\.action =/;
var text;
for (var i=0, iLen=scripts.length; i<iLen; i++) {
script = scripts[i];
if (re.test(script.text)) {
text = script.text.match(/document\.loginform\.action ="[^"]+/)[0];
alert(text.split('"')[1]);
}
}
}
You are not searching even for a second or using what people suggest you, this is a bad way to ask for people help.
This is a solution using regex.
<?php
$html = <<<EOD
....
<script>
*****************************************
**********************************
document.loginform.action ="../Login1.action";
document.loginform.submit();
}
</script>
.....
EOD;
$match = preg_match('/document\.loginform\.action\s*=\s*"([^"]+)";/isU', $html, $result);
echo $match[1];
?>
You may want to achieve the same using a DOM Parser, you will need to check here: http://docs.php.net/manual/en/domdocument.loadhtml.php for more informations.
I'm writing a php script that needs to load a 2D array into a js variable as json. First i make the array then use json_encode to turn it into a string. Then I run a small bit of js to get it accessable on the client side. Like so:
$sBaseData = Filters::$sFilterBaseTypeData;
$sBaseData = str_replace('\r',' ',$sBaseData);
$sBaseData = str_replace('\n',' ',$sBaseData);
$sBaseData = str_replace('\t',' ',$sBaseData);
echo <<<HTML
<script type="text/javascript">
var validation_data = JSON.parse('$sBaseData');
</script>
HTML;
Firefox complains about an unexpected character here:
var validation_data = JSON.parse('{"enumeration":{"js":"","msg":""},"date":{"js":" var parts = widget.value.split('-'); var d = new Date(parts[0],parts[1],parts[2]); PASS = (d.getDay()>=1); ","msg":"Invalid date. Please Enter a date in the format: YYYY-MM-DD"},"text":{"js":"","msg":"what did you do?"},"integer":{"js":"if (isNaN(widget.value)) { PASS = false; } else { intVal = parseInt(widget.value); PASS = (widget.value == intVal); } ","msg":"Please enter an integer value"},"decimal":{"js":"PASS = isNaN(widget.value); ","msg":"Please enter a number"},"group":{"js":"","msg":""},"dealer":{"js":"","msg":""}}')
I tried using http://jsonlint.com/ to find out which character was at fault but it says it's all valid and wonderful. I replaced some characters that were causing issues, is there anything else I should be replacing?
The problem is you have ' in your string while you are using ' to quote the string.
If your json string is valid, you don't need to parse it even. The below will work.
echo <<<HTML
<script type="text/javascript">
var validation_data = {$sBaseData};
</script>
HTML;
Uh...
var parts = widget.value.split('-');
Putting that in a string that uses single quotes will break it. Use a JSON encoder to output your JavaScript literal.
Your JSON is valid but in your js code the simple quote closes the parse function's argument.
Try like this:
"date":{"js":" var parts = widget.value.split(\'-\');
I got really confused when i tried to transfer variables from php to js.
everything is fine when i try to get value using an id
for example:
var name = $("#name").val();
but my question is, if i want to convert for example this variable:
$id = 182938; //the id of the user
to this variable:
var id;
this question might be dumb... maybe easy for you, but not for me :p
I have looked it up and only found something like this anywhere i looked for:
<?php
$number = rand();
?>
<script language="javascript">
var num = <?php echo $number ?>
</script>
Does it have the same affect as passing down the value?
Thanks!!
Not quite. Encoding as JSON will ensure that it is a valid JavaScript literal.
var num = <?php echo json_encode($number) ?>
what the code does is:
<?php
$number = rand(); //assign random number to $number. let's say it's "3"
?>
//then these are printed on the page normally
<script language="javascript">
var num = <?php echo $number ?> //the $number is echoed at this position
</script>
and then the browser receives:
<script language="javascript">
var num = 3;
</script>
You have to generate syntactically VALID javascript. PHP can echo text into ANY part of the page it's generating, but that doesn't necessarily mean it's actually USABLE text. In your case, you've forgotten a ;, so your generated javascript is actually a syntax error:
var num = <?php echo $number ?>;
^--- missing
The same sort of thing occurs when you're outputting text. Consider where you're storing someone's name into a variable:
<?php
$name = "Miles O'Brien"; // <-- note the single quote
?>
<script>
var name = <? php echo $name ?>;
</script>
This LOOKS ok, but it'll actually generate yet another syntax error:
var name = Miles O'Brien;
there's no quotes around the whole string, and the embedded quote will START a string in javascript, leading the JS interpreter to complain about an undefined variable "Miles", an undfined variable "O", and an unterminated string literal.
Instead, the PHP should have been:
var name = <? echo json_encode($name) ?>;
The JSON encapsulation guarantees that you're embedding syntactically valid Javascript values.
I m new to CakePhp and JQuery.
I am getting an error in using the cakephp code inside my JQuery.
My code
<script type="text/javascript">
$(document).ready(function(){
var attributeid;var fieldname;
$("#"+<?=$r['Attribute']['id'];?>).change(function () {
fieldname=<?=$r['Attribute']['label'];?>;
alert(fieldname);//this show me that undefined
attributeid=<?=$r['Attribute']['id'];?>;
alert(attributeid);//But this works
});//attribute change
});//ready function
if I echoed ($r['Attribute']['label'];) this value is coming inside my <?php ?>.
But not inside my JQuery.
Note :
attributeid=<?=$r['Attribute']['id'];?>;
alert(attributeid);//But this works
Error:
Name is not defined
fieldname=name;
alert(fieldname);
You are not thinking about how this is translating over once the variables are echoed.
If you have a variable $x with the contents "test", doing this:
var x = <?=$myvar?>;
Will result in:
var x = test;
This is not valid (unless test is a variable) because you need quotations around it to make it a string:
var x = "<?=$myvar?>";
Which then results in the valid:
var x = "test";
The reason it works with the other variable is because you are echoing an ID, which is an integer:
var x = <?=$myid?>;
Would translate to:
var x = 5;
Which is perfectly valid.
All this being said, you should put all the stuff you want to send over to Javascript in an array and call json_encode on it to easily and safely print the values over. Without it, you have to worry above about escaping quotes in the string and such.