I'm trying to put a php variable within a js script that is in a result variable that will be processed with json but i don't get it to work. I know it has something to do with the "" and '' but i can't figure out what it is.
$result["html"] .= "<script type='text/javascript'>setTimeout(function () { window.location='.$config[\"BURL\"].'; }, 2500);</script>";
Edit: whoohoo i got the 15 points to upvote! Thanks u all!
You will have to concatenate strings using . and remove the escaping of the quotes for the index, like so:
$result["html"] .= "<script type='text/javascript'>setTimeout(function () { window.location='" . $config["BURL"] . "'; }, 2500);</script>";
Related
My question
My question is about correctly parsing HTML from php into a variable inside of a javascript object (which in this case is ace-editor's value variable)
My problem
I have got a textarea for HTML and CSS, the HTML gets retrieved from the database and needs to be inserted into a field of croppie, i am currently using PHP's json_encode functionality to put it inside of the variable, but it seems to still escape from the value.
My code
<?php
$css = ($modify) ? trim($template->style()) : "";
$html = ($modify) ? trim( $template->html() ) : "";
$html = json_encode($html);
$css = json_encode($css);
?>
YUI().use(
'aui-ace-editor',
function(Y) {
var editorhtml = new Y.AceEditor({
boundingBox: '#editor-html',
height: '400',
mode: 'html',
value: '<?php echo substr( $html, 1, -1 ); ?>',
width: '100%',
showPrintMargin: false
}).render();
var editorcss = new Y.AceEditor({
boundingBox: '#editor-css',
height: '400',
mode: 'css',
value: '<?php echo substr( $css, 1, -1 ); ?>',
width: '100%',
showPrintMargin: false
}).render();
}
);
What happens
When i use this, and open up a specific template which can be managed, i will not be able to see the textarea's (because the ace editor could not be loaded), i get random errors relating to line 666 which is the exact line the HTML gets stored in. I did sanitize the outputs in json_encode correctly.. right?
in this screenshot, you can see the HTML/css which gets inserted. But the problem occurs on line 666 which the HTML is located at. Click here if the screenshot isn't readable for you
So my question is..
Why exactly does it not parse the HTML into the object correctly? Am i not sanitizing it correctly or am i missing something?
You are breaking the output of json_encode by changing double quotes it creates to single quotes.
It's better to call json_encode directly when adding value to the script tag:
value: <?php echo json_encode($html); ?>,
Your issue is because your $html string contains single quotes, try escaping them or using double quotes
I generate some JS objects strings in PHP because all of the variables i need are there, instead of passing them to js and generate the object there:
$results[] = "{value:" . $data . ",color:\"rgba($aa,$ab,$ac," . Config::$TRANSPARENCY_B . ")\",highlight:\"rgba($ba,$bb,$bc," . Config::$TRANSPARENCY_B . ")\",label:\"" . $entry->getDate() . "\"}";
Now i want to pass the finished result list of JS object strings to JS in order to display it. The resulting structure should be like: [{object1}, {object2}, ...]
In order to achieve this i use htmlspecialchars(json_encode($result), ENT_QUOTES, "UTF-8")
However this ends up in something of the structure: {"{object1}", "{object2}", ...], which of course won't work. How can i manage to throw away the useless enclosing "? I had a look through json_encode() and htmlspecialchars() but none of the parameters there seems to fit.
Any ideas? Thanks!
EDIT: Turns out i am completely dumb. Of course i should pack up some real objets and not a string representing them.. THANKS!
Why not just create real objects, that way encoding them as JSON is easy
$obj = new stdClass;
$obj->value = $data;
$obj->label = $entry->getDate();
$results[] = $obj;
echo json_encode($results);
Associative arrays would also be outputted as "objects" in JSON, and is probably easier
You would be better off not manually making JSON out of strings and use the json_encode function to do it for you:
$results[] = array(
'value' => $data,
'color' => "rgba($aa,$ab,$ac," . Config::$TRANSPARENCY_B . ")",
'highlight' => "rgba($ba,$bb,$bc," . Config::$TRANSPARENCY_B . ")",
'label' => $entry->getData()
);
echo json_encode($results);
I've got a button I build with php to fire a javascript onclick event:
<button onClick='edit(this, "<?php echo $this->result[$i]["type"]; ?>","<?php echo $quality; ?>", "<?php echo json_encode($stuff); ?>", ...)">
</button>
I just added the json data $stuff. Now when I'm in javascript to get some values:
jQuery(stuff).each(function(index) {
console.log( "The key is " + this.name + " and the value is " + this.hash );
});
I get this error: SyntaxError: missing ) after argument list
This is because json data is using double quotes so the result looks something like this:
"foo", "bar", "[{"name":"test","hash":"123"},{"name":"test1","hash":"456"},..."
In this onclick event I've tried changing the quotes to single quotes or vice versa. I've tried escaping quotes with backslashes. It seems nothing works. What am I missing?
Have you tried escaping the quotes for the json that you are returning? You can do so like this:
echo json_encode($this->result[$i]["type"]);.
It will make your json like this:
\"foo\", \"bar\", \"[{\"name\":\"test\",\"hash\":\"123\"}....
If your code is already in json, json_encode() shouldn't change anything except adding the blackslashes.
... "<?php str_replace('"', '\"', $this->result[$i]["type"]); ?> ...
Maybe it's because in text you show (type) is " character.
I am trying to create a Javascript function that echoes out a Wordpress function called the_title() which just returns the title of the a blog. Through PHP it echoes out fine but when I do it through Javscript, however, quotes seem to be unescaped (specifically single quotes). Any help or explanation why this is happening?
THE CODE:
function createSliderTabs() {
var para = document.createElement("li");
var strings = "<?php the_title(); ?>";
var post_string = strings.replace(/"/g, "").replace(/'/g, "").replace(/\(|\)/g, "");
var node = document.createTextNode(post_string);
para.appendChild(node);
var element = document.getElementById("control-navigation");
element.appendChild(para);
}
createSliderTabs();
THE RESULT:
Macy’ ;s Herald Square (had to include space or it would've changed to single quote)
WHAT IT SHOULD BE:
Macy's Herald Square
Any help or guidance on why this is happening? Thx in advance...
From php to js transformation you always have to use json_encode().
to avoid xss
to describe unicode characters
You can use html_entity_decode:
I'm not really familiar with wordpress, but I suppose you would use it inside the_title():
function the_title()
{
$str = 'Macy’s Herald Square';
echo html_entity_decode ($str, ENT_COMPAT , "UTF-8");
}
If you need to use json_encode() you should be able to do
$json = html_entity_decode(json_encode($array), ENT_COMPAT , "UTF-8");
EDIT: added ENT_COMPAT , "UTF-8"
I'm trying to return use a JSON object with handlebars. Making a small todo list to learn how to use it.
My PHP API is as follows :
$query = "SELECT *
FROM table";
try
{
$db = getConnection();
$response = $db->query($query);
$todo = $response->fetchAll(PDO::FETCH_OBJ);
$bdd = null;
echo json_encode($todo);
}
It then returns something like :
[{"id":"1","todo":"Do something","who":"Me","is_done":"0"},{"id":"2","todo":"Learn JSON","who":"Me","is_done":"0"}]
But I'd actually need it to be like this :
{todos: [{"id":"1","todo":"Do something","who":"Me","is_done":"0"},{"id":"2","todo":"Learn JSON","who":"Me","is_done":"0"}]}
I tried in my PHP API to add instead of echo json_encode($todo)
echo '{todos: ' . json_encode($todo) . '}';
But it doesn't work. Any ideas ?
Your "todos" property name must be quoted with double-quote characters.
echo '{"todos": ' . json_encode($todo) . '}';
Though JavaScript syntax allows for property names without quotes, strict JSON insists on them.
While Pointy's answer is correct (might want to read about JSON), alternatively you could do this:
echo json_encode(array('todos' => $todo));
PHP associative arrays will be serialized to JSON as objects (json_encode() example in Manual).
Try with :
echo '{ "todos" : ' . json_encode($todo) . '}';
Try this:
echo json_encode(array( 'todos' => $todo ));
Instead of making the JSON yourself, make the structure you want, then have PHP make the JSON for you.