Im learning laravel. I wanna ask a stupid question. Hope be helped from all of you.
When a controller return a view, I can send value blade template.
return view('home', ['message' => 'this is home page']);
I can get that from home.blade.php as:
<h1>{{$message}}</h1>
I can even send that value to javascript by the way below:
var message = "{{$message}}";
Yeah, that it!
But how can i send that value to separate javascript file.
/resources/views/home.blade.html:
<script src="/js/home.js"></script>
how can i get that value to /public/js/home.js if i dont use the way below?
<script>var message = {{$message}}</script>
<script src="/js/home.js"></script>
Thank for reading!
You can make a script tag contain all your dynamic values, and make your file
/js/home.js
use it
like this
<script>
var appSettings = {message :"{{$message}}"};
</script>
<script src="/js/home.js"></script>
so inside home.js
you can access this value
alert(appSettings.message);
Related
I have a js file located in assets folder (not View). can i pass a varible from a controller?
In view file:
The Js is called like this
<canvas id="chart1" class="chart-canvas"></canvas>
</div>
It is not possible (in my point of view) to put a variable to external JS file. You can use data-... attributes and get values from html elements.
For example you can pass your PHP variable as a json encoded string variable in your controller.
$data['chart_info'] = json_encode($chart_info);
return view('your_view', $data);
Then put it in data-info like this.
<canvas id="chart1" class="chart-canvas" data-info="{{ $chart_info }}"></canvas>
And finally in JS, you can get the variable and decode (parse) it as following.
let canvas = document.getElementById('chart1');
let info = JSON.parse(canvas.dataset.id);
console.log(info);
You can put that part of the Javascript in the view and send the variable to the same view. For example, add a section in view:
#section('footer')
<script type="text/javascript">
</script>
#endsection
Do not forget that you should add #yield('footer') to the end of your layout view.
I don't like to mix javascript and PHP/Blade, it might be hard to read the code in the future... You could use a different approach, loading the chart with a async ajax request.
You will have to create a end-point that returns the data you need for your chart:
Your router:
Route::get('/chart/get-data', [ ControllerName::class, 'getChartData' ]);
Your controller method:
public function getChartData() {
$chartData = [];
// Your logic goes here
return $chardData;
}
In your javascript (using jquery) file there will be something like that:
function loadChartData() {
$.ajax({
'url': '/chart/get-data',
'method': 'GET'
})
.done((data) => {
// Load your chart here!!!
})
.fail(() => {
console.log("Could not load chart data");
});
}
Hope I helped ;)
I have problem because im using angular with laravel.I added this in routes.php
Blade::setContentTags('<%', '%>'); // for variables and all things Blade
Blade::setEscapedContentTags('<%%', '%%>'); // for escaped data
But its not working because im getting an error when i display data from angular.
Any suggestion how can i fix this?
For example if i say:
{{'test'}} it works but if i say {{response.test}} where response is from angular i get an error because laravel thinks that is his.
Blade will ignore anything preceded by the # character. Try that.
first confing laravel blade and angular js
<script type="text/javascript">
var app = angular.module('myApp', [])
.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('<%=');
$interpolateProvider.endSymbol('%>');
});
</script>
write your angular code like this
<%= cs.Category_name %>
I have profile user page index.blade.php where I should to shoe Google map.
This template looks like:
#extends('users.index')
#section('content')
<script>Google scripts</script>
#endsection
So, when page is rendered I get outpus as:
<html>
<head></head>
<body>
<script>Google scripts</script>
</body>
</html>
So, when I do HTML validation onlne, I get error, that you can not use scripts in body. It should be in HEAD.
Is there an way to do this in Laravel?
I dont want to load Google script on each pages.
in index page make script in its head to check page URL and if matched requested url then load scripts in page like below
<script>
const RequestedUrl = window.document.URL;
function injectScript ( myScriptURL ) {
let script = document.createElement("script")
script.type = "text/javascript";
script.src = myScriptURL;
document.getElementsByTagName("head")[0].appendChild(script);
}
if(RequestedUrl === 'http://your.URL') { // or RequestedUrl.includes('/cats') for ex.
injectScript(//jquery script URL//);
injectScript(//google script URL//);
}
</script>
if it depended on jquery or any make sure to load it same way before google scripts
learn more
I am trying to configure ajaxAppender of log4javascript in DJango. I have made a file frontendlog.json where I want to write the logs going from the front end. This is how I write the script in myPage.html.
<script type="text/javascript" src="/static/js/log4javascript.js"></script>
<script language="javascript">
var url = '/frontEndLog/';
var log = log4javascript.getLogger("serverlog");
var ajaxAppender = new log4javascript.AjaxAppender(url);
ajaxAppender.addHeader("Content-Type", "application/json");
var jsonLayout = new log4javascript.JsonLayout();
ajaxAppender.setLayout(jsonLayout);
log.addAppender(ajaxAppender);
window.onerror = function(errorMsg, url, lineNumber){
log.fatal("Uncaught error "+errorMsg+" in "+url+", line "+lineNumber);
};
log.info("Front End Log");
alert('!!')
</script>
In my django urls.py I have this entry url(r'^frontEndLog/$', 'TryOn.views.frontEndLog'),
and in my django view I have this view function
def frontEndLog(request):
LOGGER.info ("frontEndLog")
return render_to_response('frontEndLog.json', mimetype="text/json")
So I expected the frontEndLog to be written in frontEndLog.json in the same location as other HTMLs are found in django. However, it tells me that XMLhttpRequest Request to URL returned status code 500. Can somebody please tell me where I am going wrong here and is this the correct way to use log4javascript in django?
I solved it. I printed the django request object in views.py. There I was able to find the log messages in the request.POST. It appears in the form of a dictionary since it is JSON-ified. You can access the logs with this
clientLogs = request.POST.get('data')
'data' is the key in the key : value pair here. (You can easily understand that when you see the POST object).
Whether you want to print it in the views.py itself or write it to a a txt file is up to you. So all this while the logs were actually getting logged without me being able to identify it! I guess I should have read the documentation better.
I am trying to pass the contents of a bean to javascript so that I can parse it and create a JSON object... (Yes I am still on ATG 9.1). However I am having trouble getting from serverside to client side.... I am new with this stuff and would appreciate any explanation as documentation on this is scarce and not helpful.
<dsp:tomap var="cartMap" bean="MyShoppingCartModifier.order" recursive="true"/>
<script>
var myCartMap = "${cartMap}";
//Logic (easy)
</script>
Doing this generates an "Uncaught SyntaxError: Unexpected token ILLEGAL" on my browser (Chrome)
Any wisdom will greatly help me in my quest in learning this stuff.
The problem is your usage of the tomap tag. You can't just pass in an entire tomap'd object because the tomap tag isn't going to create a nice, parsable json object.
You should either:
1) Format the json yourself right within your tags. Choose only the values that you want from the order.
<script>
var myCart = {
total : '<dsp:valueof bean="MyShoppingCartModifier.order.priceInfo.total">'
...
}
// Then use myCart for something here
</script>
or 2) There's a little known JSP to JSON library found here, http://json-taglib.sourceforge.net, that is very useful. To use that, you'd create a separate page, something like orderJSON.jspf, that is used to generate a pure json object from your order. Then in the page that you require this js, you can do:
<script>
var myCart = <%# include file="/path/to/orderJSON.jspf" %>
// Then use myCart for something here.
</script>