How can I call npm module from PHP class - javascript

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

Related

How to pass entire ViewModel into External Javascript file in .net core mvc 3.1?

I would like to pass my entire ViewModel from a .cshtml file into an External Javascript that is included in the same cshtml file.
I have tried different solutions but none of them work. I first started with reguarl js variable in cshtml file and passed it into the external js file.
E.g for the below code when I click on the below button I get, Uncaught ReferenceError: myValue is not defined
**- in test.cshtml file:**
<button onclick="testAlert()"></button>
<script language="text/javascript">
var myValue = "myValue test";
</script>
<script src="~/js/test.js"></script>
**in test.js:**
/**
* This is a test alert function in external js.
* */
function testAlert() {
console.log(myValue);
}
The above is just a test for regular variables which if when it works, then I would like the below object in the external javascript like below.
***in test.cshtml:***
var customer = #Html.Raw(JsonConvert.SerializeObject(Model.CustomerDetails));
***Then in test.js***
function testAlert() {
console.log(customer.Names.FirstName);
}
As far as I know, if you want to pass the model to JS scripts, I suggest you could use #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(object model)) to convert the model to a json string as #Seabizkit suggests. Then you could convert this json to model in the js and read its property.
More details, you could refer to below codes:
Model class:
public class Course
{
public int CourseID { get; set; }
public string Title { get; set; }
public int Credits { get; set; }
public string SemesterNumber { get; set; }
}
In your view set a button like below:
<input type="button" onclick="testAlert()" value="test" />
Then add a script at cshtml like below:
#section scripts{
<script>
// Notice: we should add '' between the html.raw to set it as a json string.
var customer = '#Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model))';
</script>
}
Then in the another js file add below codes:
Since my model is just a simple model like this to test, if you want to use my codes, you should modify it.
function testAlert() {
console.log(customer);
var ce = JSON.parse(customer);
alert(ce.SemesterNumber);
}
Result:
i think.... you lookng for
var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
so in your case something like
function testAlert() {
var customer = #Html.Raw(JsonConvert.SerializeObject(Model.CustomerDetails));
var customerJson = JSON.parse(customer);
console.log(customerJson.Names.FirstName);
}
I got my own answer but was not fully satisfied with it yet, so didn't post until today.
Need more refinement though.
test.cshtml:
#using Newtonsoft.Json;
<script type="text/cshtml">
viewmodel = #Html.Raw(JsonConvert.SerializeObject(Model));
</script>
test.js:
at the top:
var viewmodel;
Only by doing this does it work correctly. Most similar to #brando Zang's answer except for the extra initializing part. Still not sure why it works without var or let in the main cshtml page.
Also, intellisense is not working yet on my external js file test.js.
But thanks a ton to Brando Zang and Sea Bizkut for taking the time to help me out.
Some findings which will be useful for other people:
In default .net core mvc 3.1 , the default json is automatically converting viewmodel values to camelcase from pascal case, so using newtonsoft instead keeps default functionality and naming conventions.
Can do it for default JSon parser itself in startup itself but it is a hassle, so using Newtonsoft instead.
Also for enum values, it takes the value and not the string by default. so in the model. e.g in js object for CustomerType you will get 0,1,2 instead of Standard, Premium or VIP. so to fix it,
(VB syntax below for enum - not able to show code indented properly in SO)
Public Enum CustomerType
Standard = 0
Premium = 1
VIP = 2
End Enum
TestModel.cs:
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
[JsonConverter(typeof(StringEnumConverter))]
public CustomerType CustomerType;

In Angularjs how do I load the same javascript file but pass different keys for different environment (Test, beta, prod)

in Angularjs in a html page I need to load an external javascript file:
<script src="https://www.my-url.com/js/my.js?Key=xxxxxxxx"></script>
But based on different env (test, beta, prod), I will have different Key.
How can I implement this like what we usually do using web.config in .net?
Edit:
I saw some answers, but seems not exactly what I need. so I elaborate my environment: I have a client side which is pure html and Angularjs, my server side is an Asp.net Web API web service. When I talk about web.config in the original post, I don't mean put the key in web.config, but something conceptually similar. I want this "config file" on the client side, not on my Web API.
You can use gulp-replace and automate it on your build time.
There are two issues to solve:
Getting web.config values into the angular app
Making use of the config to download a script
1. Getting web.config to the app:
I've detailed in a blog post the method I use. Essentially, use a custom angular provider in the applications .cshtml file. This will load all web.config items with the prefix of client:...
Used by the MVC controller:
public static class ApplicationConfiguration
{
private const string ClientAppSettingPrefix = "client:";
public static object GetClientConfiguration()
{
var clientConfiguration = new ExpandoObject() as IDictionary<string, Object>;
// Find all appSetting entries prefixed with "client:"
foreach (var key in ConfigurationManager.AppSettings.AllKeys.Where(key => key.StartsWith(ClientAppSettingPrefix)))
{
// Remove the "client:" prefix before adding to clientConfiguration
clientConfiguration.Add(key.Replace(ClientAppSettingPrefix, String.Empty), ConfigurationManager.AppSettings[key]);
}
return clientConfiguration;
}
}
Script added into the app's .cshtml file:
<!-- Inject the configuration -->
<script type="text/javascript">
(function() {
angular.module('client.config', [])
.provider('applicationConfiguration', function() {
var config = #Html.Raw(JsonConvert.SerializeObject(Model, new JsonSerializerSettings {ContractResolver = new CamelCasePropertyNamesContractResolver()}));
return {
config: config,
$get: function() {
return config;
}
};
});
})();
</script>
So now you can use it in you add as a normal dependency:
angular.module('app', [
// Add as a dependent module
'client.config'
])
.config([
'applicationConfigurationProvider', 'dataServiceProvider', function(applicationConfigurationProvider, dataServiceProvider) {
// Set the api root server configuration
dataServiceProvider.setApiRootUrl(applicationConfigurationProvider.config.apiRoot);
}
]);
2. Making use of config to download script
As suggested in other answers, use JQuery's getScript() function.
Other SO answers also suggest using a simple injection into the head if you don't want to depend on Jquery. Take a look at Single page application - load js file dynamically based on partial view for ideas
You have couple of options here.
Option 1:
Use Angular's http service to get script files dynamically as String and then use eval() function to execute resulting String.
References: eval Angular $http service
Option 2:
Use JQuery's getScript method
Example:
var keys={ 'prod':'prodKey',
'staging:='stagingKey',
'dev':'devKey'
}
//Assuming you have an variable storing modes like prod, staging or dev
var url='https://www.my-url.com/js/my.js?Key='+keys[ENVT.MODE];
$.getScript( url, function( data, textStatus, jqxhr ) {
console.log( data ); // Data returned
console.log( textStatus ); // Success
console.log( jqxhr.status ); // 200
console.log( "Script loaded successfully" );
});
Reference: getScript

JAX-RS JSON object to JavaScript

I am new to JAX-RS and trying to build a simple website interface.
So I have written a function returning a JSON object
like this:
#GET
#Path("/mypath")
#Produces (Mediatype.APPLICATION_JSON)
public String returnJson() {
String json = //.... fill String
return json;
}
which works well when browsing to this path.
On the other hand I have a UI page like this:
#GET
Produces(MediaType.TEXT_HTML)
public InputStream viewUI() throws FileNotFoundException {
File page = new File("page.html");
return new FileInputStream(page);
}
which works also.
Next thing I want to do is filling a dropdown list in my page.html with JavaScript, which also should not be a problem.
But I dont know how to get the JSON object to the JavaScript array (in page.html).
First of all, when using jaxrs, you don't need to convert objects to json. This is done automatically by jaxrs. Your method should return an object. As you asking to convert json into array, I assume, your method should return a List. Regarding of how to call and consume results from the rest service, as per Luts Horn comment, you need to use some sort of client side library, for example jquery.
You can look here http://www.tutorialspoint.com/jquery/jquery-ajax.htm

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.

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