vuejs & http.get call not working - ajax

I'm starting to work with vuejs and I'm trying to make a http get call without sucess. I've tried several example showing how to do that but I get the following error in my console: this.$http is undefined.
html
<!doctype html>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.21/css/uikit.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.21/js/uikit.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.21/js/uikit-icons.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.19.1/vis.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.19.1/vis.min.css" rel="stylesheet" type="text/css"/>
<script src="https://unpkg.com/vue"></script>
</head>
<body>
<div id="app">
<p v-bind:title='message'>
{{ message }}
<p>
<button v-on:click='changeView("matrice")'>get data</button>
</div>
</body>
<script type="text/javascript" src="/front/lala_web/matrice.js"></script>
</html>
js
var app = new Vue({
el: '#app',
data: {
message: 'Empty data'
},
methods:{
changeView: function(v){
this.$http.get('/view/'+v)
.then(function(resp){
this.message = resp.data;
})
.catch(function(){alert('Error')});
}
}
})
I'been able to get a http get call working using the following js, but doing so doesn't change data.message value of vuejs and I get the following error data is not defined.
js
var app = new Vue({
el: '#app',
data: {
message: 'Empty data'
},
methods:{
changeView: function(v){
var viewUrl = '/view/'
$.ajax({
url: viewUrl+v,
method: 'GET',
success: function (resp) {
if (resp.error == false){
console.log(resp)
data.message = resp.data
}
},
error: function (error) {
console.log(error)
}
});
}
}
})

You need to reference this.message not data.message. Also, you'll need to save a reference to this outside the scope of the ajax call, since this in the success handler doesn't refer to the Vue instance:
changeView: function(v){
var viewUrl = '/view/'
var self = this;
$.ajax({
url: viewUrl+v,
method: 'GET',
success: function (resp) {
if (resp.error == false){
console.log(resp)
self.message = resp.data
}
},
error: function (error) {
console.log(error)
}
});
}

Related

Fetching JSON data on Ajax button click in .net core

I am new to Ajax. Trying to fetch JSON data returned from Get webAPI from controllers but on button click nothing rendering on View.
This is how my view look like
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var ulEmployees = $('#ulEmployees');
$('#btn').click(function () {
var id = $(this).attr(id);
$.ajax({
url: '/api/employee', type: "GET", dataType: "json",
data: { id: id },
success: function (data) {
ulEmployees.empty();
$.each(data, function (index, val) {
var fullName = val.FirstName + ' ' + val.LastName;
ulEmployees.append('<li>' + fullName + '</li>')
});
}
});
});
$('#btnClear').click(function () {
ulEmployees.empty();
});
});
</script>
</head>
<body>
<input id="btn" type="button" value="Get All Employees" />
<input id="btnClear" type="button" value="Clear" />
<ul id="ulEmployees"></ul>
</body>
</html>
This is the JSON data returned by webapi
Can anyone help me what went wrong here? Thanks in advance.
Below should work:
$(document).ready(function () {
var ulEmployees = $('#ulEmployees');
$('#btn').click(function () {
var id = $(this).attr('id');
fetch('/api/employee?id=' + id)
.then((resp) => resp.json())
.then(function(data) {
ulEmployees.empty();
$.each(data, function (index, val) {
var fullName = val.firstName + ' ' + val.lastName;
ulEmployees.append('<li>' + fullName + '</li>');
});
})
.catch(function(error) {
console.log(error);
});
});
});

How to catch a data from callback of GET jsonp request?

I'm trying to handle callback of jsonp request, but callback function is not run.
$(document).ready(function() {
$.ajax({
url: 'https://storage-testnet.shiftproject.com/peers?callback=?',
type: "GET",
dataType: 'jsonp',
jsonpCallback: 'peersData',
complete: peersData
});
var peersData = function (data) {
if(!data){
console.log("Error, can't retrieve data");
} else {
console.log(data)
}
}
}
Is there some mistake?
Your data is not wrapped in a pad eg. the following
<script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript">
//credit https://www.sitepoint.com/jsonp-examples/
function jsonCallback(json) {
console.log(json);
}
$.ajax({
url: "http://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-2.json",
dataType: "jsonp"
});
</script>
https://jsfiddle.net/kblau237/pmw0yah9/5/
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Tut156</title>
<script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#theButton").click(function () {
//moved your stuff inside a button click
$.ajax({
//question mark for callback will cause jquery to generate a random callback
//I am taking out the callback
url: 'https://storage-testnet.shiftproject.com/peers',
type: "GET",
dataType: 'json',
success: function (data) {
alert(JSON.stringify(data));
}
});
})
})
</script>
</head>
<body>
<div>
<input type="button" id="theButton" value="Go" />
</div>
</body>
</html>

Load Vue Componet via AJAX

I'd like to load Vue Component via AJAX dynamically and render its template.
Main Vue Instance:
const router = new VueRouter({
path: '/vue/actions/',
mode: 'history'
});
var app = new Vue({
el: '#mainContainer',
router,
data: {
mainContent: ''
},
methods: {
action: function (url) {
alert(url);
this.$router.push({ path: '/vue/actions/?'+url});
console.log(this.$route.query);
},
actions: function () {
var action;
if (!this.$route.query.action || this.$route.query.action == 'main') {
action = 'index';
} else {
action = this.$route.query.action;
}
var mainContent;
fetch('/vue/actions/?content_type=json&action='+action).then((response) => {
if(response.ok) {
return response.json();
}
throw new Error('Network response was not ok');
}).then((json) => {
this.$router.push({ path: '/vue/actions/', query: { action: json.action }});
// this.mainContent = json.template;
console.log(json.template);
this.dynamicComponent = json.template;
}).catch((error) => {
console.log(error);
});
}
},
created: function () {
this.actions();
}
})
Initial Page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="" />
<meta name="author" content="" />
<meta http-equiv='cache-control' content='no-cache'>
<meta http-equiv='expires' content='0'>
<meta http-equiv='pragma' content='no-cache'>
<script type="text/javascript" src="/js/vue.min.js"></script>
<script src="/js/vue-router.js"></script>
</head>
<body>
<template><div><component :is="dynamicComponent"></component></div></template>
<div id="mainContainer" v-html="mainContent"></div>
<script type="text/javascript" src="/js/main.js"></script>
</body>
</html>
Component I'd like to load via AJAX:
Vue.component('dynamicComponent', {
template: '<div>Dynamic Component!</div>'
});
Is it possible to load such Vue Componet and render its template (with an ability to use Vue data bindings in the Component template)?
Here is how I got what I need:
Main Vue Instance:
const router = new VueRouter({
path: '/vue/actions/',
mode: 'history'
});
var app = new Vue({
el: '#mainContainer',
router,
data: {
mainContent: ''
},
methods: {
action: function (url) {
this.$router.push({ path: '/vue/actions/?'+url});
console.log(this.$route.query);
},
actions: function () {
var action;
if (!this.$route.query.action || this.$route.query.action == 'main') {
action = 'index';
} else {
action = this.$route.query.action;
}
Vue.component('dynamic-component', (resolve) => {
import('/vue/actions/?content_type=javascript&action='+action).then((component) => {
resolve(component.default);
});
});
}
},
created: function () {
this.actions();
}
})
Main/Initial Page Body:
<body>
<div id="mainContainer">
<dynamic-component></dynamic-component>
</div>
<script type="text/javascript" src="{{.__web_root_folder}}/js/main.js"></script>
</body>
Component code that I'm loading when needed:
export default {
template: '<div>Async Component! {{.test}}</div>',
data () {
return {
test: 'Works!'
}
}
}
Thanks to #MazinoSUkah !

Getting Error "parsererror" "Error: jQuery21106393266040831804_1456914722748 was not called" On Ajax Call Reactjs

Here I wrote A code which fetches data from API http://fcctop100.herokuapp.com/api/fccusers/top/recent and displays on console for starter but I'm Getting Error Like "parsererror" "Error: jQuery21106393266040831804_1456914722748 was not called"
var App = React.createClass({
//setting up initial state
getInitialState:function(){
return{
data:[]
};
},
componentDidMount(){
this.getDataFromServer('http://fcctop100.herokuapp.com/api/fccusers/top/recent');
},
//showResult Method
showResult:function(response){
console.log(response);
this.setState({
data:response.results
});
},
//making ajax call to get data from server
getDataFromServer:function(URL){
$.ajax({
type:"GET",
dataType:"jsonp",
url:URL,
success: function(response) {
this.showResult(response);
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
render:function(){
return(
<div>
<Result />
</div>
);
}
});
var Result = React.createClass({
render:function(){
return(
<div>
<ul>
<ResultItem/>
</ul>
</div>
);
}
});
var ResultItem = React.createClass({
render:function(){
return(
<div>
<li>Hello This Is From ResultItem Component</li>
</div>
);
}
});
ReactDOM.render(
<App />,
document.querySelector("#app")
);
<!DOCTYPE html>
<head>
<meta charset="UTF-8" />
<title>React Tutorial</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<div id="app"></div>
<script src="demo.js" type="text/babel"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.2/marked.min.js"></script>
</body>
</html>
Your API returns JSON, you don't need use JSONP, just change dataType from jsonp to json
$.ajax({
type: "GET",
dataType: "json",
....
});
and in showResult set only response because response contains Array of Objects and does not have results property
this.setState({
data: response
});
Example

Ajax Code To Display Data

I wrote this code in javascript to disply information in this page (Normal_Info.php),
but unfortunately it did not work. If anyone can help me I will be grateful
<html>
<head>
<script language="javascript">
function ajaxFunction()
{
return window.XMLHttpRequest ?
new window.XMLHttpRequest :
new ActiveXObject("Microsoft.XMLHTTP");
}
function Go_there()
{
var httpObj = ajaxFunction();
httpObj.open("GET","Normal_Info.php", true);
httpObj.send();
httpObj.onreadystatechange = ChangedState()
{
if (httpObj.readyState == 4 && httpObj.status == 200)
{
document.getElementById("result").innerHTML=httpObj.responseText;
}
}
}
</script>
</head>
<body>
<form id=ff>
<input type=button value=Hi OnClick=Go_there() />
</form>
<div id=result>
</div>
</body>
</html>
i suggest using jquery http://jquery.com/
<script src="jquery.js"></script>
<script language="javascript">
$('#ff').submit(function() {
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('#result').html(data);
// alert('Load was performed.');
}
});
});
</script>
no need to click event

Resources