embed javascript ojbect in jade template from controller - javascript

I'm using jade to do all my rendering, and I"m passing my data from my controller in node into my page template.
I want to add an object inline with javascript... I have a variable app in a js file, and I want to include more data into that app object. I have the following:
script(type="text/javascript")
app.stations = !{page_data.station_info}
Which I would want to output as
script(trype="text/javascript")
app.stations = [{my json object}]
But instead it's rendering like this:
<script type="text/javascript">
<app class="stations">= [my json object]
</app>
EDIT:
After an hour of research I figured it out: (you need to put a . after script
script.
app.stations = JSON STUFF

After an hour of research I was able to figure it out... You do script. and then write your javascript normally. See below
script.
app.stations = JSON STUFF

Related

How to access returned object from groovy controller in JS file

I am trying to access the returned object from grrovy controller into my javascript code.
Here's the code.
Groovy Controller:
def result = [
data : 'data',
status : 'success',
]
[result: result]
GSP file:
<g:hiddenField name="result" value="${result}" />
JS file:
var jsresult = $("#result").val();
console.log(jsresult);
console.log(jsresult.data);
Here's the console output:
{data=data, status=success}
undefined
Looks like some issue with formatting but not able to find out the root cause. Tried converting it into JSON but still not able to access the properties (jsresult.data).
Please let me know how I can resolve this and let me know if any alternate way of passing data from groovy controller to JS code.
Thanks.
First, make sure your result is being encoded a proper JSON:
<g:hiddenField name="result" value=${result as JSON}" />
Then parse it in javascript:
var jsresult = JSON.parse($("#result").val());
You'll get an object back that you can interact with as you expect.
As far as other ways to do this: there are quite a few, but for simple and arbitrary data transfer to a static page, this is probably the simplest. If you're using ajax requests you can avoid having to place the JSON-encoded data on your page at all, but from what you included here that does not appear to be the case.

Pass generated HTML to JavaScript

I'm trying to pass a string of generated HTML from Python to Javascript. This is the simplified version of my view (using Pyramid framework).
#view_config(route_name='view_page', renderer='templates/page.jinja2', permission='view')
def view_cosmeceutical(request):
gen_html = markdown( ingredient.desc )
return dict(gen_html=gen_html)
From this thread, I saw that I can use {{ variable }} in Javascript too, so in my JS file, I have a function that attempts to change the innerHTML of the element with the id 'content-desc'. But all I'm getting is the string {{ genHTML }} instead of the actual variable containing the generated HTML.
function insertHTML() {
genHTML = '{{gen_html}}';
$('#content-desc').html(genHTML);
}
What am I doing wrong?
One good way to pass data and content from the server-side Python to JavaScript are
JSON embeds in HTML
Separate AJAX calls which serve JSON objects as application/json mime
For the embed approach, I would do somethibng along the lines to export data to the page template as JSON:
import json
gen_html = ...
javascript_data = json.dumps(dict(gen_html=gen_html))
return dict(javascript_data=javascript_data)
Then in the page template pass this to JavaScript global variables:
<script>
window.javascriptData = {{javascript_data}}; // Check need to escape HTML in your case
</script>
And then in JavaScript (keep preferably in a separate static .JS file):
$(document).ready(function() {
$('#content-desc').html(window.javascriptData.gen_html);
});
Also, I would not generate HTML for just passing it to JavaScript in the first place. Instead, I would pass raw data to JavaScript as JSON, and then generate HTML on the client-side from this data using client-side templating. This increases the complexity, but is more "clean" and flexible.
Example microtemplating engines for the client-side JavaScript:
DOM tree based JavaScript template engines

Codeigniter - sending json to script file

I query the db i my model like so
function graphRate($userid, $courseid){
$query = $this->db->get('tblGraph');
return $query->result();
}
My controller gets data back from my model and I json encode it like so
if($query = $this->rate_model->graphRate($userid, $courseid)){
$data['graph_json'] = json_encode($query);
}
$this->load->view('graph', $data);
And thats returns me a json object like so
[
{"id":"1","title":"myTitle","score":"16","date":"2013-08-02"},
{"id":"2","title":"myTitle2","score":"17","date":"2013-09-02"},
{"id":"3","title":"myTitle3","score":"18","date":"2013-10-02"}
]
In my view graph I'm loading an js file
<script type="text/javascript" src="script.js"></script>
Now I want to use $data that is being sent from my controller to my view, to my external script.js to use as labels and data to feed my chart. But How do I get that Json data to my external script.js so I can use it?
1 more thing about the json data, isn't it possible to get the output of the json data as
{
"obj1":{"id":"1","title":"myTitle","score":"16","date":"2013-08-02"},
"obj2":{"id":"2","title":"myTitle2","score":"17","date":"2013-09-02"},
"obj3":{"id":"3","title":"myTitle3","score":"18","date":"2013-10-02"}
}
The problem isn't a Codeigniter problem, it's a javascript scope/file inclusion/where-do-i-get-my-data-from problem.
I run into this all the time and have used these solutions:
naming my php files with .php extensions and loading them as if they're views.
Just putting the script that needs data from a view IN the view file where it's used
Using an ajax request in my included js file to hit a controller and get json data.
I use #2 most frequently (for things like datatables where I WANT the js code right there next to the table it's referencing.
I use #1 occasionally, but try NOT to do that because it means some .js files are in my webroot/js dir and some are in teh application/views directory, making it confusing for me or anyone else who wants to support this project.
#3 is sometimes necessary...but I like to avoid that approach to minimize the number of requests being made and to try to eliminate totally superfluous requests (which that is).
You need to print the result of the output json string to the html generated file.
But you need to parse the string with some script. I would recommend you: http://api.jquery.com/jQuery.parseJSON/
For the second question. It is possible by doing:
$returnValue = json_encode(
array (
"obj1" => array("id"=>"1","title"=>"myTitle","score"=>"16","date"=>"2013-08-02"),
"obj2" => array("id"=>"2","title"=>"myTitle2","score"=>"17","date"=>"2013-09-02"),
"obj3" => array("id"=>"3","title"=>"myTitle3","score"=>"18","date"=>"2013-10-02"),
)
);
Print the output using PHP like:
echo json_encode($query);
Then from the client-side (where JavaScript resides) load that JSON that you printed using PHP. This can be done easily using JQuery.
Like this:
$.get("test.php", function(data) {
alert("Data Loaded: " + data);
});
You can find more information about this here: http://api.jquery.com/jQuery.get/
Now you'll need to parse this data so that JavaScript can understand what you got as text from the server. For that you can use the JSON.parse method on the "data" object in the aforementioned example. Once parsed, you can use the object like any other object in JavaScript. You can find more information about JSON.parse here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
I hope that helps.

reading data from external file

I am new to both three.js and javascript so this might be a very noob question.
I have a list of json objects in a file which contains data as following:
[
{ "x":x,"y":y,"z":z ,"r":r},
{ "x":x2,"y":y2,"z":z2 ,"r":r2},
{ "x":x3,"y":y3,"z":z 3,"r":r3}
]
And render it on screen.
Its exactly an example here: http://mrdoob.github.com/three.js/examples/webgl_materials2.html
except that sphere values I am reading from a file?
How do i tweak the example above that i read the values from this file instead of directly hardcoding these values in js?
Please help
THanks
If all you want to do is separate the data from your application logic, then you don't need to create a JSON file and load it via Ajax, you can just create another JavaScript file and put the data in there.
For example:
// myData.js
var myData = [
{ "x":x,"y":y,"z":z ,"r":r},
{ "x":x2,"y":y2,"z":z2 ,"r":r2},
// ...
];
// --------------
// myApplication.js
// Here goes the three.js code and you can access the data here, for example
alert(myData[0].x);
In your HTML file, you have to include the data file first, so that all following scripts have access to the myData variabe:
<script src="myData.js"></script>
<script src="myApplication.js"></script>
<!-- this works to: -->
<script>
alert(myData.length);
</script>
If you want to or have to load the file via Ajax, have a look at this question: How do I load a JSON object from a file with ajax?.

CakePHP, pass parameter to js.php file?

Im trying to use PHP to generate a javascript file. I have the file included and all scripts are workning in it. The think i cant figure out is how i pass a parameter to this file?
To pass a parameter from the controller to the view i use:
$this->set('object_models', $object_models);
To pass it from the view to a element i use:
echo $this->element('pageElement', array('object_model' => $object_model));
Im including my js.php file by adding it in the view with:
echo $this->Html->script('modelDrawer.js.php?', false);
Have you considered using parseExtensions and including your JS file as a view for a controller that you can perform logic on directly?
This would work similarly to the way rss feeds and xml files are generated with Cake.
See this article
UPDATE
Go to your routes.php file, and add the line Router::parseExtensions('js');
Then, create a controller called, for the sake of this, DynamicController.php - and paste this in there:
class DynamicController extends AppController {
public $uses = array();
public function modelDrawer() {
// logic in here
$this->set( 'object_models', $object_models );
}
}
Create a view folder and view file:
/app/View/Dynamic/js/model_drawer.ctp
In that model_drawer.ctp file, you can place your view/script logic that you want to be cakeified.
You can then call your script like this:
<script type="text/javascript" src="/dynamic/modelDrawer.js"></script>
Give that a try!

Categories