Cannot get the data from axios with api - vue js - javascript

I have an issue when i get the data with vue js, it returns a HTML not json. I conse the route params it show an id of the post. This is my code in vue:
axios.get("api/posts/" + this.$route.params.id).then(response => {
console.log(this.$route.params.id);
console.log(response.data);
});
And this is the response data :
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel</title>
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">
<link rel="stylesheet" href="http://127.0.0.1:8000/css/app.css">
<script src="http://127.0.0.1:8000/js/app.js" defer></script>
</head>
<body>
<div id="app">
<index></index>
</div>
</body>
</html>
But in the postman, i access the url "api/posts/1" it show json data
{"id": 1,"title": "Schambergerstad Fancy Rooms",
"description": "Qui minima tempora ea modi maiores. Quaerat non aut porro vel occaecati. Deleniti quaerat quod veniam. Dolor ducimus facilis molestiae omnis fuga occaecati.",
"created_at": "2020-06-04T11:28:25.000000Z","updated_at": "2020-06-04T11:28:25.000000Z"
}
But i see in network tab, the request url is "http://127.0.0.1:8000/posts/api/posts/1". Why become to that url? I call it in axios is "api/posts/1"
How to fix it?

try adding headers Content-Type json
axios.get("/api/posts/" + this.$route.params.id, {
headers: {
'Content-Type': 'application/json'
}
}).then(response => {
console.log(this.$route.params.id);
console.log(response.data);
});

Okay sorry it's just typo axios.get("api/posts/" + this.$route.params.id) it's should add "/" before "api/posts/"
axios.get("/api/posts/" + this.$route.params.id)

Related

Getting to run jQuery - $ is not defined Error

Hello I'm new to Javascript, i'm trying to get to run jQuery library but Chrome notifies this error to me.
I did search a few posts about this in Stack Overflow and on Google but even so to me at least i couldn't find a satisfactory answer (i checked to have put jQuery script as first). Here is my HTML source code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Responsive Design</title>
<link rel="stylesheet" href="css/style.css" type="text/css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/slick.css">
<link rel="stylesheet" href="css/slick-theme.css">
<!--<script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/slick.min.js"></script>
</head>
<body>
<header>
<div class="container">
<div class="row">
<a href="" class="logo">
<img src="" alt="">
</a>
<nav>
<ul>
<li>Home</li>
<li>Work</li>
<li>Services</li>
<li>Clients</li>
<li>Our Team</li>
<li>Contact</li>
</ul>
</nav>
</div>
</div>
</header>
<section class="slider">
<ul class="slider-carousel" id="#slider-carousel">
<li class="img1">
<h2>BEAUTIFIED BUSINESS <span>TEMPLATE</span></h2>
<p>We believe in creativity always</p>
<i class="fab fa-apple"></i>
<i class="fab fa-android"></i>
<i class="fab fa-windows"></i>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Distinctio modi ducimus aut nihil explicabo, quia voluptatibus. Sint consequatur culpa vel sapiente, et dicta ratione facere distinctio, maiores modi eligendi. Perspiciatis.</p>
Get Started
Buy Now
</li>
<li>
<h2>Slider</h2>
</li>
<li>
<h2>Slider</h2>
</li>
</ul>
</section>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
This is my directory structure:
**Project
|
+-- index.html
|
+-- js
| |
| -- bootstrap.min.js
| -- jquery-3.4.1.min.js
| -- main.js
| -- slick.min.js
|
+-- css
| |
| -- all.css
| -- bootstrap.min.css
| -- slick.css
| -- slick-theme.css
| -- style.css
|
+-- images
| |
-- slider1.jpg
This is the single line of code i run:
$(Document).ready(function(){})
ERRORS I GET IN BRACKETS:
ESLint (2)
ERROR:
'$' is not defined. [no-undef] $(Document).ready(function(){})
ERROR: 'Document' is not defined. [no-undef] $(Document).ready(function(){})
JSLint (7)
'$' was used before it was defined. $(Document).ready(function(){})
'Document' was used before it was defined. $(Document).ready(function(){})
Expected exactly one space between 'function' and '('. $(Document).ready(function(){})
Expected exactly one space between ')' and '{'. $(Document).ready(function(){})
Missing space between ')' and '{'. $(Document).ready(function(){})
Missing 'use strict' statement. $(Document).ready(function(){})
Expected ';' and instead saw '(end)'. $(Document).ready(function(){})
(I tried to load both, the local jQuery script and the other, but none of them seemed to work though)
{Thank you for your attention}
You must have a .eslintrc.json file.
Make sure you have the following lines of code in it:
"env": {
"browser": true,
"commonjs": true,
"es6": true,
"jquery": true
},
"plugins": [
"dollar-sign",
"jquery"
],
"rules": {
"dollar-sign/dollar-sign": [
2,
"ignoreProperties"
]
}
You can read more here: https://eslint.org/docs/user-guide/configuring#configuration-file-formats

v-on:click event Vue.js to show user posts

I'm a student and I'm just getting into Vue.js so I'm still very new to it. Right now I'm making a project where I'm getting usernames from an API and when you click on the user it has to show the related post, but this is not working. When I click the button with the v-on:click event. nothing happens, not even in the console. So I hope someone can help me with my problem, I would really appreciate it.
main.js :
const app = new Vue({
el: "#app",
data: {
users: [],
posts: [],
},
methods: {
Showpost(id, i) {
fetch("https://jsonplaceholder.typicode.com/posts?userId=" + id)
.then(response =>response.json())
.then((data) => {
this.posts = data;
})
},
},
mounted() {
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
.then((data) => {
this.users = data;
})
},
template: `
<div>
<td v-for="user, i in users">
<button v-on:click="Showpost(user.id, i)" >{{ user.name }}</button>
</td>
<h1>{{ posts.title }}</h1>
</div>
`,
});
html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<title>Users</title>
</head>
<body>
<h1>Users</h1>
<div id="app">
</div>
<script src="https://unpkg.com/vue"></script>
<script src="./main.js"></script>
</body>
</html>
json users :
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
}
json posts :
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
Try to create a property called post and update it on every click on a specified user by assigning this.post=data[i]:
new Vue({
el: "#app",
data: {
users: [],
posts: [],
post: ''
},
methods: {
Showpost(id, i) {
fetch("https://jsonplaceholder.typicode.com/posts?userId=" + id)
.then(response => response.json())
.then((data) => {
this.post = data[i];
})
},
},
mounted() {
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
.then((data) => {
this.users = data;
})
},
template: `
<div class="flex">
<div v-for="user, i in users">
<button class="btn" v-on:click="Showpost(user.id, i)" >{{ user.name }}</button>
</div>
<h1>{{ post.title }}</h1>
</div>
`,
});
.flex{
display:flex;
flex-wrap:wrap;
}
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="Vue.delete">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.1/vue.min.js"></script>
</head>
<body>
<div id="app">
</div>

Angular UI-Router View Not Displaying Anything

I can't get UI-Router to work, which is really annoying because I'm building a site off of another site I built where it was working fine. Currently, ui-view is not displaying anything, and ui-sref links are not clickable or redirecting. I'm not getting any errors either. My code is below. Any help would be much appreciated!
JS: app.js
var app = angular
.module("RssTransfers", ["ui.router"])
.config(MainRouter);
function MainRouter($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('transfers', {
url: '/',
templateUrl: 'transfers.html',
})
.state('about', {
url: '/about',
templateUrl: 'about.html'
})
.state('upload', {
url: '/upload',
templateUrl: 'upload.html'
})
};
HTML: index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>RSS Transfers</title>
<link rel="stylesheet" type="text/css" href="./css/materialize.css" />
<link rel="stylesheet" type="text/css" href="./css/style.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.js"></script>
<script src="./js/ng-file-upload-shim.min.js"></script> <!-- for no html5 browsers support -->
<script src="./js/ng-file-upload.min.js"></script>
<script src="./js/app.js"></script>
<script src="./js/transferController.js"></script>
<script src="./js/uploadController.js"></script>
<script src="./js/materialize.js"></script>
</head>
<body ng-app="RssTransfers">
<div ng-include="'navbar.html'"></div>
<div class="wrapper" ui-view></div>
</body>
</html>
dummy text to display: transfers.html
<div ng-controller="TransferController as transfer">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Commodi, est, cum. Dicta, eius obcaecati quia culpa ipsam quibusdam tempore adipisci molestias optio, nam corporis, veritatis voluptatem incidunt cumque a sequi?</p>
</div>
As requested, here's the code for the controller:
TransferController.js
angular.module('RssTransfers')
.controller('TransferController', TransfersController);
TransfersController.$inject = ['$http'];
function TransfersController($http){
var self = this;
self.all = [];
self.addTransfer = addTransfer;
self.newTransfer = {};
self.getTransfer = getTransfer;
getTransfers();
function getTransfers(){
$http
.get('http://localhost:3000/transfers/')
.then(function(response){
self.all = response.data.transfers;
});
}
function addCriminal() {
$http
.post('http://localhost:3000/transfer', self.newTransfer)
.then(function(response){
getTransfers();
});
self.newTransfer = {};
}
}
Solved, although I'm not sure why. I deleted my frontend files and started from scratch, and it works fine. I suspect there may be an issue with ui-router and ng-file-upload conflicting, but I'll tackle that issue when I get there.
I've taken your code and created a plunkr here. Note - that it doesn't contain the controller just yet.
angular.module('RssTransfers',['ui.router']);
(function() {
'use strict';
angular
.module('RssTransfers')
.config(routing);
routing.$inject = ['$stateProvider', '$urlMatcherFactoryProvider', '$urlRouterProvider'];
function routing( $stateProvider, $urlMatcherFactoryProvider, $urlRouterProvider ){
$urlMatcherFactoryProvider.strictMode(false);
// For any unmatched url, redirect to /root
$urlRouterProvider.otherwise("/transfers");
$stateProvider
.state('transfers', {
url: '/transfers',
templateUrl: 'transfers.html',
})
.state('about', {
url: '/about',
templateUrl: 'about.html'
})
.state('upload', {
url: '/upload',
templateUrl: 'upload.html'
});
}
})();
though I'm still unsure why yours doesn't work...

Angularjs $state couldn't navigate back

I can only navigate from page 1 to page 2 but couldn't get back from page 2 to page 1.
demo http://codepen.io/anon/pen/qEOJBp
I wonder why? The code look flawless for me :
<ion-nav-view name="home"></ion-nav-view>
<ion-nav-view name="threadContent"></ion-nav-view>
<script type="text/ng-template" id="home.html">
<ion-view name="home">
<ion-content>
<h2>Home Page</h2>
<p>Here is the main route for the app.</p>
GO
</ion-content>
</ion-view>
</script>
<script type="text/ng-template" id="threadContent.html">
<ion-view name="threadContent" title="Thread Content">
<ion-content>
Back
<h2>Using the app</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facilis architecto hic officia quasi excepturi sequi deleniti maiores consectetur veritatis sint?</p>
</ion-content>
</ion-view>
</script>
$rootScope.$on('$stateChangeSuccess', function (event, to, toParams, from, fromParams) {
$rootScope.$previousState = from;
$rootScope.$previousStateParams = fromParams;
});
On my project I have used ui.router, but main idea is:
Catch change state event and save data to root scope. And you will always have an ability back to previous sate.

AJAX ModalPopup not displaying

I can't seem to get the Modal popup to show. With the code below, the display goes out of focus but no window displays.
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="AjaxToolkit" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnShow" runat="server" Text="Open ModalPopup" OnClientClick="return ShowModalPopup('modal');" />
<ajaxToolkit:ModalPopupExtender runat="server" ID="modal" BackgroundCssClass="darken"
CancelControlID="btnCancel" PopupControlID="pnl" TargetControlID="btnShow" />
<asp:Panel ID="pnl" runat="server" style="width:55%;display:none;">
<h1>You can now see me!</h1>
<p>"Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum."</p>
<asp:Button ID="btnCancel" runat="server" Text="Close" />
</asp:Panel>
<asp:ScriptManager ID="ScriptManager1" runat="server"/>
</div>
</form>
</body>
</html>
<script type="text/javascript">
function ShowModalPop(PopupExtenderID) {
var ModalPopWindowShow = $find(PopupExtenderID);
if (ModalPopWindowShow) {
ModalPopWindowShow.show();
}
return false;
}
</script>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
_grid.DataSource = BuildList();
_grid.DataBind();
}
private List<EntityPerson> BuildList()
{
...
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
btnShow.Click +=new EventHandler(btnShow_Click);
}
protected void btnShow_Click(object sender, EventArgs e)
{
Button btnShow = sender as Button;
ScriptManager.RegisterStartupScript(btnShow, btnShow.GetType(), "Popup", "return ShowModalPopup('modal');", true);
}
All your help is appreciated.
If there is another way to show a pop up window with AJAX, I would appreciate guidance on that as well.
I just need to be able to display cell content in a modal window when a user clicks on a cell in a grid.
I replaced
<asp:ScriptManager ID="ScriptManager1" runat="server"/>
with
<ajaxToolkit:ToolkitScriptManager ID="ajaxSM" runat="server" />
and I got the popup to show.

Categories

Resources