Hi all -
I have been given a project to port to ModX. In the original (php) page there is this section in the header:
<script type="text/javascript">
//read columns form csv
var col1 = "<?php echo $col1;?>";
col1 = col1.split(",");
var col1u = "<?php echo $col1u;?>";
col1u = col1u.split(",");
var col2 = "<?php echo $col2;?>";
col2 = col2.split(",");
var col3 = "<?php echo $col3;?>";
col3 = col3.split(",");
</script>
Obviously this is a mixture of JS and PHP.
Can anyone tell me the best way to snippetise/chunk this. It's driving me mad.
I am sure there are lots of suggestions that it shouldn't have been done like that and should be rewritten - but I'd rather just get it working as is!
Thanks for any help - Jon
you can create a snippet, which sets some placeholders
[[yoursnippet]]
<script type="text/javascript">
//read columns from csv
var col1 = "[[+col1]]";
col1 = col1.split(",");
var col1u = "[[+col1u]]";
col1u = col1u.split(",");
var col2 = "[[+col2]]";
col2 = col2.split(",");
var col3 = "[[+col3]]";
col3 = col3.split(",");
</script>
-
☆ A M B ☆
- 24,524 Posts
Or you can reverse the javascript/php situation if you want to
<?php
$js = '<script type="text/javascript">
var col1 = ' . $col1 . ';
col1 = col1.split(",");
var col1u = ' . $col1u . ';
col1u = col1u.split(",");
var col2 = ' . $col2 . ';
col2 = col2.split(",");
var col3 = ' . $col3 . ';
col3 = col3.split(",");
</script>';
-
☆ A M B ☆
- 24,524 Posts
You can also use json in the data attribute's value, so it would be possible to load up a whole json string and break it up in the javascript.
You can also use JSON syntax in data attributes, like so:
<div data-foobar='{"foo":"bar"}'></div>
Note that the attribute uses single quotes while the key:value pair inside are in double quotes; this is required to be valid JSON syntax. To access this with jQuery, just add the key name as an object at the end of the string:
var baz = $('div').data('foobar').foo;
Ya it's pretty crazy what you can do with the data attribute. On heartroasters.com/shop I even put the markup needed for what seems like an AJAX request in a data attribute, so the page appears to be AJAX but is Infact 100% loaded upfront.
jpdevries
Thanks very much for all the interesting and informative replies.
I ended up using placeholders, but it's interesting to see how many ways there are of doing a similar thing.
Hopefully, next time I am asked to do something like this I will be given less horrible code to start with!
Thanks again - Jon
IMHO, such mixes of PHP and JS are ugly. If it's possible use AJAX and JSON.
-
☆ A M B ☆
- 24,524 Posts
AJAX is great, but it's not always suitable. Neatly generating small bits of code to insert onto the page as it's being loaded may be more efficient. Having to wait for an AJAX call to form a set of tabs that need to be displayed immediately, for example, isn't really efficient. The content for each tab is another matter, although you'd probably want the default tab to have its content already.