How can I succssefully acces an Global Variable from PHP in HTML - javascript

Pre Info:
In the PHP I declare a global array ($GLOBALS[]), in it I stow the data for the blade.
On the Blade i have a dropdown. If the dropdown changes, i send via AJAX the value to the Controller.
With the new data i calculate the new information, i want to show on the Blade.
But when I try to get the data in HTML like {{$GLOBALS['MyNumber']}} I only get the initialization value.
<?php
.
.
.
$GLOBALS = array(
'MyNumber' => 1,
'companyCode' => 0
);
class MyClass extends Controller
{
public function getData(){
$GLOBALS['companyCode'] = #$_POST['companyCode'];
if ($GLOBALS['companyCode'] == 902){
$GLOBALS['MyNumber'] = 100; //for the example, I set the data fix
}else{
$GLOBALS['MyNumber'] = 20; //for the example, I set the data fix
}
return response()->json(array('AJAX succses' => $response), 200);
}
.
.
.
In HTML i wanna show an dashboard-card with the new data like this:
I have 4 Cards and 7 Tables with data from SQL.
#section('page_content')
<div class="card #if($GLOBALS['MyNumber'] >95) dashboard-card-success #else card-anger-#endif" id="bkfI">
<div class="dashboard-title">
{{ __('bkf_usage') }} {{ today()->year }}
</div>
<div class="dashboard-content">
<div class="dashboard-number" id="bkf_usage">{{$GLOBALS['MyNumber'] }} %</div>
<div class="dashboard-description"></div>
</div>
</div>
But every time i reload the div (so the color can change) the $GLOBALS['MyNumber'] stays on the init of 1.
But the internal use (if $GLOBALS['companyCode']) works fine. How can i solve this issue? Or can you help me to find a work-around?
Maybe pass all the Vars back via ajax to JS and store tem in an JS variable? So i can still access from HTML to them?
Thank You!

Related

Laravel- How to "catch" a variable with Javascript passed to a blade.php view

so i'm currently working on a project and i want to add a calendar to one view, i'm using FullCalendar, the calendar is shown in the view but i'm currently trying to add events to that calendar, those events are going to be "pulled" from my database into the calendar to be displayed, now the problem is that when i pass the array with the events to the blade.php view that contains the calendar a error comes up saying that the variable "events" is undefined and i don't know if i'm doing something wrong, here's the code:
RegisteredUserController.php
$events = array();
$citas = Cita::all();
foreach($citas as $cita){
$events[] = [
'title' => $cita->paciente_id,
'start' => $cita->hora_de_inicio,
'end' => $cita->hora_de_finalizacion
];
}
return redirect(RouteServiceProvider::HOME)->with(['events' => $events]);
RouteServiceProvider.php
public const HOME = '/home';
homeView.blade.php (This is where i get the error, in the line where i assign it to citas)
<div id="calendar">
</div>
<script>
$(document).ready(function(){
var citas = #json($events);
$('#calendar').fullCalendar({
header: {
left: 'month, agendaWeek, agendaDay',
},
events: citas
})
});
</script>
routes / web.php
Route::get('/home', function (){
return view('homeView');
})->name('homeView');
Not sure if it's helpful but i'm using Laravel's Breeze to handle the authentication of users, so when an user is aunthenticated they're redirected to the page where the calendar is.
i've tried the following
RegisteredUserController.php
return redirect(RouteServiceProvider::HOME, compact('events));
This one makes the whole calendar disappear:
homeView.blade.php
var citas = {{ Session::get('events') }};
Thank you in advance.
the return should be like this
return view('path_of_the_blade', compact('events'));
So then in View, you can use
<script>
var citas = #json($events);
</script>
On you controller, why don't you just simply use:
return view('homeView')->with(['events' => $events]);
or simplier:
return view('homeView', compact('events'));
This would surely pass the variable events on the blade file.
Then on your blade file, you will just reference it as:
var citas = {{ $events }};

Retrieve Firebase database specific value depending on key with angular 5

as the title says I build a CRUD application using Angular 5 and CRUD works just fine but now I need to retrieve a specific post data with advanced routing so the url should be something like :
https://example.com/blog/howtoDoSomething
and the page should contain this post details like name, content , image and so on .
I tried
details.component.ts
this.sub = this.route.params.subscribe(params => {
this.key = params['$key'];
});
details.component.html
<p>
this page about {{ $key }}
</p>
the above code worked fine with angular 4 with some difference of course and I used a json file not Firebase .
I also tried this one :
details.component.ts
var x = this.blogService.getData();
x.snapshotChanges().subscribe(item => {
this.blogList = [];
item.forEach(element => {
var y = element.payload.toJSON();
y["$key"] = element.key;
this.blogList.push(y as Blog);
});
});
details.component.html
<div *ngFor="let blog of blogList">
{{blog[$key].title}}
</div>
this one if I use blog alone like :
<div *ngFor="let blog of blogList">
{{blog}}
</div>
this retrieves the whole database as as
[object object] repeated
thanks in advance .
// user-service.ts
public getUser(userId: string) {
return this.afs.doc('users/' + userId).valueChanges();
)
// user-component.ts
// Get userId from route
this.user$ = this.userService.getUser(userId);
// user-component.html
<div *ngIf="user$ | async as user">
{{user | json}}
</div>

how to load the content of a show method in laravel on the index method using jquery

i have two methods show and index
i have a list of items on the index method that when a user clicks it takes her to another page containing some data that belongs to that id. instead of doing it such way i want to use jquery to achieve this, to make the data load on the same page. i have the following on my index.blade.php view, please how do i achieve this in laravel
#foreach ($categories as $category)
<div class="body">
<h4><a style="text-decoration: none; " href="{{ URL::route('category.show', $category->id) }}">{{$category->name}}</a></h4>
</div>
#endforeach
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use illuminate\HttpResponse;
use App\Http\Requests\todolistRequest;
use App\Http\Requests\CreateCategoryRequest;
use App\Http\Requests;
use App\Companylist;
use App\Category;
use Illuminate\Support\Facades\DB;
class CategoryController extends Controller
{
public function create(){
return view('category.create');
}
public function index(){
$categories=Category::all();
return view('category.index',compact('categories'));
}
public function store(CreateCategoryRequest $request){
$category = new Category($request->all());
$category->save();
return \Redirect::route('category.create')->with('message', 'Your list has been created!');
}
public function show($id)
{
$category = Category::findOrFail($id)->companylist()->get();
$cat=Category::findOrFail($id);
// this my route
Route::resource('category','CategoryController');
return view('category.show')->with('category', $category)->with('cat',$cat);
}
//
}
To show details data on index page without page refreshing , you should use ajax , in ajax return data and show it in index page ( i.e. under each list )
In ajax you have to pass the id and depending on id return corresponding data.
Hope it helps

Jquery Classes and InnerHtml

So what I'm doing is pulling battery voltage and the state of a battery from a Mysql database processing the data in data.php and putting that into a Json array all that is fine. When I get to the Javascript side I get stuck.
2 Questions:
Question 1: How do insert the value into id voltage in html without removing the span?
HTML Code:
<div id="voltState" class="tile-box bg-green">
<div class="tile-header">
Battery Status
<div class="float-right">
<i class="glyph-icon icon-bolt"></i>
Green
</div>
</div>
<div class="tile-content-wrapper">
<i class="glyph-icon icon-database"></i>
<div id="voltage" class="tile-content">
<span>volts</span>
</div>
</div>
</div>
Questions 2: class="tile-box bg-green"> I want to replace with the var status from the Javascript so it looks something like class="tile-box bg-(status var here)">
$(document).ready(function() {
sensorData();
});
function sensorData(){
$.ajax({
type:'GET',
url:"data.php",
data:"json",
success:function(sensor) {
//document.write(sensor);
var volt = sensor[0];
var status = sensor[1];
var date = sensor[2];
document.getElementById('voltage').innerHTML = (volt);
$("#voltState").toggleClass('bg-green bg-(STATUS VAR HERE??)');
},
dataType:'json'
});
}
setInterval(sensorData, 3000);
You can use $("#voltage").append(volt) or $("#voltage").prepend(volt) based on if you want the span before or after the value. In this case I assume you want the span after the volt so you can use the second code. If you would like the value inside a new span you can also use:
$("#voltage").prepend($("").text(volt));
You can store the previous status value in a variable lets say pastStatus. So once you have set
$("#voltState").removeClass('bg-'+pastStatus).addClass('bg-'+status);
pastStatus = status
Note: toggleClass is used when you want to switch between adding and removing the same class. It can't be used in this case since you want to add a class and remove another.
document.getElementById('voltage').appendChild(volt);
or
document.getElementById('voltage').innerHTML = '<span>'+volt+'</span>';

Sorting out array of parent child relations where two children share a parent from an array and display it using div

I have the following data which gets served from a neo4j query, The data that gets sent back is in the format
home->parent->child1
home->parent->child2
home->parent2->child1
home->parent3->child1
home->parent3->child2
home->parent3->child3
I am trying to use javascript to display html which should be like this
<div id="parent1">
<div id="child1"></div>
<div id="child2"></div>
</div>
<div id="parent2">
<div id="child1"></div>
</div>
i tried loopong throigh the query and trying to get the parent to be the index of an object and the child to be values under it
i would do this like this in php
$jsonContents = (object)("parent"=>"child","parent"=>"child"....);
$array = array();
foreach($jsonContents as $jsCo=>$jsoCont){
$array[$jsoCont->parent][] = $jsoCont->child;
}
this would return the
$array as
home->parent1->[0]->child
->[1]->child
parent2->[0]->child...
This would let me avoid the check for uniqueness of the home parent category as well as put them in a hierarchy so i can interpret it properly in my View part of MVC, to create my div structure.
this is the url for the example json data
http://www.jsoneditoronline.org/?id=bdda268982eb431d361c25e9035bbc99
No answers to this, solved it by myself.
Here
var data = 'data shown in link above';
var myArr = [];
$.each(data, function(index, element) {
var parent = String(element.parent.properties.name);
var child = String(element.child.properties.name);
if(myArr[parent]){
myArr[parent][(myArr[parent].length)] = child;
} else {
myArr[parent] = Array(child);
}
});
Hope this helps people. :)

Categories

Resources