convert from PHP to JSON file to to draw chart wirth JS - javascript

i want to extract data from the database and send as JSON file to the front-end and then try to draw graph. i have three tables notification where the website url is saved, status that has status and speed( google page speed) and a pivot table where all data related to a website is stored as values. i have model, and inside the model, i have a function that makes many to many relations between notifications and status table.
i have a controller called chart controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ChartController extends Controller
{
public static function speedHistory(){
$o_status = Status::where('name','speed')->first();
$o_response = $this->statuses()->where('status_id', $o_status->id)
->select('values AS value', 'created_at AS timestamp')->orderBy('created_at','DESC')->get();
if($o_response){
return response()->json($o_response);
}
// return an empty json array instead of false
//return false;
return response()->json(array());
}
}
and a front end page called app.js
document.addEventListener('DOMContentLoaded', function(){
$.getJSON("/json", function (result) {
alert(result)
}
and a route
Route::get('json','ChartController#speedHistory');
i use alert to see,if the data is going to app.js but it doesnt work. i would apperciate nay kind of help and suggestions?
this is the view file
extends('layout')
#section('header')
<a class="logout" href="<?php echo 'login'?>">Logout</a>
<a href="{{ URL::to('/') }}">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/65/Crystal_button_cancel.svg/32px-Crystal_button_cancel.svg.png" alt="Submit" width="48" height="48">
</a>
#stop
#section('content')
<script src="app.js"></script>
<table class="table">
<thead>
<h3>{{ $notification->website_url }}</h3>
<tr>
<th>date</th>
<th>status</th>
</tr>
</thead>
<tbody>
<?php $notificationHealth = $notification->history('health'); ?>
#foreach($notificationHealth as $status)
<tr>
<td>{{ $status['timestamp'] }}</td>
<td> {{ $status['value'] }}</td>.
</tr>
#endforeach
</tbody>
</table>
<canvas id="pageSpeedHistoryChart" width="200" height="50"></canvas>
#stop
#section('footer')
#stop

Can you add more details?
With /json you are calling a page under the same domain. Is this right?
You can use developer tools of chrome. Under network tab you can see the response of the call that you have done.

Related

Ng-repeat is not working if page is loaded dynamicly

I have this page;
<script>
angular.module('myapp', []).controller('categoryCtrl', function($scope) {
$scope.category = <? echo json_encode($myarr); ?>;
$scope.subcategory = <? echo json_encode($myarr2); ?>;
});
</script>
<div ng-app="myapp" ng-controller="categoryCtrl" id="cate-container">
<div ng-repeat="x in category" class="cate-holder">
<div class="cate-class" onClick="opensubcate(this)">{{x.isim}}</div>
<div class="subcate-holder">
<div ng-repeat="y in subcategory | filter:{kategori:x.isim}" class="subcate-class">{{y.isim}}</div>
</div>
</div>
<div id="list-holder">
</div>
</div>
And with ajax i call this page into #list-holder.
<script>
angular.module('myapplist', []).controller('listCtrl', function($scope) {
$scope.list = <? echo json_encode($myarr3); ?>;
});
</script>
<div ng-app="myapplist" ng-controller="listCtrl" id="list-container">
<div ng-repeat="i in list">{{i.isim}}</div>
</div>
Everything works great and it is coming with $scope.list is defined with what i got from database. But ng-repeat="i in list" is not working and printing {{i.isim}} as it is.
If I open the second page directly it prints the outputs of i.isim
And the ajax for those who doubt ajax is not working well =)
$('.subcate-class').click(function(){
var thissub = $(this).text();
var thiscate = $(this).parent('.subcate-holder').prev('.cate-class').text();
$.ajax({
url:"php/salelist.php",
data:{kategori:thiscate,altkategori:thissub},
type:'POST',
success: function(e){
$('#list-holder').html(e);
}
});
});
Ah, I see the problem now that you've shared your Ajax call. And yes, this Ajax call is the problem.
What you're doing wrong is that you use jQuery and Angular together. Don't do that, ever. These are concurrent technologies that really don't work the same way. Angular generates the DOM from data, jQuery manipulates the DOM. In other words, jQuery fetches your data, but Angular has no idea about it, so it doesn't react and doesn't update the view.
Not to mention that you are loading two libraries instead of one.
Solution : DROP jQuery and do things the Angular way (use the $http service), or DROP Angular and do everything the jQuery's way.
pass the php variable values through ng-init function and then assign the list.
<div ng-app="myapplist" ng-controller="listCtrl" id="list-container"
ng-init="loadList('<? echo json_encode($myarr3); ?>')">
<div ng-repeat="i in list">{{i.isim}}</div>
</div>
angular.module('myapplist', []).controller('listCtrl', function($scope) {
$scope.list;
$scope.loadList($scope.list)
});
I have solved the problem with a bit of research. The ajax was not the main problem but the main problem was having two ng-app. The first one is rendering it-self automaticly but the second one doesnt render on document onload. Ajax was not the main problem as tried to predefine $scope.list and remove ajax, there was still ng-repeat problem. Then I understand the problem was second ng-app. I converted two page format into one page and removed second ng-app and put them all into first ng-app. Then I decided to use $http of angular, instead of $.ajax of jquery because there was no way to put $.ajax response into angulars $scope.list. The final is this;
PS: ng-repeat doesnt need any $apply or something because when var change it renders again automaticlly.
<script>
angular.module('myapp', []).controller('categoryCtrl', function($scope, $http) {
$scope.category = <? echo json_encode($myarr); ?>;
$scope.subcategory = <? echo json_encode($myarr2); ?>;
$scope.liste;
$scope.clickfunc = function(e){
$scope.thissub = $(e).text();
$scope.thiscate = $(e).parent('.subcate-holder').prev('.cate-class').text();
$http({
method : "POST",
url : "php/salelist.php",
params:{kategori:$scope.thiscate,altkategori:$scope.thissub}
}).then(function mySuccess(response) {
$scope.liste = response.data.list;
}, function myError(response) {
$scope.liste = response.statusText;
});
}
});
</script>
<div ng-app="myapp" ng-controller="categoryCtrl" id="cate-container">
<div ng-repeat="x in category" class="cate-holder">
<div class="cate-class" onClick="opensubcate(this)">{{x.isim}}</div>
<div class="subcate-holder">
<div ng-repeat="y in subcategory | filter:{kategori:x.isim}" class="subcate-class" ng-click="clickfunc($event.target)" onClick="showem()">{{y.isim}}</div>
</div>
</div>
<div id="list-holder">
<div id="list-container">
<div id="back" onClick="goback()"><</div>
<input type="text" ng-model="filterem" id="filterem" placeholder="Ara...">
<table class="urun-table">
<tr><th width="31%"></th><th width="10%">Kategori</th><th width="10%">Altkategori</th><th width="31%">İsim</th><th width="7%">Stok</th><th width="11%">Fiyat</th></tr>
</table>
<div id="table-scroll">
<table class="urun-table">
<tr ng-repeat="i in liste | filter:filterem" class="urun-holder">
<td width="33%"><img src="urun/{{i.resim}}" class="urun-img"></td>
<td width="10%" class="urun-cate">{{i.kategori}}</td>
<td width="10%" class="urun-sub">{{i.altkategori}}</td>
<td width="33%" class="urun-name" onClick="details(this)">{{i.isim}}</td>
<td width="7%" class="urun-price">{{i.stok}}</td>
<td width="7%" class="urun-stock">{{i.fiyat}} TL</td>
<td style="display:none" width="0" class="feed">{{i.feed}}</td>
<td style="display:none" width="0" class="origin">{{i.origin}}</td>
<td style="display:none" width="0" class="feature">{{i.feature}}</td>
</tr>
</table>
</div>
</div>
</div>
</div>

Meteor JQuery Start Rating Issue

I am getting issues trying to use the follow Meteor Package: dandv:jquery-rateit.
I am using it for a ticket system where each update will have a start rating. But when I have more than 1 comment the second one always return 0 value.
Here is my code:
JS:
Template.rating.events({
'click .rateit': function(e){
var rating = $('#rate').rateit('value');
console.log(rating);
Session.set('UpdateId', this._id);
var UpdateId = this._id;
console.log(UpdateId);
/*Meteor.call('saveRate',rating,UpdateId);*/
return false;
}
});
Template.rating.rendered = function () {
this.$('.rateit').rateit();
}
HTML:
<template name="Update">
{{#each Updates}}
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title" align="center">Update</h3>
</div>
<div class="panel-body">
<table class="table">
<tr>
<td width="15%" nowrap align="left">Created By:</td>
<td width="35%" align="left">{{createdBy.username}}</td>
<td width="15%" nowrap align="left">Created At:</td>
<td width="35%" align="left">{{formatDate createdAt}}</td>
<td width="15%" nowrap align="left">Rating:</td>
<td width="35%" align="left">{{> rating}}</td>
</tr>
<tr>
<td colspan="4">{{description}}</td>
</tr>
</table>
</div>
</div>
{{/each}}
</template>
<template name="rating">
<div class="rateit" id="rate"></div>
</template>
Now when I try to rate the second comment is return 0. Screenshot: http://screencast.com/t/ejaTI98X
No matter what star do I select, it always return 0. I think that the error should be probably in the HTML.
I really appreciate all your help on it. If you have any question just let me know.
Have a great day.
You iterate over Updates and I assume there are more than one update. For each update you call the template {{>rateit}} which then renders a div with id=rate, so you will end up with several divs with the same id, so you don't really know which one $('#rate') you are accessing.
In your event handler you also use the global jQuery handler.
I suggest you use the following pattern instead to scope jQuery local to the templates context
Template.rating.events({
'click .rateit': function(e,template){
var rating = template.$('.rateit').rateit('value');
console.log(rating);
Session.set('UpdateId', template.data._id);
var UpdateId = template.data._id;
console.log(UpdateId);
/*Meteor.call('saveRate',rating,UpdateId);*/
return false;
}
});

How to call a controller function from another controller component and pass control to the called controller component

I have HTML structure like this
<aside class="side" align="left">
<table onclick="reply_click(event)" ng-controller="TableCtrl" >
<tr ng-repeat = "table in tables">
<td><button id = "{{table}}" width = "70">{{table}}</button></td>
</tr>
</table>
</aside>
<article class="tabs">
<section id="erd">
<h2>ERD</h2>
<p>This content appears on tab ERD.</p>
</section>
<section id="col">
<h2>Columns</h2>
<h2>Columns</h2>
<div id="list" ng-controller="ColCtrl">
<table>
<tr>
<th>Column Name</th>
</tr>
<tr ng-repeat="column in columns">
<td>{{column.name}}</td>
</tr>
</table>
</div>
</section>
<section id="home">
<h2>Home</h2>
<p>This content appears on tab Home. lfkdgl;k lkfd;lkg ';lkfg ;lkg 'df;lk ;lk ';lk ';fdlkg ';fdlkg';dflk;ldfkg';lkdlfkdfkglkdf lkjhlsdjhfljdfhlkjdh jh jhkjdhfkjsdhf skjdhf lk h dsfjlkjsdlkfj;dslkfj dskfj;kj sdfkj fkdj;lfkjsd;lkfj sdkfj ;slkj sdfj;lskjf skdj flksjdf ; sdfkj ;sdlkfj dskfj sdkjfhueuu suehu heu he u heu heh ueh ufhu fhe uueh ush uhsudh ue huhuhufheuheu u heiu h euh eh ue </p>
</section>
</article>
I used the suggestions from this SO answer to call a controller
AngularJS. How to call controller function from outside of controller component
The controller I and calling is
angular.element(document.getElementById("list")).scope().loadColumns();
It fires correctly. The problems I am calling it from a button in TableCtrl component. After loadColumns() is fired it went to the TableCtrl component to loop which is the wrong place. How can I tell it to go to the correct place ColCtrl area to loop and populate data?
Thanks,

Pass object to isolated directive

When my application loads a function to get items from a server runs, this function get the title and Id of all items on the server,
then puts them in an array.
In my main html I have a table that displays this array, and when i click the title of an Item, I call another function (onView)
which gathers more information about that item from the server. This new information is passed to
a variable called '$scope.currentItem'.
I also have a directive called 'currentItem', this is used to display that item for the user.
myApp.directive('currentItem',function(){
return{
restrict:'E',
scope:{
data:'='
},
templateUrl: 'currentItem.html',
controller:function($scope){
}
};
});
To know if a user has clicked an item I have a boolean called isView, so when the function to gather more information runs
the isView is set to 'true'.
My html looks like this:
<div ng-app="myApp">
<hr>
<div ng-controller="appCtrl">
<div ng-hide="isView" class="col-md-12">
<table id="mainTable" ng-table="tableParams" class="table">
<tbody ng-repeat="item in items">
<tr>
<td id="Title" data-title="'Title'">
{{item.id}} |<a ng-click="onView(item.id)">{{item.title}}</a>
</td>
<td data-title="'Description'">
{{item.description | date:'dd-MM-yyyy'}}
</td>
<td data-title="'Created'">
{{item.created | date:'dd-MM-yyyy'}}
</td>
</tr>
</tbody>
</table>
</div>
<div ng-show="isView" class="col-md-12">
<current-item data="currentItem"></current-item>
</div>
</div>
</div>
This can't be the correct way to pass an object to a directive, seeing I always use the same 'currentItem' object.
How could I improve this, so that each object is isolated and editable in a seperate view?

Jquery total noob import inquiry relating to where to put files

I downloaded the Jquery Raty plugin: https://github.com/wbotelhos/raty
Then I installed this folder structure into my {{static_url}}js folder and named it Raty.
Then I imported it into my template as follows and put the path as the location of where its images are stored.
<script type="text/javascript" charset="utf-8" src="{{ STATIC_URL }}js/raty/js/jquery.raty.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('.thingrating').each(function(index){
$(this).raty({
readOnly: false,
path: "{{ STATIC_URL }}js/raty/img/",
start: $(this).children("span:first").text(),
click: function(score, evt) {
var vote_url = "rate/" + this.attr('id').substring(2) + "/" + score + "/";
$.ajax({
url: vote_url,
success: function(){
alert('vote successful');
}
});
}
});
});
});
</script>
Is this correct? I'm not seeing that it is working in my template, so want to make sure this process of storing the script and importing it into my template is correct before I continue to decipher what is wrong...
Here's the rest of my template:
{% block body %}
<h2>Things</h2>
<div class="block" id="block-tables">
<div class="content">
<p></p>
<div class="inner">
<table class="table">
<tr>
<th class="first">Name</th>
<th class="last">Rating</th>
</tr>
<tr class="odd">
<td>{{ item.modelname }}</td>
<td><div class="thingrating" id="t_{{ item.id }}"><span style="display:none;">{{ score }}</span></div></td>
</tr>
</table>
<div class="actions-bar wat-cf">
</div>
</div>
</div>
</div>
{% endblock %}
Take a look at this jsfiddle demo. It works fine (well, except that looks like start should be changed to score as I understand that way you want to define initial score). Incorrect path to images will not break it at all. Browser will simply show default icon for not available image if path to images is wrong. Not sure what is in {{static_url}} variable. If it contains something like 'http://example.com/static' - you must add a slash after it.
Possible problems - script tag for raty appears before jQuery. Or results of template processing are not available on page when $(document).ready event happens.

Categories

Resources