AngularJS ng-repeat for one row in PDO fetch - php

I am newer to Angular and seem to be having difficulty finding out why I'm getting blank fields. I'm using the 1.7.7 version of angular-min and angular-route.
The data is being pulled from a table called "news" and I am only needing the ID and ARTICLE columns. The ARTICLE column is stored from a CKEditor textarea.
My route looks like:
var app = angular.module("HabbfinityApp", ["ngRoute"]);
app.config(['$routeProvider','$locationProvider',
function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when("/", {
templateUrl : "home.php"
}).when("/home", {
redirectTo : "/"
}).when("/news", {
templateUrl : "news.php"
}).when("/newsinfo/:id", {
templateUrl : "newsinfo.php",
controller: "newsList"
}).otherwise({
redirectTo : "/"
});
}]);
app.controller("newsList", function($scope, $http, $routeParams){
var id = $routeParams.id;
$http.get("newsitem.php?id=" + id)
.then(function(resp){
$scope.item = resp;
});
});
app.filter('unsafe', function($sce) {
return function(val) {
return $sce.trustAsHtml(val);
};
});
My newsitem.php looks like:
<?php
require('config2.php');
$id = $_GET["id"];
$newsQuery = $dbh->prepare("SELECT id, article FROM news WHERE id=:id LIMIT 1");
$newsQuery->execute(array(":id"=>$id));
$newsQueryData = $newsQuery->fetch(PDO::FETCH_ASSOC);
echo json_encode($newsQueryData);
?>
My newsinfo.php looks like:
<div class="row">
<div class="col-md-12">
<div class="panel-default panel-custom">
<div class="panel-heading">
<h3 class="panel-title"><i class="fa fa-lg fa-newspaper-o" aria-hidden="true"></i> News</h3>
</div>
<div class="panel-body">
<div ng-controller="newsList">
<div ng-repeat="x in item">
<img src="assets/images/news.png" alt="News" class="img-center img-responsive">
<br>
Tweet
<br>
<br>
<p ng-bind-html="x.article | unsafe"></p>
</div>
</div>
</div>
</div>
</div>
</div>
ISSUE
After the first image, twitter button and actual article, everything gets repeated another five times, so I end up with six images and six tweet buttons where the ID of the repeated five is blank.
Here's a var_dump using htmlentities so you can see exactly what those columns are pulling in.
string(899) "{"id":"610","article":"<p style=\"text-align:center\"><strong><span style=\"font-size:26px\">All of us at habbfinity would like wish our<\/span><\/strong><\/p>\r\n\r\n<p style=\"text-align:center\"><strong><span style=\"font-size:26px\">Builder<\/span><\/strong><\/p>\r\n\r\n<p style=\"text-align:center\"><strong><span style=\"color:#2980b9\"><span style=\"font-size:48px\">Sarah<\/span><\/span><\/strong><\/p>\r\n\r\n<p style=\"text-align:center\"><img alt=\"Image result for happy birthday gif\" src=\"http:\/\/bestanimations.com\/Holidays\/Birthday\/flowers\/happy-birthday-vintage-roses-gold-gif.gif\" \/><\/p>\r\n"}"
I've tried doing:
<div ng-repeat="x in item | limitTo: 1">
That doesn't work.
TEMP FIX
After reading through some of the posts on here, I managed a temporary fix.
I added the following to the newsList controller:
$scope.id = $routeParams.id;
I then changed newsinfo.php by moving the image and twitter button outside of ng-repeat and changed {{x.id}} in the twitter link to {{id}}.
QUESTION
How can I fix this to allow everything to be within the ng-repeat without having to use the temporary fix?
Or is what was done for the temporary fix the better way of doing it anyway?
EDITED ANSWER / QUESTION
Thanks to the suggestion below, I was able to get this resolved.
However, I have one more question.
Is there a way to do this on one page? For example, news.php is just a list of news posts and newsinfo.php is the single news post. Am I able to do something to get it all on news.php and keep the route to only /news, which would show the list if the route isn't news/# or show the specific item if the route is news/#?

Related

show the section based on page

I have created filter section with filter.blade.php.I have 5 selectbox in that page.I want to display only four in page1 and 5 selectbox section in page2.
In web.php
Route::get('/page1',array('middleware'=>'checksession',function(){return View('layouts.page1');}));
Route::get('/page2',array('middleware'=>'checksession',function(){return View('layouts.page2');}));
I want to display below selectbox only in page2
<div class="col-md-12">
<!-- Card header -->
<div class="card-header" role="tab" id="headingFive5">
<a class="collapsed" data-toggle="collapse" data-parent="#accordionEx" href="#collapseFive5"
aria-expanded="false" aria-controls="collapseFive5">
<h5 class="mb-0">
<div id="username_view">Username</div>
<img src="img/chevron-down.png" class="fa-angle-down rotate-icon">
</h5>
</a>
</div>
</div>
There are several ways of doing it like you are able to pass pass your current route variable as the second argument of your view.
Route::get('/page2',array('middleware'=>'checksession',function(){
$route = Route::current();
return View('layouts.page2',, compact('route'));
}));
after this pass condition over the route variable to satisfy your need.
another way is you are able to check this in your blade template directly by this:
#if(Request::url() === 'your url here')
// code
#endif
i hope this guide you. Read this for more understanding Accessing The Current Route

Angular ng-repeat not showing data on laravel?

The console shows that the posts were retrieved successfully, the backend works fine without the angular compatibility.
and its supposed to retrieve post data.
angular.js:12701 XHR finished loading: GET
"http://127.0.0.1:8000/auth/posts".
however it shows 5 empty divs like the following
main.js
$http.get('/auth/posts').then(function(data){
$scope.myposts = data;
});
PostController
public function getPosts()
{
$posts = Post::all();
return json_encode($posts);
}
Route
Route::get('auth/posts', 'HomeController#getPosts');
the html file
<div id="mypost" class="col-md-8 panel-default" ng-repeat="post in myposts">
<div id="eli-style-heading" class="panel-heading"><% post.title %></div>
<div class="panel-body panel">
<figure>
<p> <% post.body %></p>
</figure>
</div>
</div>
You need to access the data property from the response, I think you need,
$http.get('/auth/posts').then(function(data){
$scope.myposts = data.data;
});

How to check another table's columns and get their values to the other table

i am struggling over this problem
Shortly, i have payments page. Admin selects the user and course, then he should select course_type,which gets value from courses table's three columns(cost_group, cost_minigroup, cost_individual,one of them). If course_type is selected, the cost of course must be
inserted into payments table(inside course_cost column). So what i have done
Tables:
payments{ id,student_id, course_id, course_cost}
courses { id, name,cost_group,cost_minigroup,cost_individual }
My CourseController.php
> public function get($id){
> $course = Course::findOrFail($id);
> return response()->json($course);
> }
Here is my form.blade.php
<div class="ui selection dropdown">
<input type="hidden" name="course_">
<i class="dropdown icon"></i>
<div class="default text">Course type</div>
<div class="menu">
<div class="item" data-value="course_group">Group</div>
<div class="item" data-value="course_minigroup">Mini Group</div>
<div class="item" data-value="individual">Individual</div>
</div>
</div>
My PaymentsController
public function store(){
$payment = new Payment;
$payment->student_id = Input::get('student_id');
$payment->course_id = Input::get('course_id');
$payment->course_cost = Input::get('course_cost');
$payment->save();
return redirect('payment');
}
So here is problem how to get this course_cost value out of three columns of courses table. If you know how to solve or any method or advice would be great. Thank you in advance guys.
You should better get the values by js.and in your field(drop-down) there should be this code instead
<div class="menu">
<div class="item" data-value="{{$data['course_group']}}">Your call1</div>
<div class="item" data-value="{{$data['course_minigroup']}}">Your call2</div>
<div class="item" data-value="{{$data['course_individual']}}">Your call3</div>
</div>
And then You should insert some controller code
$payment->course_cost = Input::get('course_val');
And try this on your .js file
$('.course_val').click(function({
$('#course_val').val($(this).attr('data-value'));
alert('Your alert')
}))
On your blade, I see that you named the input as course_ not so sure since the HTML snippet is incomplete, but it may be the cause of your problem.
Better try to check what are you getting before storing it to anything, try to run dd(Input::all()) first as a start for debugging.
As for getting the value of the course cost, there is a lot of approach, one is ajax the updating the fields.

Multiple Jplayer audio players from Laravel DB

I'm trying to create multiple instances of Jplayers that each play a different audio file from my Laravel Database (table called archives) and i'm stuck at the point the jQuery code meets the Laravel code.
So far the audio players play but they play the same file.
also i have trouble when i navigate deeper into the website. ex: with mydomain.com/segments/ the audio player adds "segments" to the url instead of just the public directory. I know a similar issue can be solved with the URL:asset in Laravel, but i'm not sure how to with this since it's the jquery that's getting the file.
This is where i try to create my multiple jplayer instances using a laravel Forloop (i need to start at 2 because player 1 is being used elsewhere)I'm confused about how to mix the Laravel and Jquery code.
This is all in my footer.blade.php
<!--{{{$counter = 2}}}-->
#foreach ($archives as $archive)
<script>
var counter = "{{$counter}}";
var file = "archiveAudio/{{$archive->audioFile}}";
$(document).ready(function(){
$("#jquery_jplayer_"+ counter).jPlayer({
ready: function () {
$(this).jPlayer("setMedia", {
title: "Hidden",
mp3: file,
oga: ""
});
},
play: function() { // To avoid multiple jPlayers playing together.
$(this).jPlayer("pauseOthers");
},
swfPath: "../../js",
supplied: "mp3, oga",
cssSelectorAncestor: "#jp_container_" + counter,
wmode: "window",
globalVolume: true,
useStateClassSkin: true,
autoBlur: false,
smoothPlayBar: true,
keyEnabled: true
});
counter ++;
});
</script>
#endforeach
Home page Blade View (needs to start with #2 player add 1 to the player ID for each player it creates)
<div id="latest">
<!-- {{ $count = 2}} -->
#foreach ($archives as $archive)
<div class="singleLatest">
<img src = "/images/segments/{{$archive->segment->image}}" width="100px;"/>
<div class="playerAndInfo">
<h3> {{ $archive->archiveTitle}}<br>{{$archive->segment->name}}</h3>
<div id="jquery_jplayer_{{$count}}" class="jp-jplayer"></div>
<div id="jp_container_{{$count}}" class="jp-audio" role="application" aria-label="media player">
<div class="jp-type-single">
<div class="jp-gui jp-interface">
<div class="jp-controls">
<button class="jp-play" role="button" tabindex="0">play</button>
</div>
<div class="jp-progress">
<div class="jp-seek-bar">
<div class="jp-play-bar"></div>
</div>
</div>
<div class="jp-time-holder">
<div class="jp-current-time" role="timer" aria-label="time"> </div>
<div class="jp-duration" role="timer" aria-label="duration"> </div>
</div>
<div class="jp-no-solution">
<span>Update Required</span>
To play the media you will need to either update your browser to a recent version or update your Flash plugin.
</div>
</div>
</div>
</div>
</div><!--end playerAndInfo-->
</div> <!-- end single latest -->
<!-- {{ $count = $count +1}} -->
#endforeach
</div><!-- End latest -->
Thanks!

PHP, MySQL & jQuery: Display select options dynamically

having a bit of a problem here understanding how I can make the following action happen on my web page:
Right so at the moment I have two select elements on my page, one of the select elements looks like this:
<select class="form-control select-box">
<option value="make-any">Make (Any)</option>
<?php while($make = $makeFilter->fetch(PDO::FETCH_ASSOC))
{
echo '
<option value="'.$make["Make"].'">'.$make["Make"].'</option>
';
} ?>
</select>
As you can see this code is looping the 'Make' column of my SQL table, in the separate file that contains the queries I have made it so the query is using DISTINCT so it doesn't loop the same 'Makes' as the chances are there will be identical 'Makes' in the column.
I then have this block of code that displays another query into the front end:
<?php while($row = $results->fetch(PDO::FETCH_ASSOC))
{
echo '
<div class="makes ' . $row["Make"] . '">
<div class="listing-container">
<h3 class="model-listing-title clearfix">'.$row["Make"].' '.$row["Model"].' '.$row["Variant"].'</h3>
<h3 class="price-listing">£'.number_format($row['Price']).'</h3>
</div>
<div class="listing-container-spec">
<img src="'.(explode(',', $row["PictureRefs"])[0]).'" class="stock-img-finder"/>
<div class="ul-listing-container">
<ul class="overwrite-btstrp-ul">
<li class="diesel-svg list-svg">'.$row["FuelType"].'</li>
<li class="saloon-svg list-svg">'.$row["Bodytype"].'</li>
<li class="gear-svg list-svg">'.$row["Transmission"].'</li>
<li class="color-svg list-svg">'.$row["Colour"].'</li>
</ul>
</div>
<ul class="overwrite-btstrp-ul other-specs-ul h4-style">
<li>Mileage: '.number_format($row["Mileage"]).'</li>
<li>Engine size: '.$row["EngineSize"].'cc</li>
</ul>
<button href="#" class="btn h4-style checked-btn hover-listing-btn"><span class="glyphicon glyphicon-ok"></span> History checked
</button>
<button href="#" class="btn h4-style more-details-btn hover-listing-btn tst-mre-btn"><span class="glyphicon glyphicon-list"></span> More details
</button>
<button href="#" class="btn h4-style test-drive-btn hover-listing-btn tst-mre-btn"><span class="test-drive-glyph"></span> Test drive
</button>
<h4 class="h4-style listing-photos-count"><span class="glyphicon glyphicon-camera"></span> 5 More photos</h4>
</div>
</div>
';
} ?>
As you can see that block is looping various columns of my SQL table to display pretty much the whole table. PLEASE NOTE that the div with the class of 'makes' also includes the column 'Make' in the div.
I then use this jQuery to filter what results are brought to the screen:
<script>
$(document).ready(function(){
$('.form-control').change(function(){
var make = $(this).val();
if(make != 'make-any'){
$('.makes').hide();
$('.'+make).show();
} else {
$('.makes').show();
}
});
});</script>
As you can see it simply hides divs that don't have the class of the select value that has been selected.
So all of that is great however I get the feeling it just isn't enough for my users, I now want the users to be able to use a second select element to select a 'Model' of the 'Make'.
Now I know I could easily do this with the same technique I did at first but then users would be able to select 'BMW' and then select a model that wasn't associated with the 'Make' and no results would be returned.
I'd like my select element that contains the 'Models' to first of all be disabled until a user has selected a 'Make' then when a user has selected the 'Make' I'd like the second select element to show only the 'Models' that are associated with that 'Make'.
Here is an example of the columns in my SQL table:
Make, Model, Colour, FuelType, Year, Mileage, Bodytype, Doors, Variant, EngineSize, Price, Transmission, PictureRefs, ServiceHistory, PreviousOwners, Options, FourWheelDrive
I am now unsure how I can make this happen, it's really baffled me.
If someone could show me a detailed example and explain what each part does that would be great as I am a little stuck, thanks.
There are two options:
you could preload the data and save it as an object in JS and display when needed.
Or you could use ajax-calls to load the data when you need it(most websites do that nowadays)
use
$('makeselect').on('change', function() {
$.get("getmodels.php?make="+$("makeselect").val(),function(data){
var models=json.parse(data);
//iterate through the object and create the option tags
});
});
and give the select an id.
on php you should send the data encoded with json. json_encode(...)

Categories