CakePHP, pass parameter to js.php file? - javascript

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!

Related

reference javascript content coming from db instead of static file

I am developping an asp.net web application :
In the website folder, I have a folder called "integrations" containing a list of js files (name1.js, name2.js, name3.js ...)
A user makes a http request to a mvc controller method where he gives as input a "name".
This method gives the "name" as a property of a viewmodel to a razor view containing the following code :
This razor view is returned to the user.
The previous code is working well, but I would like to add an improvment. Actually you need to add a js file inside the folder integrations,
and you cannot do that when the application is running in production.
So I would like instead of having a script tag referencing a file placed inside the integrations folder to have a script tag containing a js content
coming from a data table like this :
name : jscontent
name1 : jscontent1
name2 : jscontent2
But I don't know how to changed this :
<script src="~/integrations/#(Model.Name).js"></script>
To :
<script>>query in db by #(Model.Name) parameter to get corresponding jscontent</script>
Make it a controller/method and you can take advantage of things like caching, auth etc for free:
public class ScriptController
{
public ActionResult Content(MyModel model)
{
var result = "alert("Hello World!");";
return JavaScript(result);
}
}
JavaScriptResult
Then in your html:
<script src="~/Script/Content?prop1=whatever"></script>

How can I call npm module from PHP class

I found a javascript plugin to convert HTML to markdown here https://github.com/domchristie/to-markdown.
I'm using Laravel 5. Let's say a user post an HTML string and I take the request from my PHP class. Here's my controller:
<?php
class TheController extends Controller
{
...
public function index()
{
$html_text = Request::input('html_text');
// Convert $html_text to $markdown
}
}
?>
If I were in a javascript file I could've called the function like this:
var toMarkdown = require('to-markdown');
toMarkdown('<h1>Hello world!</h1>');
How do I convert $html_text to $markdown without converting it to a text file and read it, if possible
You shouldn't use a npm package for that, there are plenty php packages to do this. You can find a lot of packages compatible with Laravel on packalyst.
For example:
http://packalyst.com/packages/package/alfredo-ramos/parsedown-extra-laravel

Print js file Yii2

Is there any way to print js file?
I know I can use register method of AssetBundle class to register a js/css file into page, also there is another option: to store javascript code in a php variable and use the following method:
\yii\web\View::registerJs($js, \yii\web\View::POS_READY);
But what I need is (on server-side) open a js file, get the contents and write down the code into the html.
The meaning of doing so is that the javascript code is needed only in one page, but also I don't want to add extra requests on client-side.
Also, I know, I can use php include method to load the file and store into a variable, but maybe there is a Yii-way.
So, is there any proper way to do so ? Any help will be appreciated.
Try this , I hope this will Help you.
<?php
$this->registerJs('
$(document).ready(function(){
$(\'.ordinary\').hide();
$(\'.special\').hide();
$(\'#company-typeofcompany\').change(function () {
var x = $(this).val();
if (x === "ordinary") {
$(\'.ordinary\').show();
$(\'.special\').hide();
} else {
$(\'.special\').show();
$(\'.ordinary\').hide();
}
});
});', \yii\web\View::POS_READY);
?>
Thank You..

embed javascript ojbect in jade template from controller

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

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.

Categories