laravel vue.js select list from database - javascript

I just begun Vue.js and I have some issues with it:
I’m currently working with Laravel, a PHP framework.
I would like to do a select list for a research, i have different applications but there are all related to different countries. And when I select a country I would like that only apps with this country appear.
I used to use php but we have to reload the page each time and it’s not very quick and easy to use.
My main page is like that:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>VueJS</title>
<link rel="stylesheet" href="">
<script src="/js/vue.js"></script>
</head>
<body>
<div id="app">
<div id="country">
<select v-model="selectedcountry">
<option v-for="option in options" v-bind:value="option.value">#{{ option.text }}
</option>
</select>
<span>Sélectionné : #{{ selectedcountry }}</span>
</div>
<script src="/js/app.js"></script>
</body>
</html>'
And my app.js :
new Vue({
el: '#country',
data: {
selectedcountry: 'All Countries',
options: [
{ text: 'All Countries', value: 'world' },
{ text: 'Denmark', value: 'denmark' },
{ text: 'France', value: 'france' },
]
}
})'
And in my database my table is : "cards" with an attribute call "country".
My controller is :
<?php
namespace App\Http\Controllers;
use App\Apps;
use Illuminate\Http\Request;
class SearchController extends Controller
{
public function search(Request $request)
{
if ($request->has('Country')) {
$apps = Apps::where('Country', $request->Country)->get();
return view('index', compact('apps'));
}
}
}
How can I do that?

My controller is :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Apps;
class SearchController extends Controller
{
public function search(Request $request){
if( $request->has('Country') ){
$apps = Apps::where('Country',$request->Country)->get();
return view('index',compact('apps'));
}
}
}

You must create vue component for your application. Working with component makes your code easier and well structured, also you are confusing yourself with #country and #app and you also need to define your form elements for vue.

Related

How can I use javascript library function in nuxt.js?

This source worked in html file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Kakao JavaScript SDK</title>
<script src="https://developers.kakao.com/sdk/js/kakao.js"></script>
<script>
// SDK를 초기화 합니다. 사용할 앱의 JavaScript 키를 설정해 주세요.
Kakao.init('JAVASCRIPT_KEY');
// SDK 초기화 여부를 판단합니다.
console.log(Kakao.isInitialized());
</script>
</head>
<body></body>
</html>
So I thought the next source will work on Nuxt.js.
But it showed just
'ReferenceError
Kakao is not defined' in these source
in nuxt.config.js
// Global page headers (https://go.nuxtjs.dev/config-head)
head: {
title: 'P-Cloud OCR',
meta: [
{ 'http-equiv': 'X-UA-Compatible', content: 'IE=Edge' },
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: '' },
],
link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],
script: [
{ src: 'https://developers.kakao.com/sdk/js/kakao.js'},
]
}, ```
in pages/login.vue
<script>
export default {
...
}
Kakao.init('JAVASCRIPT_KEY');
console.log('Kakao.isInitialized() >>', Kakao.isInitialized());
</script>
Why is this source not working?
There are basically 2 approaches you can do:
1. Load the library directly in your layout/page/component
head () {
if (window.Kakao) {
this.afterKakaoLoaded()
return
}
return {
script: [
{
hid: 'kakao',
src: 'https://developers.kakao.com/sdk/js/kakao.js',
callback: () => {
this.afterKakaoLoaded()
}
}
]
}
},
methods: {
afterKakaoLoaded () {
window.Kakao.init('...')
}
}
2. Load the library within a plugin
Josh Deltener wrote a great article about how to achieve that: https://deltener.com/blog/nuxt-third-party-code-is-poison/
In nuxt you can overwrite the default .nuxt/views/app.template.html.
You need to create app.html file at the root of the project. Then put the below code inside this file:
app.html
<!DOCTYPE html>
<html lang="en" {{ HTML_ATTRS }}>
<head {{ HEAD_ATTRS }}>
{{ HEAD }}
</head>
<body {{ BODY_ATTRS }}>
{{ APP }}
</body>
</html>
Then you can follow the traditional way that you mentioned in question:
<!DOCTYPE html>
<html lang="en" {{ HTML_ATTRS }}>
<head {{ HEAD_ATTRS }}>
{{ HEAD }}
<script src="https://developers.kakao.com/sdk/js/kakao.js"></script>
<script>
// SDK를 초기화 합니다. 사용할 앱의 JavaScript 키를 설정해 주세요.
Kakao.init('JAVASCRIPT_KEY');
// SDK 초기화 여부를 판단합니다.
console.log(Kakao.isInitialized());
</script>
</head>
<body {{ BODY_ATTRS }}>
{{ APP }}
</body>
</html>
But be aware that in this method, all pages in your application load this script.

Vuejs will not render component correctly when trying to loop thru array data or v-for

<!DOCTYPE html>
<html lang="en">
<head>
<script src="js/vue.js"></script>
<meta charset="UTF-8">
<title>V-for example</title>
</head>
<body>
<script type="x/template" id="testTemplate">
<div><h1>{{name}}</h1>
<p>{{Age}}</p></div>
</script>
<div id="example">
<div id="filler">
<template v-for="person in people">
<test-component name="{{person.name}}"></test-component>
</template>
</div>
</div>
<script>
var newComponent = Vue.extend({
template: '#testTemplate',
props: ['name'],
data: function () {
return {
Age: 1010
}
}
});
Vue.component('test-component', newComponent);
new Vue({
el: '#example',
data: {
people: [{
name: 'jason',
age: 15,
complete: true
}, {
name: 'Jeremy',
age: 20,
complete: false
}]
},
ready: function () {
var divoutput = document.querySelector('#filler');
alert(divoutput.innerHTML);
len = this.$data.people.length;
for (i = 0; i < len; i += 1) {
var nameT = this.$data.people[i].name;
divoutput.innerHTML += '<test-component name="' + nameT + '"></test-component>';
}
},
});
</script>
</body> </html>
I'm trying to take all of the people in the Vue data array and inject it into a component and add it to a innerHTML of a div during the Vue.ready() function. I show that result is being injected in to the "filler" array but the components them selves are not being rendered properly. If I make a manual instance of my component it works fine.
You shouldn't try to add Vue component using innerHTML. That's managing the DOM yourself, just let Vue do that on its own. Here is a fiddle:
https://jsfiddle.net/xccjsp4b/
I changed the script template to a div because I'm not certain you can use the script tag like that (although I could be wrong). Then you just use a v-for to loop through the people and pass the relevant data as properties. If each person is going to have their own age, you want it to be a property not a data variable.
Also, use the shorthand binding of :name="person.name" rather than name="{{person.name}}". The : tells Vue to evaluate the expression.

obtain different values in star rating

how are you. I'm implementing a rating at IONIC, although this is basically angular. I want to get the value for each category. if I qualify rubric "animals" I want to get the value I selected. if I qualify "cars" I want to get the value I selected.
My problem is that I always get the same value for both categories. What can I do?. I want to know what is the best solution because then I think creating dynamic code and do not want to repeat code in n categories.
http://plnkr.co/edit/1PomwzklGD2Y8esbsnxT?p=preview
HTML
What do you think about the animals?
<ionic-ratings ratingsobj='ratingsObject'></ionic-ratings>
What do you think about the cars??
<ionic-ratings ratingsobj='ratingsObject'></ionic-ratings>
JAVASCRIPT
$scope.ratingsObject = {
iconOn: 'ion-ios-star', //Optional
iconOff: 'ion-ios-star-outline', //Optional
iconOnColor: 'rgb(200, 200, 100)', //Optional
iconOffColor: 'rgb(200, 100, 100)', //Optional
rating: 4, //Optional
minRating: 1, //Optional
readOnly:false, //Optional
callback: function(rating) { //Mandatory
$scope.ratingsCallback(rating);
}
};
$scope.ratingsCallback = function(rating) {
$scope.cars=rating;
$scope.animals=rating;
console.log('Selected rating is : ', rating);
//is the same value :(
console.log("animals: "+$scope.animals);
console.log("cars: "+$scope.cars);
};
I suggest to use another ionic rating library like this one which enables the use of ng-model. So you can use ng-repeat with an array as a model, and then bind the <rating> directive to a property automatically updated when user set the rating.
Here below is your example adapted to use that lib and made dynamic:
angular.module('ionicApp', ['ionic', 'ionic.rating'])
.controller('MyCtrl', function($scope) {
$scope.myTitle = 'IONIC RATINGS DEMO';
$scope.categories = [{
name: "animals",
question: "What do you think about the animals?",
rating: 0
}, {
name: "cars",
question: "What do you think about the cars?",
rating: 0
}, {
name: "flowers",
question: "What do you think about the flowers?",
rating: 0
}];
$scope.rating = {};
$scope.rating.max = 5;
});
<!DOCTYPE html>
<html ng-app="ionicApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<link href="http://code.ionicframework.com/nightly/css/ionic.min.css" rel="stylesheet">
<script src="http://code.ionicframework.com/nightly/js/ionic.bundle.min.js"></script>
<script src="https://rawgit.com/fraserxu/ionic-rating/master/ionic-rating.js"></script>
<link rel="stylesheet" href="https://rawgit.com/fraserxu/ionic-rating/master/ionic-rating.css">
<script src="script.js"></script>
</head>
<body ng-controller="MyCtrl">
<ion-view>
<h1 class="text-center">{{myTitle}}</h1>
<div class="list">
<div class="item item-button-right" ng-repeat="category in categories">
{{category.question}}
<rating ng-model="category.rating" max="rating.max"></rating>
</div>
</div>
<pre>categories = {{categories|json}}</pre>
</ion-view>
</body>
</html>
P.S.: in the <pre> tag is shown the model only for debug and demo.

Form with nested controllers and "controller as" syntax

I'm trying to create a more than average complex form with custom actions on some controls. The main controller of the view is holding the model that will be saved at the end. Inside this main controller, I have a separate controller for each input control that has some specific actions.
Here is a short example and the question is, if I want to implement the UserChoiceCtrl.selectLastUser function, how can I do without using $scope ?
More generally, how can I access to a model in the main controller in a child controller ? It's easy in the view, but how can I do in the controller code ?
#Plunker if you prefer
angular.module('myApp', []);
angular.module('myApp')
.controller('TaskCtrl', [
function() {
var viewModel = this;
// This is injected in controller in real life
viewModel.users = [
{login: 'Tom', password: '123'},
{login: 'Stanley', password: '123'},
{login: 'Joe', password: '123'},
{login: 'Katy', password: '123'},
{login: 'Kate', password: '123'},
{login: 'Tony', password: '123'}
];
viewModel.task = {
user: viewModel.users[0],
description: ''
};
viewModel.save = function() {
alert(angular.toJson(viewModel.task));
};
}
]);
angular.module('myApp')
.controller('UserChoiceCtrl', [
function() {
var viewModel = this;
viewModel.selectLastUser = function() {
// No way to access the task variable # TaskCtrl ?
// The following line is working but using $scope
// $scope.taskCtrl.task.user = $scope.taskCtrl.users[5];
};
}
]);
body {
font-family: 'Arial';
}
label,
input,
textarea {
display: block;
}
label {
margin-top: 8px;
}
<!DOCTYPE html>
<html data-ng-app="myApp">
<head>
<script data-require="angular.js#1.4.0" data-semver="1.4.0" src="https://code.angularjs.org/1.4.0/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body data-ng-controller="TaskCtrl as taskCtrl">
<h1>New task</h1>
<form name="taskCtrl.taskForm">
<label>Description</label>
<textarea data-ng-model="taskCtrl.task.description"></textarea>
<div data-ng-controller="UserChoiceCtrl as userChoiceCtrl">
<label>User</label>
<select data-ng-model="taskCtrl.task.user" data-ng-options="user as user.login for user in taskCtrl.users"></select>
<button data-ng-click="userChoiceCtrl.selectLastUser()">Last user of list</button>
</div>
<br>
<button data-ng-click="taskCtrl.save()">Save</button>
</form>
</body>
</html>
Try this
<button data-ng-click="userChoiceCtrl.selectLastUser(taskCtrl.task.user)">Last user of list</button>
viewModel.selectLastUser = function(user) {
alert(user);
// No way to access the task variable # TaskCtrl ?
// The following line is working but using $scope
// $scope.taskCtrl.task.user = $scope.taskCtrl.users[5];
};
A way could be creating the main controller as a service and injecting it to the children:
http://fdietz.github.io/recipes-with-angular-js/controllers/sharing-code-between-controllers-using-services.html
See if this serves the purpose,
basically i am getting an instance of the task controller using the $controller service.
angular.module('myApp')
.controller('UserChoiceCtrl', function ($controller) {
var task = $controller('TaskCtrl');
console.log("Task", task);
var viewModel = this;
viewModel.selectLastUser = function () {
// No way to access the task variable # TaskCtrl ?
// The following line is working but using $scope
// $scope.taskCtrl.task.user = $scope.taskCtrl.users[5];
task.task.user = task.users[5];
alert ( task.task.user.login);
};
console.log("User", viewModel)
});

ASP.Net MVC Scripts not working with controller's default action url. Same is working with controller/action url

When mvc application is queried with controller name alone in the url without specifying action, the page is rendered but ajax/scripts are not working, whereas the same page when queried with action in the url, is working as expected.
Not working url: http://localhost:port/Search --> Page rendering is fine but scripts are not working - Search results are not showing up
Working url: http://localhost:port/Search/Index --> Page and scripts are working as expected - Search results are showing up
C#:
public class SearchController : Controller
{
private readonly List<string> _cars;
public SearchController()
{
_cars = new List<string>{"Corolla","Camry","Civic","Land Rover","Range Rover","Polo"};
}
public ActionResult Index()
{
return View();
}
public async Task<JsonResult> GetMatchingResults(string filter)
{
var results = await Task.Run(() => GetSearchResults(filter));
return new JsonResult() { Data = results,JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
private List<string> GetSearchResults(string filter)
{
var results = _cars.Where(car => car.Contains(filter));
return results.ToList();
}
}
HTML:
<html>
<head>
#using System.Web.Optimization
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
<meta name="viewport" content="width=device-width" />
<script src="~/Scripts/ApplicationScripts/SearchViewJS.js" type="text/javascript"></script>
<title>SearchView</title>
</head>
<body>
<div>
<input class="searchText" type="search" />
</div>
<div>
<input class="searchResults" type="text" />
</div>
</body>
</html>
JS:
$(document).ready(function () {
$(".searchText").on('input', function (event) {
var filter = $(event.currentTarget).val();
search(filter).then(display);
});
function search(filter) {
return $.getJSON('GetMatchingResults/', { 'filter': filter });
}
function display(result) {
$(".searchResults").val(result);
}
})
It is because of the context of
$.getJSON('GetMatchingResults/', { 'filter': filter });
In the first case that will be trying to hit /GetMatchingResults the second tries to hit /search/GetMatchingResults. A fix could be to use
$.getJSON('/search/GetMatchingResults/', { 'filter': filter });
Or even better would be to generate the path from a HTML helper that will route correctly if you update your routing rules. This would look something like
$.getJSON('#Url.Action("GetMatchingResults", "Search")', { 'filter': filter });

Categories

Resources