Having trouble making JSON parse and eval to work in JavaScript - javascript

As I stated above, I have a PHP script and a JavaScript, I have a few objects that read text files on the server side and then pass the data to the JavaScript.
Here's my entire code:
map.html: http://www.pastebin.com/b45mbvgp and index.php: http://www.pastebin.com/zibdquzu
The part that really matters:
var x = <?php echo json_encode($streetsObject); ?>;
var obj = eval("("x")");
I've also tried
var obj = JSON.parse(x);
the X variable does get set to the size of the passed object, 527 (tested it) but when I try to use the eval or JSON parse function is simply doesn't work. Do I have some sort of mistake in my html code which is messing with my calls to other libraries? If so that would be weird because kinetic.js is working just fine. I've been googling examples of JSON and I have yet to see an example of parsing a passed object, it's all examples of local objects :(
(Code works fine if I remove eval / json line of code)

Simply do:
var obj = <?php echo json_encode($streetsObject); ?>;
JSON means JavaScript Object Notation. If you insert JSON directly to Javascript, it will run fine, just in this case. No parsing needed. eval is not recommended to use for JSON parsing, but the same applies to that (note that eval actually works because JSON is valid Javascript!).
JSON.parse is only needed if you have JSON in a Javascript string. So this would work:
var str = '<?php echo json_encode($streetsObject); ?>';
var obj = JSON.parse(str);

Related

Print PHP JSON encoded array, to JavaScript and decode it, produces errors

I have to use some data from PHP to JavaScript. I am using JSON for that. I encode the array with PHP's json_encode function and then I want to decode it with JavaScript.
<?php
$data = array(
"..."=>"...",
.....
);
?>
<script>
var data = jQuery.parseJSON('<?php echo json_encode($data); ?>');
console.log(data);
</script>
The problem is sometimes produces errors in javascript console on parsing the JSON, most of times when $data contains HTML.
How can I print a json encoded code inside javascript, dinamically with PHP?
Thank you!
JSON is in fact JavaScript Object Notation, it can be echoed directly in a variable, and doesn't need parsing.
var data = <?= json_encode($data); ?>;
The errors will typically come from when the data contains ' (which prematurely terminate your string literal) or new line characters (which get parsed by the JS parser and render the JSON invalid).
You could get around this by explicitly escaping such characters (with a string replacement function run on the generated JSON), but that is more effort than is worth going to.
Since JSON is a subset of the JavaScript literal syntax, you can just treat it as JavaScript directly. You don't need to wrap it in a string and then parse that string to the JS data structure.
var data = <?php echo json_encode($data); ?>

Generate JSON array

I want to generate a JSON array with PHP, but it doesn't work well.
My PHP array looks like this:
protected $resultArray = array("1.0" => 0, "1.3" => 0);
then I do this:
return json_encode($resultArray);
but then i've got this:
var array = [{"1.0":2,"1.3":1}];
Why is " replaced with "?
quot; is a quote character (") encoded as HMTL. json_encode() does not produce HTML encoded sequences.
Replace return with echo in return json_encode($resultArray); and you'll see this for yourself.
Most probably the returned string is passed further to a function that runs it through htmlspecialchars() or htmlentities() and this is the correct way to work with it if you put it into an HMTL context.
Use a different viewer class if you need to output only the json_encode()-ed string. I don't know TYPO3 but I guess you should use JsonView; pass it $resultArray as-is and it will call json_encode() for you.
I think you may using etended library for example in wamp server I tested this code and it's work fine
$str = "<div style='position:relative'><img src='/assets/ui/success.png' /><span
style='position:relative;top:-15px;'>Nachricht empfangen!</span></div>";
echo json_encode(array('prompt' => $str));
//output
//{"prompt":"<div style='position:relative'><img src='\/assets\/ui\/success.png' \/><span style='position:relative;top:-15px;'>Nachricht empfangen!<\/span><\/div>"}
Thanks guys for help!
The solution is (only for typo3). To get a properly correct JSON-Array in the view the JS code has to be improved the following way:
var array = {f:format.htmlentitiesDecode(value:chartarray)};

Catching php mysql variable in javascript

Im wondering how to catch mysql row in javascript, i tried to do that this way:
var x = <?php
mysql_connect(Not important);
mysql_select_db(not important);
$zapytanie = "SELECT (times) FROM dane WHERE email='$email'";
$idzapytania = mysql_query($zapytanie);
$wiersz = mysql_fetch_row($idzapytania);
echo $wiersz[0];
mysql_close (notimportant);
?>;
alert(x);
But this is not working. Any solutions? Sorry if this questions seems to be lame but i not the best in php/js, but have few things to do.
You should enclose the output of PHP in single quotes if you want it to be treated as a string in javascript. Like this:
var x = '<?php
mysql_connect(Not important);
mysql_select_db(not important);
$zapytanie = "SELECT (times) FROM dane WHERE email=\'$email\'";
$idzapytania = mysql_query($zapytanie);
$wiersz = mysql_fetch_row($idzapytania);
echo $wiersz[0];
mysql_close (notimportant);
?>';
Or alternatively, replace echo $wiersz[0]; for echo "'". $wiersz[0] ."'";
Try this
<?php
mysql_connect(Not important);
mysql_select_db(not important);
$zapytanie = "SELECT (times) FROM dane WHERE email='$email'";
$idzapytania = mysql_query($zapytanie);
$wiersz = mysql_fetch_row($idzapytania);
$w=$wiersz[0];
mysql_close (notimportant);
?>;
<script>
var x =<?php echo $w ?>
alert(x);
</script>
If you want to pass an array from PHP to jquery/javascript, the best way would be using JSON. Pseudocode:
var x=JSON.parse(<?php echo json_encode($array); ?>);
<script type="text/javascript">
setVariables('<?php echo $tag_name ?>', '<?php echo $client_id ?>');
</script>
and then creating that function in your .js file to utilize those values and do what you need.
function setVariables(name, id){
var tag_name = name
var client_id = id
//Operations that need these values.
}
write bundles to javascript!
Personally whenever transferring initilisation data from PHP to the client I find it best to combine the data into an array, and use casting and json_encode (as per Helpful's answer) to make a final structure that is nice and easy to use on the JavaScript side. This saves echoing different variables all over the place, and will automatically handle any type and escape syntax that is required i.e. wrapping strings with quotes, or back-slashing internal quotes in strings.
<?php
$export = array();
mysql_connect(Not important);
mysql_select_db(not important);
$zapytanie = "SELECT (times) FROM dane WHERE email='$email'";
$idzapytania = mysql_query($zapytanie);
$wiersz = mysql_fetch_row($idzapytania);
mysql_close (notimportant);
$export['x'] = !empty($wiersz[0]) ? $wiersz[0] : 'default';
?>
var data = <?php echo json_encode((object) $export); ?>;
Obviously the above is a little overkill for just one small value, however, if there ever became more than one value — something that could quite easily happen after further coding — it would be very easy to extend:
$export['x'] = !empty($wiersz[0]) ? $wiersz[0] : 'default';
$export['something_else'] = 54321;
Then all you need do to access these values in JavaScript is:
data.x
data.something_else
why use an array and why cast to an object?
The reason why I use an associative Array on the PHP side is because I find writing to arrays cleaner in PHP than Objects — not a huge fan of the -> notation. Also instantiating an Array is easier and seemingly more native than an Object in many versions of PHP. I then cast to an object before writing to JavaScript because I find the opposite is true in JavaScript, it's easier and nicer to read when accessing objects rather than arrays. This is all personal taste however.
NOTE: When defining your keys in the $export array you should be wary to keep to standard variable naming conventions i.e. either use camelCase/interCaps or convert spaces to underscores. Whilst you can get away with using any characters, even spaces, it will mean accessing the data from the JavaScript side becomes more cumbersome.
another thing to bear in mind
When setting variables in JavaScript it's often seen as a bad thing to pollute the global namespace. This basically means writing variables at the top level of run-time, that attach to themselves to global Object (usually Window), so that they are accessible by every bit of JavaScript code that runs in that execution. It is seen as bad because unless you use a likely unique variable name, collisions with other code can occur i.e. if both bits of code rely on the same global variable.
If you just output your data var at the top of your script it will become part of the global namespace, and using something as bland as data would be a prime example of something to avoid. It may not matter at all for small projects that aren't going to be extended or worked on by multiple coders, but it is always a good idea to get into the habit of avoiding this.
You can of course just use a variable name that is more unique to your project e.g. myProjectData, or if you have an over-arching namespace that defines your project i.e. examples of which would be jQuery, JSON, console; you could attach it to that e.g. Project.data.
However, if you wanted a more general approach you can also do this by wrapping your JavaScript code in an anonymous function.
<?php
$export = array();
$export['random_value'] = 'Where\'s my monkey?';
?>
(function( data ){
/// data will only be available inside this function
/// or to other sub functions defined inside this function.
console.log(data.random_value);
})(<?php echo json_encode((object) $export); ?>);
With the above code you should end up with your JavaScript always having a nice bundle of values to access, properly escaped and formatted, that have come straight from PHP in an easy way, and that doesn't pollute the global namespace.
WARNING: Obviously it should be noted that if you use the above anonymous wrapper method and you call in any other script files within your page, they wont be able to access data unless you pass the object to that code in some way. This is why people often prefer to have an over-arching namespace object for their project i.e. MyProject.data. However you do not necessarily have to do this — due to the benefit of having all your values bundled up in a singular JavaScript object — because passing it to other code is as simple as sending one variable as a parameter to a function i.e. other.code(data)

js, make a json object a string - the easy way?

I have tried lots of different ways, and using many diffent PHP and JS functions to try to achieve this.
Hoe to i turn this json object ;
"lines" : ["text line 1<br/>","text line 2<br/>","text line 3<br/>","text line 4<br/>"]
Into this string, so that i can add to a HTMl div
text line 1<br/> text line 2<br/> text line 3<br/> text line 4<br/>
No, quotes, brackets or anything else.
In it's simplest form all i have is stringify;
lines = JSON.stringify(obj.lines)
but the above outputs, brackets, quotes, and commas
Sorry if this is a simple and silly question, but i h (finishing now (embarrassed!)) ave searched everywhere for a simple answers. Nothing stands out.
Check out Array.join:
var html = obj.lines.join("");
Example: http://jsfiddle.net/VXbs7/
You have a JSON string. You need to parse it into a data structure, then get the array of strings, and loop over them (outputting as you go).
If you're doing this from javascript, it's quite easy. JSON is native to javascript and can be interpreted as an object quite simply. It looks like you only have half your JSON object pasted in your question though. A whole JSON object is wrapped in [] or {} (unless it's just a string or number type, but then it's not an object).
Anyway, if you're in PHP - you can easily json_decode() this string and loop it like so:
<?php
$arr = json_decode($json_string, true); //true makes it an array instead of object
foreach ($arr['lines'] as $line)
{
echo $line;
}
If you're trying to accomplish it in javascript (in the browser), it's also quite easy (assuming your string is stored in a php variable, and that you're using jquery for dom manipulation)
<script type="text/javascript">
var obj = <?= $json_string; ?>,
mydiv = $('#mydiv);
for (key in obj['lines'])
{
var line = obj['lines'][key];
mydiv.append(line);
}
</script>
both of those should give you the output you're looking for

Storing HTML in a Javascript Variable

I am currently coding a website that will allow a user to input data into a MySQL database using a WYSIWYG editor. The data stores into the database without a problem and I can query it using PHP and display it on my webpage.
Up to this point everything is working ok until I try to move the HTML stored in the MySQL database into a javascript variable. I was able to get it working using CDATA[], but not for every browser. It works in Firefox, but not IE or Chrome. I am looking for a solution that will be able to work in all of the browsers. Any help would be greatly appreciated.
Since you're using PHP:
<script>
var foo = <?php echo json_encode($htmlFromDatabase); ?>
</script>
The json_encode method, while normally used for encoding JSON objects, is also useful for converting other PHP variables (like strings) to their JavaScript equivalents.
"Safefy" your code, like this
str_replace( array("\r", "\r\n", "\n", "\t"), '', str_replace('"','\"',$str));
The above function clears linebreaks, and tabs so that your code appears in one line. If it breaks into more than one line, then it cannot be parsed as a string in JS and an error is thrown. Also we are escaping " to \", maybe there are more string replacements that need to take place, it depends in your content.
and inline it in javascript,
//<![CDATA[
var myHtml = <?php echo '"'.$stuff.'"'; ?>;
//]]>
keep in mind the '"' part so that it appears like this var myHtml = "test";

Categories