Syntax error help - php

I seem to have a syntax error and can't see it myself, could someone run over it for me please?
Thanks.
<script>
var acurl_<?php echo $request_data['friendship_id']; ?> = "sn-include/create_bond_accept.php?friendship_id=<?php echo $request_data['friendship_id']; ?>&friend_id=<?php echo $fromuser['id']; ?>";
</script>

Because you got some answers that intended to show you how to improve your code, but actually don't do so (IMO), here is my attempt:
<?php
$acurl = array();
$acurl[$request_data['friendship_id']] = sprintf('sn-include/create_bond_accept.php?friendship_id=%s&friend_id=%s', $request_data['friendship_id'], $fromuser['id']);
?>
<script>
var acurl = <?php echo json_encode($acurl); ?>
</script>
I would not create dynamic variable names. This code would create a JS object, where the properties are the friendship IDs, something like:
{
'42': 'sn-include/create_bond_accept...'
}
You can access these URLs more easily from JavaScript than if you have dynamic variable names.

David, on the bright side, you don't have a syntax error.
If you're developing PHP, I would recommend two things:
Get a better IDE. Dreamweaver is TERRIBLE for working with PHP. I recommend NetBeans (it's awesome and free).
Start breaking up your code into chunks. The big ball of html and PHP is hard to debug.
Check this out:
<?php
// prepare output
$segment = '?friendship_id=' . $request_data['friendship_id'];
$segment .= '&friend_id=' . $fromuser['id'] . '";' . "\n";
$acurl = 'var acurl_' . $request_data['friendship_id'];
$acurl .= ' = "sn-include/create_bond_accept.php';
$acurl .= $segment;
$dnurl = 'var dnurl_' . $request_data['friendship_id'];
$dnurl .= ' = "sn-include/create_bond_deny.php';
$dnurl .= $segment;
?>
<script type="text/javascript">
<?php
echo $acurl;
echo $dnurl;
?>
</script>

Use here doc instead:
<?php
echo <<<JS
<script>
var acurl_{$request_data['friendship_id']} = "sn-include/create_bond_accept.php?friendship_id={$request_data['friendship_id']}&friend_id={$fromuser['id']}";
</script>
<script>
var dnurl_{$request_data['friendship_id']} = "sn-include/create_bond_deny.php?friendship_id={$request_data['friendship_id']}&friend_id={$fromuser['id']}";
</script>
JS;
?>
See http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

Related

Echo javascript function

I am tryaing to to make this echo work, but i cant get the grip of it
echo '<script>
function replaceWithImgLinks(txt) {
var linkRegex = /([-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?(?:jpg|jpeg|gif|png))/gi;
return txt.replace(linkRegex, "<img class="sml" src="$1" /><br />");
}
var newHTML = replaceWithImgLinks($(".ms").html());
$(".ms").html(newHTML);';
echo "</script>";
What am i doing wrong? i think i got something wrong with my " ' .
There was a couple of issues. I started by just running it in JavaScript until I got it to work, then moved it into PHP (for the sake of sanity).
<?php
print '
<script>
function replaceWithImgLinks(txt) {
var linkRegex = /([-a-zA-Z0-9#:%_\+.~#?&\/\/=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&\/\/=]*)?(?:jpg|jpeg|gif|png))/gi;
return txt.replace(linkRegex, "<img class=\"sml\" src=\"$1\" /><br />");
}
var newHTML = replaceWithImgLinks($(".ms").html());
$(".ms").html(newHTML);
</script>';
?>
Shouldn't the regex be something like:
(^|\b)((https?:)?\/\/[^\s]*?\.(jpe?g|png|gif))(\b|$)
Debuggex Demo
You shouldn't be echo'ing scripts, especially scripts in script tags. I would seriously look into just using your back end to fetch, then use an asynchronous technology that fetches data parsed JSON. That way you can call your scripts normally.

Using PHP to determine what HTML to write out

This block of PHP code prints out some information from a file in the directory, but I want the information printed out by echo to be used inside the HTML below it. Any help how to do this? Am I even asking this question right? Thanks.
if(array_pop($words) == "fulltrajectory.xyz") {
$DIR = explode("/",htmlspecialchars($_GET["name"]));
$truncatedDIR = array_pop($DIR);
$truncatedDIR2 = ''.implode("/",$DIR);
$conffile = fopen("/var/www/scmods/fileviewer/".$truncatedDIR2."/conf.txt",'r');
$line = trim(fgets($conffile));
while(!feof($conffile)) {
$words = preg_split('/\s+/',$line);
if(strcmp($words[0],"FROZENATOMS") == 0) {
print_r($words);
$frozen = implode(",", array_slice(preg_split('/\s+/',$line), 1));
}
$line = trim(fgets($conffile));
}
echo $frozen . "<br>";
}
?>
The above code prints out some information using an echo. The information printed out in that echo I want in the HTML code below where it has $PRINTHERE. How do I get it to do that? Thanks.
$("#btns").html(Jmol.jmolButton(jmolApplet0, "select atomno=[$PRINTHERE]; halos on;", "frozen on")
You just need to make sure that your file is a php file..
Then you can use html tags with php scripts, no need to add it using JS.
It's as simple as this:
<div>
<?php echo $PRINTHERE; ?>
</div>
Do remember that PHP is server-side and JS is client-side. But if you really want to do that, you can pass a php variable like this:
<script>
var print = <?php echo $PRINTHERE; ?>;
$("#btns").html(Jmol.jmolButton(jmolApplet0, "select atomno="+print+"; halos on;", "frozen on"));
</script>

Why does PHP throw source code indentation out?

For a while I have wondered why PHP throws source code indentation out.
Example
PHP:
<script type="text/javascript">
swfobject.embedSWF("a.swf", "a", "100%", "100%", "10.0.0", "a.swf", params);
params.1 = "<?php echo implode(',', $_POST['1']); ?>";
params.2 = "<?php echo $_POST['2']; ?>";
params.3 = "<?php echo $_POST['3']; ?>";
<?php if ($_POST['4']) { ?>params.5 = "/mode <?php echo $_POST['2']; ?> +D";<?php } ?>
params.6 = "Test";
</script>
Generates source code:
<script type="text/javascript">
swfobject.embedSWF("a.swf", "a", "100%", "100%", "10.0.0", "a.swf", params);
params.1 = "A";
params.2 = "B";
params.3 = "C";
params.5 = "/mode B +D";
params.6 = "Test";
</script>
Why does PHP throw source code indentation out on the next row, and how can I stop it from making my code ugly?
I agree that this is not nice. Anybody who doesn't care about the source code will not get a job with us. Ugly source codes are the source of all evil! No, just kidding.
However, you make a basic mistake in your code by mixing PHP and HTML in the way you do. Yes, I know it can be done, but should you? Is your PHP code very readable? I think not.
This is the way I would code it:
<?php
// get parameters
$params[1] = implode(',', $_POST['1']);
$params[2] = $_POST['2'];
$params[3] = $_POST['3'];
if ($_POST['4']) $params[5] = "/mode {$_POST['2']} +D";
$params[6] = "Test";
// create javascript
echo '<script type="text/javascript">'.PHP_EOL.
' swfobject.embedSWF("a.swf","a","100%","100%","10.0.0","a.swf",params);'.PHP_EOL;
foreach ($params as $no => $value) {
echo " params.$no = \"$value\";".PHP_EOL;
}
echo '</script>';
?>
In other words: You have a powerful programming language, why not use it? Since all output is now done by PHP you have full control over it.
There are still many things wrong with this code, but that's for another time.

Javascript String with Single Quote printed from PHP code

I have following script printed from PHP . If some one has a single quote in description it shows javascript error missing ; as it thinks string terminated .
print "<script type=\"text/javascript\">\n
var Obj = new Array();\n
Obj.title = '{$_REQUEST['title']}';
Obj.description = '{$_REQUEST['description']}';
</script>";
Form does a post to this page and title and description comes from textbox.Also I am unable to put double quotes around {$_REQUEST['title']} as it shows syntax error . How can I handle this ?
a more clean (and secure) way to do it (imo):
<?php
//code here
$title = addslashes(strip_tags($_REQUEST['title']));
$description = addslashes(strip_tags($_REQUEST['description']));
?>
<script type="text/javascript">
var Obj = new Array();
Obj.title = '<?php echo $title?>';
Obj.description = '<?php echo $description?>';
</script>
You also need to be careful with things like line breaks. JavaScript strings can't span over multiple lines. json_encode is the way to go. (Adding this as new answer because of code example.)
<?php
$_REQUEST = array(
'title' => 'That\'s cool',
'description' => 'That\'s "hot"
& not cool</script>'
);
?>
<script type="text/javascript">
var Obj = new Array();
Obj.title = <?php echo json_encode($_REQUEST['title'], JSON_HEX_TAG); ?>;
Obj.description = <?php echo json_encode($_REQUEST['description'], JSON_HEX_TAG); ?>;
alert(Obj.title + "\n" + Obj.description);
</script>
Edit (2016-Nov-15): Adds JSON_HEX_TAG parameter to json_encode calls. I hope this solves all issues when writing data into JavaScript within <script> elements. There are some rather annoying corner cases.
Use the string concatenation operator:
http://php.net/manual/en/language.operators.string.php
print "<script type=\"text/javascript\">\n
var Obj = new Array();\n
Obj.title = '".$_REQUEST['title']."';
Obj.description = '".$_REQUEST['description']."';
</script>";

var transfert between php and javascript

I like to get a dir listing in php
glob("*.jpg");
or
$dir = '.'; //requested directory to read
$notthat = array('.', '..'); //what not to include
$listedfiles = array_diff(scandir($dir), $notthat); // removed what not to include
so i like to send that array to a javascript like that (slides = $listedfiles)
function startSlideshow(slides) { .. do something..}
What is the best way to do that ?
json_encode is your friend for this. No looping is necessary. It will return a pure json object string that you can then just echo into your js file using PHP. Example:
var slides = <?php echo json_encode( $filelistarray );?>
function startSlideshow(slides) { .. do something..}
you can always just do an echo of it to a javascript :
echo ' <script type="text/javascript">
var filelist = [];
';
foreach($listedfiles as $file)
{
echo " filelist[] = $file; ";
}
echo "</script>";
PHP and Javascript cannot directly interact, however, you can output Javascript from PHP the same way you can output plain text or HTML:
<script type="text/javascript">
var slides = [];
<?php
foreach ($listedfiles as $file)
{
echo "slides[] = '" . addslashes($file) . "';\n";
}
?>
// ... do js stuff
</script>
Basically, after creating your array in PHP, you output the JS code to create the same array in javascript.

Categories