How to pass something with apostrophe to json - php

My facebook app uses facebook's ui method, to which you pass json. My php variable's however might contain apostrophe's... what is the best way to preserve them, while properly passing them to the fb method?
FB.ui(
{
method: 'feed',
name: '<? echo $tname; ?>',
link: '<? echo $short; ?>',
caption: '<? echo $description; ?>'
},

use json_encode
$myJSON = array(
'method' => 'feed',
'name' => $tag_line.' at '.$owner_name,
'link' => $short,
'caption' => $description,
'description' => $short
);
$myJSON = json_encode($myJSON);
$myJSON is now contains a string with your data in JSON format and ready to echo to the page.
{
"method" : "feed",
"name" : "tag_line at owner_name",
"link" : "short",
"caption" : "description",
"description" : "short"
}

You need to "escape" them, meaning add a backslash before them.
There are some convenience functions in PHP to help you accomplish this: json_encode (specifically for properly formatting JSON) or addslashes.
However, you should use json_encode rather than addslashes in this case, since addslashes may output incorrect formatting for JSON depending on the input.

The OP needs to escape apostrophes - something that json_encode does not do. The problem that is often encountered is that a json string needs to be generated in php using json_encode and placed in javascript code (as in OP example). Since Javascript does not have heredoc comments you will need to either escape apostrophes or double quotes in order to prevent a parse error.
Something such as:
jQuery.parseJSON('<?=str_replace("'", "\\\\u0027", json_encode(array('something' => "John's")))?>');
But event this is not optimal as it will sometimes stay as \u0027 on js side. So ideally we need to replace whatever code we used to translate our quote using js again:
var code = '<?=parse(json_encode($data)) ?>';
code = code.replace(/\\\\u0027/g, "'");
jQuery.parseJSON(code);

Related

PHP - HTML characters posted within Tweet status

When using Abrahams/TwitterOAuth library, special HTML characters are placed in a Tweet.
$content = "test's";
$params = array(
"status" => $content
);
$result = $connection->post("statuses/update", $params);
results in
test's
within the posted Tweet status.
A vardump($content) in the browser reveals test's as expected.
I've tried html_entity_decode and htmlspecialchars_decode but neither work for the posted Tweet.
You need to tell it explicitly to convert the quotes. This is done with ENT_QUOTES.
Example:
echo htmlspecialchars_decode('test's',ENT_QUOTES) . "\n";
echo htmlspecialchars_decode('test's');
Output:
test's
test's
Demo: https://eval.in/426992
There are also other constants that can be used if you only want to decode single quotes etc. See the manual for more information, http://php.net/manual/en/function.htmlspecialchars-decode.php.
ENT_QUOTES Will convert both double and single quotes.
$content = "test's";
$content = htmlspecialchars_decode($content, ENT_QUOTES);
works for me.
Thanks chris85!

Using MYSQL query data with jQuery Autocomplete

I'm trying to query data with MYSQL,
then link it to an <input> with jQuery's Autocomplete.
I'm still not used to using PHP inside Javascript, so I'm not sure how to get contents
inside an array. When every I console.log my PHP for debugging, it says Array.
Here is my JS code:
var SOMETHING = ["<?php echo $SOMETHING; ?>"];
//console.log(SOMETHING);
$( "#input_add_album" ).autocomplete({
source: SOMETHING
});
Here is my PHP code:
global $SOMETHING;
$SOMETHING = array();
$sql = "
select B from A
";
$stmt = $dbh->query($sql);
$result = $stmt->fetchAll();
foreach ($result as $SOME_CONTENT) {
array_push($SOMETHING, $SOME_CONTENT["SOME_CONTENT"]);
}
This question is old but I'm going to go over the 2 most likely solutions. The problem your having is that your trying to echo an Array to see it's contents and that isn't possible. It's also not possible for the JavaScript interpreter to interpret PHP. PHP processes .php files on your host and then serves them to the clients machine. The client end should never see any PHP, it would not know what to do with it. So the end result after the PHP files are run from server, must be a well formatted document to fit the guidelines of a file type the browser can handle, in this case html and JavaScript. So then in order to log the contents of a PHP variable to the console with JavaScript, it must be in a form JavaScript understands. Luckily for you, there is a format that JavaScript understands and most other languages support. The way to move any string, number, array or associative array to JS is with JSON. JavaScript Object Notation. Just remember, that associative arrays in PHP become objects in JavaScript.
$regular_array = json_encode(array( 'words', 'to', 'send' ));
$php_assoc = json_encode(array(
'assoc' => 'arrays',
'become' => 'JavaScript',
'objects' => array(
'this','will','be',1,array()
),
));
echo "
<script>
/** Check that window.console.logs isn't undefined, if we were just
* using JavaScript I wouldn't be so verbose. Since our PHP variable is
* traveling so far from home, I want to make sure we get the right address
*/
if (window && 'console' in window ) {
window.console.log({$regular_array});
window.console.log('JS object with array inside', {$php_assoc});
}
</script>";
That will log the values out to the browsers console. It would be the equivalent of logging the following array and object to the console with regular old JavaScript.
var regularArray = [ 'words', 'to', 'send' ];
var phpAssoc = {
assoc : 'arrays',
become : 'JavaScript',
objects : [ 'this', 'will', 'be', 1, [] ]
};
In Google Chrome, the phpAssoc object looks like this in the console. It can be fully expanded, looked through, and used like any other JavaScript object.
Object {assoc: "arrays", become: "JavaScript", objects: Array[5]}
*In this example I didn't save the PHP output into a JavaScript variable, but you can see how to inject the value into console.log so you can do the same exact thing with echo "var something = {$some_other_thing};";

Extracting JSON from an HTML page with regex (PHP)

I have an HTML page which has a very large and very complex chunk of JSON in a script tag.
I want to extract the JSON so that I can decode it in a php script.
The JSON looks something like:
<script type="text/javascript">
var user_list_data_obj = (
({
... truncated ...
})
);
... some more js ...
</script>
The script tags can't be used in the pattern, because there's other JS between them, and there's nothing to make them unqiue anyway.
I believe I need to match against the variable name, and the first occurrence of '}));' but my attempts to match that have failed.
What I've got so far is:
$pattern = '/var user_list_data_obj = \(\s\(({.*})\)\s\);/';
Which returns nothing.
What am I doing wrong in that pattern? I know its difficult to match anything that has opening and closing delimiters like JSON, etc with a regex, but it should be possible in this case, no?
EDIT:
I'm trying to get the entire "user_list_data_obj" object parsed into my php script. But really, the bits I'm interested in are the several "columns :[] " arrays, so if it's easier to get those out separately, it might make sense to do that.
The columns[] arrays look something like
columns : [
{ display_value : '<input type="checkbox" name="user" value="username">'},
{ display_value : 'username', sort_value : 'username'},
{ display_value : 'username', sort_value : 'username'},
{ display_value : 'Enabled', sort_value : '1' },
{ display_value : '<img class="" src="/enabled.gif">', sort_value : '1' },
{ display_value : '<img class="" src="/enabled.gif">', sort_value : '1' },
{ display_value : '<img class="" src="/enabled.gif">', sort_value : '1' }
],
I was able to match the entire json object with the following
/user_list_data_obj\s*=\s*\(\s*\({(.*?)}\)\s*\);/
But in actuality, I ended up using preg_match_all to match each columns[] array in the json by using:
/columns\s*:\s*\[.*?\],/s
The closest I can get is
preg_match('/var user_list_data_obj = \(\s+\(({.*})\)\s+\);/s', $html, $matches);
The s modifer allows for the matching of newlines.
This is imperfect as it makes assumptions about the structure: namely that the JSON you need literally starts with
( /* some space */
({
and ends with
}) /* some space */
);
If you can't make those assumptions, a less specific regex will likely match other parts of the script. Also, if you have }) ); at some point in the script that you don't want to match, it will still be matched. Using {.*?} won't work because there can be many nested objects literals in the string you want to capture.

JSON object "undefined" error in Javascript

I am uploading a file using PHP and want to return the file name and the file status to javascript. In PHP I create the json object by:
$value = array('result' => $result, 'fileName' => $_FILES['myfile']['name']);
print_r ($value);
$uploadData = json_encode($value);
This creates the json object. I then send it to a function in javascript and recieve it as a variable called fileStatus.
alert (fileStatus);
It displays
{"result":"success","fileName":"cake"}
which should be good. But when I try and do
fileStatus.result or fileStatus.fileName
I get an error saying that they are undefined. Please help I'm really stuck on this. Thanks.
The fileStatus is just a string at this point, so it does not have properties such as result and fileName. You need to parse the string into a JSON object, using a method such as Firefox's native JSON.parse or jQuery's jQuery.parseJSON.
Example:
var fileStatusObj = jQuery.parseJSON(fileStatus);
If the alert displays {"result":"success","fileName":"cake"} then you probably still have to turn the string into a JSON object. Depending on the browsers you are developing for you can use the native JSON support or the JSON.org implementation to turn your string into an object. From there on it should work as expected.
When you are setting the variable, do not put quotes around it. Just set the variable like this:
var fileStatus = <?php echo $uploadData; ?>;
or:
var fileStatus = <?=$uploadData?>;
Do not do this:
var fileStatus = '<?php echo $uploadData; ?>';

magento escape string for javascript

Is there a helper function that will properly escape a string to be rendered as a single quote quoted JavaScript string literal?
I know of jsQuoteEscape but it only handles quotes and does not treat \n & \r etc.
so if my string is 'line1\nlineb' (i.e. two lines with a newline between them)
and I use
var jsvar='<?php echo $this->helper('myextension')->jsQuoteEscape($mystring); ?>';
I will get in the rendered content
var jsvar='line1
line2';
which is a syntax error.
Thanks,
Eyal
Yes
$string = 'Hello
There';
var_dump( Mage::helper('core')->jsonEncode($string) );
var_dump( json_encode($string) );
I've never been clear if this encoding a non-object string datatypes as a javascript string is a side-effect of the JSON encoding, or if it's true, according to Hoyle Crockford JSON, so I always like to wrap my strings in an object when passing them around
$o = new stdClass();
$o->param = 'This is my
Param';
$json = json_encode($o);
echo 'var data = ' . $json . ';' . "\n";
echo 'var jsdata = data.param';
This is how you'd handle this with javascript. There's no method that's build specifically for this. If you're interested in seeing the helper methods you do have available from a block, checkout the methods in
app/code/core/Mage/Core/Block/Abstract.php
app/code/core/Mage/Core/Block/Template.php
and if you're dealing with a template that's part of a block higher up the chain, get its class and then check its definition
var_dump get_class($this);

Categories