Is there an issue retriving json data when using vue, axios, and laravel? - laravel

I am trying to replicate a tutorial on vuecasts (https://laracasts.com/series/learn-vue-2-step-by-step/episodes/18).
Everything looks fine and I don't get any errors except a warning:
Resource interpreted as Document but transferred with MIME type
application/json: "http://vueme.app:8000/skills"
I already tried to change content-type to text/html as suggested here:
Resource interpreted as Document but transferred with MIME type application/json warning in Chrome Developer Tools
web.php:
Route::get('/', function () {
return view('welcome');
});
Route::get('skills', function(){
return ['javascript', 'php', 'python'];
});
welcome.blade.php:
<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
<meta charset="utf-8">
<title>Laravel</title>
</head>
<body>
<div id="root">
<ul>
<li v-for="skill in skills" v-text="skill"></li>
</ul>
</div>
<script scr="https://unpkg.com/axios/dist/axios.min.js"></script>
<script scr="https://unpkg.com/vue"></script>
<script scr="/js/app.js"></script>
</body>
</html>
app.js:
new Vue({
el: '#root',
data:{
skills:[]
},
mounted(){
axios.get('/skills').then(response => this.skills = response.data);
}
});
What's not working?

Related

How to make a get request api call in Laravel

I am trying to learn how to use an API in Laravel and show json results in my view. This is a sample code I have made but nothing is showing. The API is with values because when I try it in Postman, it returns json results.
<html>
<head>
<meta charset="utf-8">
<title>Item Manager</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
</head>
<body>
<div class="container">
<ul id="items" class="list-group">
</ul>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function (){
getItems();
function getItems(){
$.ajax({
url:'https://www.boredapi.com/api/activity'
}).done(function (items){
let output = '';
$.each(items, function (key, activity){
output += '<li class="list-group-item">' +
'<strong>${activity.text}</strong>${text.body}' +
'</li>'
});
});
}
});
</script>
</body>
</html>
I suspect it might have a problem with the key tags i am trying to call. I am trying to make the call from blade not needed from the controller.
json returned from the API:
{
"activity": "Write a list of things you are grateful for",
"type": "relaxation",
"participants": 1,
"price": 0,
"link": "",
"key": "2062010",
"accessibility": 0
}
Here is the completed code.
<html>
<head>
<meta charset="utf-8">
<title>Item Manager</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
</head>
<body>
<div class="container">
<ul id="items" class="list-group">
</ul>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function (){
getItems();
var output = '';
function getItems(){
$.ajax({
url:'https://www.boredapi.com/api/activity'
}).done(function (items){
let output = '';
$.each(items, function (key, activity){
output += '<li class="list-group-item">' +
'<strong>'+key+'</strong>' + activity +
'</li>'
});
$("#items").append(output);
});
}
});
</script>
</body>
</html>
try adding this:
$.ajax({
url:'https://www.boredapi.com/api/activity',
type: "GET",
},
Also console.log() your result might be helpful.

How to use laravel-vue-i18n to change translations in laravel blades also?

Can anyone help me make translations working in laravel blades too?
I need to change/translate the contents of the title and description meta depending on the language being switched.
This is how the language changes in Vue:
<template>
<ul class='language-switcher'>
<li :class="{'active': language === 'de'}">
De
</li>
<li :class="{'active': language === 'en'}">
En
</li>
</ul>
</template>
<script>
import {loadLanguageAsync} from "laravel-vue-i18n";
export default {
name: "LanguageSwitcherComponent",
data() {
return {
language: 'en',
};
},
methods: {
switchLanguageTo(lang) {
// ...
loadLanguageAsync(lang);
// ...
},
},
}
</script>
In Vue, the translations work fine, but I need to translate title and description meta in index.balde.php as well.
<!DOCTYPE html>
<html lang="{{str_replace('_', '-', app()->getLocale())}}">
<head>
<title>{{ __("Site Title") }}</title>
<meta name="description" content="{{ __("Site Info") }}">
<meta charset="utf-8">
<meta name="csrf-token" content="{{ csrf_token() }}"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="{{mix('css/app.css')}}">
</head>
<body>
<div id="app">
<index-component/>
</div>
<script src="{{mix('js/app.js')}}"></script>
</body>
</html>
Also, this is how configured i18n in app.js:
import {i18nVue} from 'laravel-vue-i18n';
// ...
app.use(i18nVue, {
lang: 'en',
resolve: lang => import(`../../lang/${lang}.json`),
});
Thanks!
Save site language in cookies and in web.php set locale from cookies.
Route::get('/{any}', function (Request $request) {
// Set locale
App::setLocale($request->cookie('site_language') ?: 'en');
return view('index');
})->where('any', '.*');
Note: Maybe will need to add cookie name in app/Http/Middleware/EncryptCookies.php in $except list to get cookie from the $request successfully.

How to keep the component alive when refreshing page VUEJS [duplicate]

I am creating a simple laravel and vuejs CRUD Application. Vue Routes are not working, I am pretty new to vuejs; please see the code
Below is the code for web.php
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/vue','Api\PostController#home');
Route::resource('/api','Api\PostController');
Following is the code for app.js
require('./bootstrap');
window.Vue = require('vue');
window.VueRouter=require('vue-router').default;
window.VueAxios=require('vue-axios').default;
window.Axios=require('axios').default;
let AppLayout = require('./components/App.vue');
const Posts = Vue.component('Posts',require('./components/Posts.vue'));
const EditPost =
Vue.component('EditPost',require('./components/EditPost.vue'));
const AddPost =
Vue.component('AddPost',require('./components/AddPost.vue'));
const DeletePost =
Vue.component('DeletePost',require('./components/AddPost.vue'));
const ViewPosts =
Vue.component('ViewPosts',require('./components/ViewPosts.vue'));
const ExampleComponent =
Vue.component('ViewPosts',require('./components/ExampleComponent.vue'));
// Registering routes
Vue.use(VueRouter,VueAxios,axios);
const routes = [
{
name: 'Posts',
path: '/posts',
component: Posts
},
{
name: 'AddPost',
path: '/add-posts',
component: AddPost
},
{
name: 'EditPost',
path: '/edit-post/:id',
component: EditPost
},
{
name: 'DeletePost',
path: '/delete-post',
component: DeletePost
},
{
name: 'ViewPosts',
path: '/view-post',
component: ViewPosts
},
{
name: 'ExampleComponent',
path: '/example-component',
component: ExampleComponent
},
];
const router = new VueRouter({mode: 'history', routes: routes});
new Vue(
Vue.util.extend(
{ router },
AppLayout
)).$mount('#app');
This is the code of my blade tamplate, when I browse http://localhost:8000/vue this view is being rendered. As you can see in the web.php code above.
I can also see the notification in console You are running Vue in development mode. Make sure to turn on production mode when deploying for production.
<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
<div class="container">
<header class="page-header">
<div class="branding">
<img src="https://vuejs.org/images/logo.png" alt="Logo" title="Home page" class="logo"/>
<h1>Vue.js CRUD With Laravel 5 application</h1>
</div>
</header>
</div>
<section id="app">
</section>
<script>
window.Laravel = <?php echo json_encode([
'csrfToken' => csrf_token(),
]); ?>
</script>
<script src="{{ asset('js/app.js') }}"></script>
</body>
</html>
But when I run my application using
php artisan serve
and browse to
http://localhost:8000/posts
Application show a 404 error. Please help me with this problem.
You need to add a laravel route for the view where you are using the app.js (vuejs) in routes/web.php file.
Route::get('/route-name/?{name}', function(){
return redirect('vue_app');
})->where('name', '[A-Za-z]+');
and then you have to use the laravel route as a parent route for the vuejs's routes and use the url like below,
http://localhost:8000/laravel-route/view-route
in your case,
http://localhost:8000/route-name/posts
Or you can also use,
Route::get('{any}', function () {
return view('vue_app');
})->where('any', '.*');
and instead of previous use localhost:8000/posts
Try this to your web.php route
Route::get('/', function () {
return view('index');
});
Route::get('/{catchall?}', function () {
return response()->view('index');
})->where('catchall', '(.*)');
if with {any} did not work, you may also try adding ?
Route::get('/any-your-route/{any?}', function() {
return view('your-view');
})->where('any', '.*');
hope this help you. i just try this code and work on laravel blade template with vue router.
Tested on Laravel 8
For your second part of question,
You should use <div> instead of <section> and you have to bring the main/registered component inside of the html element selected by id="app" in blade file. in your case,
<div id="app">
<app-layout></app-layout>
</div>
Hope this help you. you can check this basic vuejs with laravel
PS: You should ask two different problem in two seperate posts.
you can do simply like this.
Route::get('/{vue_capture?}', function(){
return view('welcome');
})->where('vue_capture', '[\/\w\.-]*');

i use open sever and when i use jquery, displays error 500 (Internal Server Error). How to fix it?

i want to sent data in controller laravel, using jquery and ajax. But when i click on button, displays this error
here is my code ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function ()
{
$("#b").bind("click",function ()
{
var id = "888";
$.ajax({
url:"/insert_",
mehtod:"get",
data:{
id:id
}
});
});
});
here is my html code
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="js/jquery.js"></script>
<script src="js/f.js"></script>
</head>
<body>
<button id="b">do it</button>
</body>
</html>
here is my controller code
public function data(Request $request)
{
$student = $request->input('id');
DB::table("student_table")
->where("name","=",$student)->delete();
}
here is my web.php code
Route::get('/insert_',"StudentController#data");
I think that the query in the controller is wrong because you are passing the id but then you are using it to retrieve the student's name...
In my opinion, you should change this code
...
$student = $request->input('id');
DB::table("student_table")
->where("name","=",$student)->delete();
...
to
...
$student = $request->input('id');
DB::table("student_table")
->where("id","=",$student)->delete();
...
The problem is that if the student is not found then is not possible to call the delete method. I hope that this answer could help.

ajax call with vuejs

Im trying to get data from an endpoint api/data which passes an object. But when I run my app I dont see anything in my console and in the network tab I dont see any xhr request. There is no warning and errors in console too. Am I doing anything wrong here? I have checked the endpoint and its passing data from backend properly.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>FLashy</title>
<link rel="stylesheet" href="http://localhost:8000/css/bootstrap.min.css" media="screen" title="no title">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4" id="app">
<h3 class="Text center">Datas</h3>
<p>
#{{ datas }}
</p>
</div>
</div>
</div>
<!-- scripts -->
<script src="http://localhost:8000/js/jquery-2.2.4.min.js"></script>
<script src="http://localhost:8000/js/bootstrap.min.js" charset="utf-8"></script>
<script src="http://localhost:8000/js/vue.js" charset="utf-8"></script>
<script src="http://localhost:8000/js/vue-resource.min.js" charset="utf-8"></script>
<script type="text/javascript">
new Vue({
el: '#app',
data: {
},
methods:{
fetchData: function(){
this.$http.get('api/data').then(function(response){
// this.$set('datas', response.data);
console.log(response);
}, function(response){
// error callback
});
},
ready: function(){
this.fetchData();
}
}
});
</script>
</body>
</html>
web.php
Route::get('api/data', function(){
$a = [];
$a['id'] = 1;
$a['message'] = 'Lorem ipsum dolor sit amet, consectetur';
$a['status'] = 'Completed';
return response()->json($a,200);
});
Your ready hook is inside methods: {} handler but in reality should be outside:
methods: {
fetchData: function () {
// your AJAX here
}
},
ready: function () {
this.fetchData()
}

Resources