Page 1 of 1

Javascript as a string datatype

Posted: Sun Oct 15, 2006 8:57 pm
by astawater
What data type would I use to store javascript code in my PHP program? I'm thinking string, but then there could be " inside the javascript which would then not work when initializing the string. So I'm confused what to use.


$foo="function Loan() { var housePrice; var IR;var dpayment;var years;var monthPay;var month;switch(document.calcform.startm.value) {case "january":document.calcform.startm.value="0";parseInt(document.calcform.startm.value)break;"; //Is what I would like the code to say, but it won't work as a result of the javascript containing a "



So how would I store the javascript code as a datatype to send/recieve via PHP/XML RPC?

Posted: Sun Oct 15, 2006 9:06 pm
by volka
There are only "problems" when a string (literal) is parsed. Not if it is only stored (as variable).
Therefore

Code: Select all

$foo="function Loan() { var housePrice; var IR;var dpayment;var years;var monthPay;var month;switch(document.calcform.startm.value) {case "january":document.calcform.startm.value="0";parseInt(document.calcform.startm.value)break;"; //Is what I would like the code to say, but it won't work as a result of the javascript containing a "
is problem, but

Code: Select all

<?php
$foo = file_get_contents('data.txt');
?>

Code: Select all

// data.txt
function Loan() { var housePrice; var IR;var dpayment;var years;var monthPay;var month;switch(document.calcform.startm.value) {case "january":document.calcform.startm.value="0";parseInt(document.calcform.startm.value)break;"; //Is what I would like the code to say, but it won't work as a result of the javascript containing a
is not. The same is true for xml-rpc.

Posted: Sun Oct 15, 2006 9:19 pm
by alex.barylski
Your want to output javascript in your PHP source code?

Well a string is the only way, really, I mean I suppose you could use an array of characters or something similar, but that would be overkill...

To prevent your Javascript strings from breaking your PHP enclosed strings you have two options:

1) Use single quotes for all your PHP strings and double quotes for your Javascript strings
2) Escape the " or ' inside your javascript string with \ so...

Code: Select all

$js_str = "function jsFunc(){ alert(\"Hello from javascript\"); }"
Notice the \ inside the PHP string, it escapes the double quote intended for your javascript string so the PHP parser reads all in correctly....

Personally I follow the former convention, so simplicity and speed.

Cheers :)

Posted: Sun Oct 15, 2006 10:22 pm
by Ollie Saunders
Don't forget heredoc syntax.