i have a view,
<div class="square_box col-xs-7 text-right">
<span>Views Today</span>
<div class="number" id="myTargetElement1"></div>
</div>
so i want to pass some values from my database to this .js file the value 90 for instance i want to fetch it from the database
var demo = new CountUp("myTargetElement1", 12.52, 90, 0, 6, options);
demo.start();
please help me out cause am stuck trying to figure out how to use the php query script inside a js file found in the public folder
I would suggest to use the html tag attribute to store the values and then retrieve it in your JavaScript file.
HTML file:
<div class="square_box col-xs-7 text-right">
<span>Views Today</span>
<div class="number" data-value={{$value}} id="myTargetElement1"></div>
</div>
JS file:.
<script>
var value = $('#myTargetElement1').attr('data-value');
var demo = new CountUp("myTargetElement1", 12.52, value, 0, 6, options);
</script>
The easiest thing to do would probably be to use ajax to call a view and display that view inside of your html.
Here is a very crude example.
$.ajax({
url: "/path/to/your/view",
cache: false
})
.done(function( html ) {
$( "#myTargetElement1" ).append( html );
});
You've to use AJAX to fetch your data into your JS code and then use it.
Or you can simply fetch your result from db and pass it to your view.
$value = DB::table('your_table')->get();
return view('some_view', [ 'value' => $value ]);
Then simply just echo it out using {{ blade }} in your view file
<script>
var demo = new CountUp("myTargetElement1", 12.52, {{ $value }}, 0, 6, options);
</script>
Related
I need some help. How can I add new values in code to the list if I use a plugin from jquery. I wrote this code, but the list is empty, although the values are passed to the view. This is probably due to the fact that I am referring to the id of the div tag, but the plugin did not work differently. Help please
<html>
<main>
<form action="#">
<div class="form-group col-xs-12 col-sm-4" id="example-2"> </div>
</form>
</main>
<script>
$('#example-2').selectivity({
items: ['Amsterdam', 'Antwerp'],
multiple: true,
placeholder: 'Type to search a city'
});
function addOption() {
var ul = document.getElementById("#example-2");
for (var item in #ViewBag.List)
{
var value = item;
}
var newOption = new Option(value, value);
ul.options[ul.options.length] = newOption;
}
</script>
</html>
result of code from answer 1
The documentation of the selectivity library covers how to add new options to the dropdown.
The main issue you have is that the output from #ViewBag.List won't be in a format that JS can understand. I would suggest formatting it as JSON before outputting it to the page, then the JS can access this as a standard object, though which you can loop.
// initialisation
$('#example-2').selectivity({
items: ['Amsterdam', 'Antwerp'],
multiple: true,
placeholder: 'Type to search a city'
});
// add options, somewhere else in your codebase...
const $list = $('#example-2')
const options = #Html.Raw(Json.Encode(ViewBag.List));
options.forEach((option, i) => {
$list.selectivity('add', { id: i, text: option })
});
Note that for this to work the JS code which reads from the ViewBag needs to be placed somewhere the C# code will be executed, ie. in a .cshtml file, not in a .js file.
I am working on java and angularjs application.
I have a html page which iterates the object and display the values on page.
html code:
<div id="{{value.pageIndex}}" ng-repeat="(key, value) in employees" class="myDivClass">
<div>
<h1><font color="red"> {{value.pageHeader}}</font></h1>
</div>
<div>
<h1> {{value.pageIndex}}</h1>
</div>
<div>text from html page</div>
</div>
I should not enclose the above html code inside another div as it will fail my other scenario's in my application.
I want to export the above html content to the PDF when user click on a button, issue is when i'm trying to get the value from html page as shown in below js code, only first iterated data is exported where as i want the entire data to be exported to the PDF.
js code:
$scope.export = function() {
var pdf = new jsPDF('landscape');
source = $('.one1');
pdf.addHTML(source, 0, 0, {
pagesplit: true
},function(dispose){
pdf.save('test.pdf');
});
}
Please find the demo of the above scenario: https://plnkr.co/edit/6jNIu5c26ACeTPsfACX2?p=preview
Any suggestions on how to pass the dynamic generated ID's to the js code and export the entire html data to PDF? Is there any way to pass dynamic generated ID's to the js code and export the entire data to the PDF.
PS: I should not enclose the above html code inside another div as it will fail my other scenario's in my application.
Use the class myDivClass to fetch your data instead of using id attribute.
You can use jQuery .each() to fetch all the data.
Add append-source div to html
<body>
<div ng-controller="listController">
<button ng-click="export()">export</button>
<div id="{{value.pageIndex}}" ng-repeat="(key, value) in employees" class="myDivClass">
<div> <h1><font color="red"> {{value.pageHeader}}</font></h1> </div>
<div><h1> {{value.pageIndex}}</h1></div>
<div>text from html page</div>
</div>
</div>
<div id="append-source"></div>
</body>
Use this div to create pdf in JavaScript
$scope.export = function() {
var pdf = new jsPDF('landscape');
var source = $('#append-source');
$('.myDivClass').each(function(){
var html = $(this);
source.append(html);
});
console.log(source);
pdf.addHTML(
source, 0, 0, {
pagesplit: true
},
function(dispose){
pdf.save('test.pdf');
}
);
}
I'm trying to figure out if what I'm doing is the right way. I have a comment form and when it gets clicked I'm appending the comment into a div element through Ajax. When the page is refreshed then of course that would disappear and instead of it I have a foreach loop that runs and echos the comments. Since they both have the same CSS attributes they look the same to the user. The reason I'm doing it this way is because the foreach loop gets updated only after a refresh. Is there a better way? Can I update the page directly from the database without refresh? I basically need that every time a user clicks on the comment button that the foreach loop will run again but I couldn't find how to do it. I feel like I'm covering a gun shot with bandage the way I do it at the moment.
Loop:
#foreach($comment as $comments)
#if($comments->image_id == $image->id)
<div id="{{$comments->id}}" class="col-md-5 ajaxrules">
<div class="deletecomment">
<i class="fa fa-trash-o"></i>
</div>
<div class="col-md-2">
<img src="{{$comments->user_avatar}}" class="img-circle buddy">
</div>
<div class="hello col-md-10">
<h4>{!! $image->user_name !!}</h4>
<p class="left">{!!$comments->body!!} </p>
</div>
</div>
#endif
#endforeach
//Where I append the comments through Ajax until the refresh that replaces it with the loop
<div class="man">
</div>
Ajax:
<script>
$(document).ready(function(){
$('.send-form').click(function(e){
e.preventDefault();
var username = "{{ $username }}";
var one = $('textarea[id="{{$image->id}}"]').val();
var value = "{{$image->id}}";
var begin = '<div class="col-md-5 addavatar">'+'<div class="deletecomment">'+'<i class="fa fa-trash-o">'+'</i>'+'</div>'+'<div class="col-md-2">'+'<img src="{{$profile}}" class="img-circle">'+'</div>'+'<div class="hello col-md-10">'+'<h4>' + username +'</h4>'+'<p>'+one+'</p>'+'</div>'+'</div>';
if(one.length > 0){
console.log(username);
$('textarea[id="{{$image->id}}"]').val('');
$.ajax({
url: 'comment',
type: "post",
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
data: {'id': value, 'comment': one},
success:function(data){
$( ".man" ).append([begin]);
},error:function(){
console.log("error!!!!");
}
});
}
});
});
</script>
You are killing yourself.
Manipulate the DOM via javascript code like you do it's really hard work!
You are not suppose to write html inside javascript strings, there must be another way!
And there is... Welcome to AngularJS!
In angular you can write your html and assign a javascript controller to it, perform ajax request and after the ajax complete you can bind the returned data to the html automatically! That means the angular refresh your html and do all the work for you. Even perform loop of let's say, row in a table, etc...
is there any ways that JavaScript can get the variable from the controller in a Laravel Blade template?
Example:
I have the code below:
$langs = Language::all();
return View::make('NAATIMockTest.Admin.Language.index',compact('langs'));
Can I get $langs and pass it to JavaScript? I already used PHP-Vars-To-Js-Transformer. But when I use JavaScript::put() for two functions in the controller. It didn't work. Any help?
This is my create function in the controller:
public function create()
{
$names = $this->initLang();
Javascript::put([
'langs' => $names
]);
return View::make('NAATIMockTest.Admin.Language.create',compact('names'));
}
this is my view:
#extends('AdLayout')
#section('content')
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('langCtrl', function($scope) {
$scope.languages = langs;
});
</script>
<div class="container-fluid" ng-app="myApp" ng-controller="langCtrl">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">
<h2>Create language</h2>
</div>
<div class="panel-body">
{!! Form::open() !!}
<p class="text-center">
{!! Form::label('Name','Language: ') !!}
<input type="text" name="searchLanguage" ng-model="searchLanguage">
</p>
<select name="Name[]" multiple size="10" ng-model="lang" ng-click="show()">
<option value="#{{v}}" ng-repeat="(k,v) in languages | filter:searchLanguage">
#{{v}}
</option>
</select><br>
<div class="text-center">
{!! Form::submit('Create',['class'=>'btn btn-primary']) !!}
{!! Html::linkAction('NAATIMockTest\LanguageController#index', 'Back', null, array('class' => 'btn btn-primary')) !!}
</div>
{!! Form::close() !!}
</div>
</div>
</div>
</div>
</div>
#endsection
my javascript.php in config folder:
<?php
return [
'bind_js_vars_to_this_view' => 'footer',
'bind_js_vars_to_this_view' => 'NAATIMockTest.Admin.Language.create',
'bind_js_vars_to_this_view' => 'NAATIMockTest.Admin.Language.edit',
'js_namespace' => 'window',
];
The idea is:
I have a table language in MySQL. I want to show the dropdown list with multiple attributes to choose, and I also want to search with angularjs as well. That's why I want to pass the variable from the controller to JavaScript. Additionally, I have the function inside LanguageController called initLang to check if any language is exist inside the database, it isn't displayed inside the dropdown list in create the view.
One working example for me.
Controller:
public function tableView()
{
$sites = Site::all();
return view('main.table', compact('sites'));
}
View:
<script>
var sites = {!! json_encode($sites->toArray()) !!};
</script>
To prevent malicious / unintended behaviour, you can use JSON_HEX_TAG as suggested by Jon in the comment that links to this SO answer
<script>
var sites = {!! json_encode($sites->toArray(), JSON_HEX_TAG) !!};
</script>
Standard PHP objects
The best way to provide PHP variables to JavaScript is json_encode. When using Blade you can do it like following:
<script>
var bool = {!! json_encode($bool) !!};
var int = {!! json_encode($int) !!};
/* ... */
var array = {!! json_encode($array_without_keys) !!};
var object = {!! json_encode($array_with_keys) !!};
var object = {!! json_encode($stdClass) !!};
</script>
Displaying unescaped data - Laravel docs
json_encode - PHP docs
There is also a Blade directive for decoding to JSON. I'm not sure since which version of Laravel but in 5.5 it is available. Use it like following:
<script>
var array = #json($array);
</script>
Blade Templates - Laravel 5.5 docs
Jsonable's
When using Laravel objects e.g. Collection or Model you should use the ->toJson() method. All those classes that implements the \Illuminate\Contracts\Support\Jsonable interface supports this method call. The call returns automatically JSON.
<script>
var collection = {!! $collection->toJson() !!};
var model = {!! $model->toJson() !!};
</script>
When using Model class you can define the $hidden property inside the class and those will be filtered in JSON. The $hidden property, as its name describs, hides sensitive content. So this mechanism is the best for me. Do it like following:
class User extends Model
{
/* ... */
protected $hidden = [
'password', 'ip_address' /* , ... */
];
/* ... */
}
And somewhere in your view
<script>
var user = {!! $user->toJson() !!};
</script>
Serializing to JSON - Laravel docs
Let's say you have a collection named $services that you are passing to the view.
If you need a JS array with the names, you can iterate over this as follows:
<script>
const myServices = [];
#foreach ($services as $service)
myServices.push('{{ $service->name }}');
#endforeach
</script>
Note: If the string has special characters (like รณ or HTML code), you can use {!! $service->name !!}.
If you need an array of objects (with all of the attributes), you can use:
<script>
const myServices = #json($services);
// ...
</script>
Note: This blade directive #json is not available for old Laravel versions. You can achieve the same result using json_encode as described in other answers.
Sometimes you don't need to pass a complete collection to the view, and just an array with 1 attribute. If that's your case, you better use $services = Service::pluck('name'); in your Controller.
2022
Laravel has been updated so this can now be simplified to:
<script>const langs = {{ Js::from(Language::all()) }};</script>
Or, for any PHP object:
<script>const jsObject = {{ Js::from($phpObject) }};</script>
This also adds the JSON_HEX_TAGs mentioned in Ken's answer.
$langs = Language::all()->toArray();
return View::make('NAATIMockTest.Admin.Language.index', [
'langs' => $langs
]);
then in view
<script type="text/javascript">
var langs = {{json_encode($langs)}};
console.log(langs);
</script>
Its not pretty tho
The best way is to put it in a hidden div in php blade
<div hidden id="token">{{$token}}</div>
then call it in javascript as a constant to avoid undefined var errors
const token = document.querySelector('div[id=token]').textContent
// console.log(token)
// eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiI5MjNlOTcyMi02N2NmLTQ4M2UtYTk4Mi01YmE5YTI0Y2M2MzMiLCJqdGkiOiI2Y2I1ZGRhNzRhZjNhYTkwNzA3ZjMzMDFiYjBiZDUzNTZjNjYxMGUyZWJlNmYzOTI5NzBmMjNjNDdiNjhjY2FiYjI0ZWVmMzYwZmNiZDBmNyIsImlhdCI6IjE2MDgwODMyNTYuNTE2NjE4IiwibmJmIjoiMTYwODA4MzI1Ni41MTY2MjUiLCJleHAiOiIxNjIzODA4MDU2LjMxMTg5NSIsInN1YiI6IjUiLCJzY29wZXMiOlsiYWRtaW4iXX0.GbKZ8CIjt3otzFyE5aZEkNBCtn75ApIfS6QbnD6z0nxDjycknQaQYz2EGems9Z3Qjabe5PA9zL1mVnycCieeQfpLvWL9xDu9hKkIMs006Sznrp8gWy6JK8qX4Xx3GkzWEx8Z7ZZmhsKUgEyRkqnKJ-1BqC2tTiTBqBAO6pK_Pz7H74gV95dsMiys9afPKP5ztW93kwaC-pj4h-vv-GftXXc6XDnUhTppT4qxn1r2Hf7k-NXE_IHq4ZPb20LRXboH0RnbJgq2JA1E3WFX5_a6FeWJvLlLnGGNOT0ocdNZq7nTGWwfocHlv6pH0NFaKa3hLoRh79d5KO_nysPVCDt7jYOMnpiq8ybIbe3oYjlWyk_rdQ9067bnsfxyexQwLC3IJpAH27Az8FQuOQMZg2HJhK8WtWUph5bsYUU0O2uPG8HY9922yTGYwzeMEdAqBss85jdpMNuECtlIFM1Pc4S-0nrCtBE_tNXn8ATDrm6FecdSK8KnnrCOSsZhR04MvTyznqCMAnKtN_vMDpmIAmPd181UanjO_kxR7QIlsEmT_UhM1MBmyfdIEvHkgLgUdUouonjQNvOKwCrrgDkP0hkZQff-iuHPwpL-CUjw7GPa70lp-TIDhfei8T90RkAXte1XKv7ku3sgENHTwPrL9QSrNtdc5MfB9AbUV-tFMJn9T7k
Is very easy, I use this code:
Controller:
$langs = Language::all()->toArray();
return view('NAATIMockTest.Admin.Language.index', compact('langs'));
View:
<script type="text/javascript">
var langs = <?php echo json_decode($langs); ?>;
console.log(langs);
</script>
hope it has been helpful, regards!
if it's an array you may want to write it like this JSON.parse('{!! json_encode($months) !!}')
For anyone else still struggling.
For me in Laravel v9.2 has this worked.
<script> const something_var = <?php echo json_encode($example->something) ?>;</script>
View
<script>
var langs = JSON.parse({!! json_encode($langs) !!});
</script>
It's Simple and It worked for me...
Just pass the PHP variable into single quotes...
<script>
var collection = '{{ $collection }}';
</script>
so I'm trying to make this works here is the jquery+php.
When I try to trigle the click in jquery it doesnt even does the "alert()".
PHP(Updated):
$MSG_Notification_sql = mysqli_query($Connection, "SELECT * FROM notifications WHERE user_id='".$bzInfo['id']."'");
while ($MSG_Notification_row = mysqli_fetch_array($MSG_Notification_sql)){
$MSG_Notification_rows[] = $MSG_Notification_row;
}
foreach ($MSG_Notification_rows as $MSG_Notification_row){
$bzWhen = date('d-m-Y H:m:i', strtotime($MSG_Notification_row['when']));
echo '<form method="POST">
<div class="notificationClick notification-messages info">
<div class="user-profile">
<img src="assets/img/profiles/d.jpg" alt="" data-src="assets/img/profiles/d.jpg" data-src-retina="assets/img/profiles/d2x.jpg" width="35" height="35">
</div>
<div class="message-wrapper">
<div class="heading"> '.$MSG_Notification_row['title'].'</div>
<div class="description"> '.$MSG_Notification_row['description'].' </div>
<div class="date pull-left"> '.$bzWhen.'</div>
</div>
<input name="notificationID" value="'.$MSG_Notification_row['id'].'" style="display: none" />
<div class="clearfix"></div>
</div>
</form>';
}
Javascript(Updated):
$(document).ready(function(){
$('.notificationClick').click(function(event){
alert('Ok');
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = $('#notificationClick').serialize();
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : '../../class/notifications/msgs_del.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json' // what type of data do we expect back from the server
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
window.location = '/?page=messages&sub=inbox&bx=preview&id='+ data.notificationID +'';
});
event.preventDefault();
});
});
Can anybody help me please? I'm trying to complete this but nothing :(
First as the others say, ids need to be singular. So use the class you already have. Now inside, you need to use the current form that you clicked on, not all the forms.
$('.notification-messages').click(function(event){ //<-- change to class
var formData = $(this).closest("form").serialize(); //change to this
...
If you are loading these dynamically, you need to use event delegation
$(document).on("click", '.notification-messages', function(event){
var formData = $(this).closest("form").serialize();
...
You can concatenate the timestamp to your id to make it unique (separated by an _ if you like) and change your selector for the click event to $('[id*="notificationClick_"]')
On the other hand, you might want to use a class instead, that's what it's there for:
$(".notification-messages")
You're using ID, you can only bind click to 1 id not multiple ids.
You should use the class to bind the .click function.