missing ) after argument list - php

I'll show the main parts of the code as most of it is irrelevant:
$url = $row['url'];
echo "<div id='anything'><img id='$url' src='$cover' alt='$title' onclick='myFunction($url)'>";
and the javascript function:
function myFunction(something) {
alert (something);
}
I recieve the following error in firebug:
missing ) after argument list
[Break On This Error]
myFunction(http://anything.com/anything...
-------------------^
I am relatively new to javascript but I can tell it is obviously not allowing the ":" from the url. However, I can't change or alter the id, as I need to alert the exact id of the Image.
I have made this work in a different format without the php, so I assume it's there where the problem lies?

The URL needs to be a string, but you're just outputting the string's contents.
You could just put quotes around it as suggested elsewhere, but that's at best an incomplete solution.
Fortunately, PHP gives you a better answer: json_encode combined (in your case) with htmlspecialchars. This is a function that (amongst other things) will properly wrap a string for you such that you can use it in JavaScript code. So:
$escapedUrl = htmlspecialchars(json_encode($url));
then
...onclick='myFunction($escapedUrl)'...
json_encode is for encoding text as JSON, but as JSON is a subset of JavaScript literal notation, and json_encode quite happily returns a valid, properly-escaped JavaScript string...
You need the htmlspecialchars as well because you're then outputting the JavaScript code you're generating into the onclick attribute, and the content of all HTML attributes in HTML text (even ones with code in them) must be properly encoded so (for instance) & must be &, etc.

Do this:
$escapedString = json_encode($url);
echo "<div id='anything'><img id='$url' src='$cover' alt='$title' onclick='myFunction($escapedString)'>";
T.J. Crowder is right, and you can check this out for more information:
What is the correct way to escape text in JSON responses?
Why is my first solution incorrect (even if it seems to work with 1 case)?
Read this: http://kunststube.net/escapism/
echo "<div id='anything'><img id='$url' src='$cover' alt='$title' onclick='myFunction(\"$url\")'>";
You basically need to print double quotes around the the value passed into the myFunction call:
onclick='myFunction(\"$url\")'

This is because you are doing something like this:
myFunction(http://anything.com)
Function parameter need to be enclosed within quotes or doble quotes in case of string parameters:
myFunction("http://anything.com")
So your echo should look like:
"<div id='anything'><img id='$url' src='$cover' alt='$title' onclick='myFunction(\"$url\")'>"
Also you should take into account that $url doesn't have to contain valid characters, so you should add some encoding/escaping (think in terms of XSS).

You have to use the encodeURI(uri) function:
"<div id='anything'><img id='$url' src='$cover' alt='$title' onclick='myFunction(encodeURI(\'$url\'))'>";

Related

Using simplehtmldom in PHP how do I get the data-href attribute?

I am using this PHP library to work with a dom :http://simplehtmldom.sourceforge.net/
I am wanting to access the data-href element of a li element on this page:http://www.spareroom.co.uk/flatshare/bristol/
according to the api reference:
http://simplehtmldom.sourceforge.net/manual_api.htm
This code should work - so long as $res represents the li dom node - which in my case it does:
echo $res->data-href;
However when i run that the echo is "0".... when I would expect to see something like :
"/flatshare/fad_click.pl?fad_id=3248085&search_id=&offset=0&city_id=&flatshare_type=offered&search_results=%2Fflatshare%2Fbristol%2F&"
Can somebody please help me to understand what I am doing wrong
$res->data-href is parse as
$res->data - href
i.e. it's a subtraction, because - is not a valid character in an identifier. Try:
$res->{"data-href"}
Since you are accessing a object keys with special characters have to be quoted and surrounded with {}.
So:
echo $res->data-herf
Should be:
echo $res->{"data-href"}
In all honesty though it probably just easier(and safer) to use the method:
$res->getAttribute("data-href");

Passing PHP-generated JSON via semantic markup

In another question, it was pointed out that using semantic markup can be a really clean way to pass data to an onclick function, along the lines of the code below.
I have a second question relating to passing JSON and having the receiving function recognize it as such. I have a PHP generated JSON value of [{"authed":"2012-03-04 17:24:24"},{"authed":"2012-03-04 11:44:38"}] that I need to pass to a function. echoing that straight into the <a> tag won't work, so I am using urlencode() to get:
click
Unfortunately, when I alert this out from popup(), I via the following code:
function popup(t) {
var auth = t.getAttribute('data-auth');
alert(decodeURI(auth));
}
I get
[{"authed"%3A"2012-03-04+17%3A24%3A24"}%2C{"authed"%3A"2012-03-04+11%3A44%3A38%22"}]
which JSON.parse() is unable to handle. Any suggestions on decoding/passing JSON using this pattern?
You need to use htmlspecialchars() to escape for html--like you should be doing for everything you echo out in html. (You are doing that right? To prevent generating invalid html?) Don't use urlencode(), which is for encoding parts of a url path or query parameter.
<?php
$data = array(array('authed'=>'2012-03-04 17:24:24'), array('authed'=>'2012-03-04 11:44:38'));
$jsondata = json_encode($data);
?>
<a data-auth="<?php echo htmlspecialchars($jsondata, ENT_COMPAT, 'UTF-8')?>" onclick="popup(this)">click</a>

Sending HTML Code Through JSON

I've got a php script which generates HTML content. Is there a way to send back that HTML content through JSON to my webpage from the php script?
Yes, you can use json_encode to take your HTML string and escape it as necessary to be valid JSON (it'll also do things that are unnecessary, sadly, unless you use flags to prevent it). For instance, if your original string is:
<p class="special">content</p>
...json_encode will produce this:
"<p class=\"special\">content<\/p>"
You'll notice it has an unnecessary backslash before the / near the end. You can use the JSON_UNESCAPED_SLASHES flag to prevent the unnecessary backslashes. json_encode(theString, JSON_UNESCAPED_SLASHES); produces:
"<p class=\"special\">content</p>"
Do Like this
1st put all your HTML content to array, then do json_encode
$html_content="<p>hello this is sample text";
$json_array=array(
'content'=>50,
'html_content'=>$html_content
);
echo json_encode($json_array);
All string data must be UTF-8 encoded.
$out = array(
'render' => utf8_encode($renderOutput),
'text' => utf8_encode($textOutput)
);
$out = json_encode($out);
die($out);
In PHP:
$data = "<html>....";
exit(json_encode($data));
Then you should use AJAX to retrieve the data and do what you want with it. I suggest using JQuery: http://api.jquery.com/jQuery.getJSON/
You can send it as a String, why not. But you are probably missusing JSON here a bit since as far as I understand the point is to send just the data needed and wrap them into HTML on the client.
Just to expand on #T.J. Crowder's answer.
json_encode does well with simple html strings, in my experience however json_encode often becomes confused by, (or it becomes quite difficult to properly escape) longer complex nested html mixed with php. Two options to consider if you are in this position are: encoding/decoding the markup first with something like [base64_encode][1]/ decode (quite a bit of a performance hit), or (and perhaps preferably) be more selective in what you are passing via json, and generate the necessary markup on the client side instead.
All these answers didn't work for me.
But this one did:
json_encode($array, JSON_HEX_QUOT | JSON_HEX_TAG);
Thanks to this answer.

Drupal: Incorrect use of t()?

I want to wrap a word in <strong> tags. Is it correct to do that right in the t() call, or am I supposed to do it some other way?
$help = '<p>' . t("Does this sample data look right for node type %node_type? If not, use your browser's <strong>back</strong> button to fix it on the previous page.", array('%node_type' => $_SESSION[NODE_TYPE_KEY])) . '</p>';
Also, what about just dropped variables directly into t(), like this?
foreach ($term_info['term_fields'] as $vocab) {
$options[$vocab] = t($vocab); // TODO: incorrect use of t()?
}
Both your questions are answered in the Drupal API documentation at http://api.drupal.org/api/function/t/6. A short summary:
You can wrap a word in html tags if you really must. Quote:
HTML markup within translation strings
is allowed, but should be avoided if
possible.
It is not allowed to drop variables into t() like you do in your code snippet. Quote:
Because t() is designed for handling
code-based strings, in almost all
cases, the actual string and not a
variable must be passed through t().

Do you have to format the printout from print_r() in PHP to have it validate with W3C?

This will not validate because of the output from print_r, is it not supposed to be used "on a site" or do one have to format it in a certain way?
<?php
$stuff1 = $_POST["stuff1"];//catch variables
$stuff2 = $_POST["stuff2"];
$stuff3 = $_POST["stuff3"];
$myStuff[0] = $stuff1;//put into array
$myStuff[1] = $stuff2;
$myStuff[2] = $stuff3;
print_r($myStuff);
?>
print_r() is mainly designed as a helpful tool for developers, not for actual production use in a manner that end-users would see. Thus, you shouldn't really be trying to validate it - if you're at the stage where you're trying to get stuff to validate, you shouldn't be using print_r anyway.
The validator can't distinguish the output of print_\r() from the surrounding html structure; it simply parses the whole character stream. If the output of your print_r() contains characters that have a special meaning in html (apparently < and > in your case) the validator must assume that it belongs to the html structure, not the text data. You have to mark them as "no, this is just text data, not a control character" for html parsers. One way to do this is to send entities instead of the "real" character itself, e.g. < instead of <
The function htmlspecialchars() takes care of those characters that always have a special meaning in (x)html.
You might also want to enclose the output in a <pre>....</pre> element to keep the formatting of print_r().
echo '<pre>', htmlspecialchars(print_r($myStuff, true)), "</pre>\n";
A plain print_r outputs text, so there's no reason for it not to affect validation. To print it out nicely formatted on an HTML page, use a <pre>:
$printout = print_r($my_var);
echo "<pre>$printout</pre>";
If you don't want to display it, but only to see it as a developer, place it in an HTML (<!-- any text -->).

Categories