I am new to React, and I'm making a webpage to show a list of items.
I have this React Code in a file called admins.js:
//more code
var AdminsBox = React.createClass({
getInitialState: function() {
return {adminsList: []};
},
setAdminsArray: function(data) {
this.setState({adminsList: data});
},
render: function() {
return (
<div>
<AdminsContentBox adminsList={this.state.adminsList}/>
</div>
);
}});
var AdminsBoxRender = ReactDOM.render(
<AdminsBox />,
document.getElementById('adminsContent')
);
And in the file index.jsp:
<html lang="es">
<head>
<link rel="stylesheet" href="base.css" />
<script src="react.js"></script>
<script src="react-dom.js"></script>
<script src="browser.js" charset="utf-8"></script>
<script src="jquery.min.js"></script>
<script src="marked.min.js"></script>
<link rel="stylesheet" href="fonts.css">
<link rel="stylesheet" href="material.indigo-blue.min.css">
<script type="text/babel" src="admins.js"></script>
<script>
$(document).ready(function() {
$.ajax({
url: 'myUrlServlet',
type: 'POST',
data: "function=getAdmins",
dataType: "json",
success: function(data){
AdminsBoxRender.setAdminsArray(data);
}
});
});
</script>
</head>
<body>
<div id="adminsContent"></div>
</body>
The error I get is AdminsBoxRender is not defined.
What am I doing wrong?
Thank you in advance.
That's not the proper way to fetch data for your component, you should fetch it in componentDidMount()
var AdminsBox = React.createClass({
getInitialState: function() {
return {adminsList: []};
},
componentDidMount: function(){
$.ajax({
url: 'myUrlServlet',
type: 'POST',
data: "function=getAdmins",
dataType: "json",
success: function(data){
this.setState({adminsList: data});
}
});
},
setAdminsArray: function(data) {
this.setState({adminsList: data});
},
render: function() {
return (
<div>
<AdminsContentBox adminsList={this.state.adminsList}/>
</div>
);
}});
window.AdminsBoxRender = ReactDOM.render(
<AdminsBox />,
document.getElementById('adminsContent')
);
You should keep the stuff related to React "inside" React.
Your approach would fall under the heading of "fighting the framework".
I would recommend going with QoP's first recommendation rather than attaching the component to the window object.
Related
I have this code in my javascript:
$(document).ready(function() {
$('#theatreC').on('click', function() {
$.ajax({
type: "POST",
url: '/Inicio.html',
data: {
llama: teatro
},
datatype: 'html',
success: function success(data) {
$('#mainPage').html(
"<p>Buscando...</p>"
);
},
error: function error(data) {
$('#mainPage').html(
"<p>Error</p>"
);
}
});
});
});
and it doesn't do anything. I checked the console, but there's no error about the script. I want that, when the user clicks on the list element with id "theatreC", it writes in the with id "mainPage". This is the header of my html file:
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="Fuentes/Fuentes.css">
<link rel="stylesheet" href="css/estilos.css">
<link rel="stylesheet" href="Icon.css">
<script src="//code.jquery.com/jquery-latest.js"></script>
<script src="script.js"></script>
</head>
I have a Web API and I'm trying to get JSON Data from it by using Vue, but I get neither data or errors, so I don't what is wrong. I want to load the data when the page is loaded.
Here is my code:
const v = new Vue({
el: '#divContent',
ready: function () {
this.loadData();
},
data: {
content: 'loading',
serverData: null
},
methods: {
loadData: function (viewerUserId, posterUserId) {
const that = this;
$.ajax({
contentType: "application/json",
dataType: "json",
url: "http://my-webapi/",
method: "Post",
success: function (response) {
that.$data.serverData = response;
},
error: function () {
alert('Error')
}
});
}
}
});
My HTML
<div id="divContent" class="content">
{{ content }}
</div>
Yes you can use jQuery’s $.ajax() API. However, using jQuery just for making Ajax calls is not recommended. You don’t want to include the whole jQuery library just for the purpose of using Ajax, do you? :-)
For Vue.js, you have quite a few options for using Ajax, such as:
Axios
vue-resource
Browser's built-in fetch API (Using fetch)
Here is an example of using the Browser's fetch API.
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.16/dist/vue.js"></script>
</head>
<body>
<div id="divContent">
<h1>Article Search Results</h1>
<form v-on:submit.prevent="search">
<input type="text" v-model="query">
<button type="submit">Search</button>
</form>
<ul>
<li v-for="article in articles" v-bind:key="article.source + article.id">
{{ article.title }}
</li>
</ul>
</div>
</body>
</html>
JavaScript
const vm = new Vue({
el: '#divContent',
data() {
return {
query: 'gene',
articles: 'loading'
}
},
created() {
this.search();
},
methods: {
search: function () {
fetch(`https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=${this.query}&format=json`)
.then(response => response.json())
.then(json => {
this.articles = json.resultList.result;
});
}
}
});
Output
You appear to already be using jQuery, so to load the Vue when the page is loaded you can update your code to the following:
$(function(){
const v = new Vue({
el: '#divContent',
created: function () {
this.loadData();
},
data: {
content: 'loading',
serverData: null
},
methods: {
loadData: function (viewerUserId, posterUserId) {
const that = this;
$.ajax({
contentType: "application/json",
dataType: "json",
url: "http://my-webapi/",
method: "Post",
success: response => this.serverData = response,
error: err => alert('Error')
});
}
}
});
})
The syntax above is using the jQuery.ready shorthand to create the Vue only after the page is loaded.
Without jQuery, you might want to listen for the DOMContentLoaded event.
Alternatively, just load the script that creates the Vue at the bottom of the page and not in the header.
Here is a complete, working example.
console.clear()
$(function(){
const v = new Vue({
el: '#divContent',
created: function () {
this.loadData();
},
data: {
content: 'loading',
serverData: null
},
methods: {
loadData: function (viewerUserId, posterUserId) {
$.ajax({
contentType: "application/json",
dataType: "json",
url: "https://httpbin.org/post",
data: JSON.stringify({testing: "some value"}),
method: "Post",
success: response => {
this.content = "loaded"
this.serverData = response.json
},
error: err => console.log('Error')
});
}
}
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.js"></script>
<div id="divContent" class="content">
{{ content }}
<hr>
Response: <br>
{{ serverData }}
</div>
Anything your put inside methods: {} won't work
unless you call loadData() with #click on the element or when page loads.
So, you should call it on the element or using either created/mount methods:
So, in your case either do this.
<div id="divContent" class="content" #click='loadData'>
or call the method when the page loads as:
created () {
this.loadData()
}
For Loading it on the page load, you can do the following:
const v = new Vue({
el: '#divContent',
data: {
content: 'loading',
serverData: null
},
methods: {
loadData(viewerUserId, posterUserId) {
$.ajax({
contentType: "application/json",
dataType: "json",
url: "http://my-webapi/",
method: "POST",
success: function (response) {
this.content = 'loaded';
this.serverData = response;
},
error: function () {
alert('Error')
}
});
}
},
mounted() {
this.loadData()
}
});
Hey guys I am new with this json syntax and I have one problem.
I made function that gets data from remote server in json like this:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery-3.1.0.min.js"></script>
<script type="text/javascript">
function getStates(value) {
var data = {
q: value
}
$.ajax({
url: 'https://something.hr/api/search',
method: 'GET',
headers: {'Accept': 'application/json'},
data: data
}).done(function(data) {
//do something with data I returned to you
console.log("success")
console.log(data)
}).fail(function(data) {
//doSomethingWith the data I returned to you
console.log("fail")
console.log(data)
});
};
</script>
</head>
<body>
<input type="text" onkeyup="getStates(this.value)" >
<br>
<script>
</script>
</body>
</html>
My problem is that I know how to get object in console log, but i wish to get that object in html, like in some box, than click on it and open his data(name, id, adress etc.)
var httpManager = (function() {
var getData = function(value) {
$.ajax({
url: 'https://api.github.com/users/zixxtrth',
method: 'GET'
}).done(function(data) {
//do something with data I returned to you
jQuery('#avatar').attr('src', data.avatar_url);
jQuery('#name').html(data.name);
jQuery('#username').html(data.login);
}).fail(function(data) {
//doSomethingWith the data I returned to you
alert('No Data');
});
};
return {
getData: getData()
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<img src='' id='avatar' width='200' height='200' />
<h1 id='name'></h1>
<h2 id='username'></h2>
I am trying to call ajax and get my HTML contend .But I want to show that data on tooltip/or pop over .I am getting the data on console I don't know why it showing black data tooltip it is showing black .is there problem in binding ?
here is plunker
http://plnkr.co/edit/OYiawflIBnpJ1PKx02LG?p=preview
when you click "star" image it show blank data.why ?
app.directive('mypopover', function ($compile,$templateCache) {
var getTemplate = function (contentType,scope,element) {
var template = $templateCache.get("templateId.html");
$.ajax({
type: "GET",
url: 'partials/popup.html',
type: 'get',
dataType: 'html',
success: function (data) {
alert('d'+data)
var options = {
content: $(template).html(data),
placement: "right",
html: true,
date: scope.date
};
$(element).popover(options);
},
error: function (data) {
}
});
return template;
}
return {
restrict: "A",
link: function (scope, element, attrs) {
console.log('entering link')
var popOverContent;
popOverContent = getTemplate("user",scope,element);
}
};
});
there was few error please see here: http://plnkr.co/edit/5SpDRkMokbPCMRT8oB0r?p=preview
app.directive('mypopover', function($compile, $templateCache) {
var getTemplate = function(contentType, scope, element) {
var template = $templateCache.get("templateId.html");
$.ajax({
type: "GET",
url: 'pop.html',
type: 'get',
dataType: 'html',
success: function(data) {
console.log($(template).html(data));
var options = {
content: data,
placement: "right",
html: true,
date: scope.date
};
$(element).popover(options);
},
error: function(data) {
alert(data)
}
});
return template;
}
return {
restrict: "A",
link: function(scope, element, attrs) {
console.log('entering link')
var popOverContent;
popOverContent = getTemplate("user", scope, element);
}
};
});
html:
<head>
<link data-require="bootstrap-css#3.x" data-semver="3.2.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<script data-require="jquery#2.1.1" data-semver="2.1.1" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script data-require="angular.js#*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script data-require="ui-bootstrap#0.10.0" data-semver="0.10.0" src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.10.0.js"></script>
<script data-require="angular-route#1.2.16" data-semver="1.2.16" src="http://code.angularjs.org/1.2.16/angular-route.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="https://dl.dropboxusercontent.com/s/a98aey2mlu0h511/bootstrap-tooltip.js"></script>
<script src=" https://dl.dropboxusercontent.com/s/s1imyubboz1qjtl/bootstrap-popover.js?m="></script>
<script src="script.js"></script>
</head>
The error was in your <script> tags list : http://plnkr.co/edit/GUlSHxy6aEwfVZuXFwDM?p=preview
<script src="https://dl.dropboxusercontent.com/s/a98aey2mlu0h511/bootstrap-tooltip.js"></script>
<script src="https://dl.dropboxusercontent.com/s/s1imyubboz1qjtl/bootstrap-popover.js?m="></script>
<script src="script.js"></script>
I have this short piece of code:
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<script type="text/javascript">
$("#term").autocomplete({
source: function(request, response) {
$.ajax({
url: 'http://query.yahooapis.com/v1/public/yql',
dataType: 'JSONP',
data: {
format: 'json',
q: 'select * from xml where url="http://google.com/complete/search?output=toolbar&q=' + encodeURIComponent(request.term) + '"'
},
success: function(data) {
response($.map(data.query.results.toplevel.CompleteSuggestion, function(item) {
return { label: item.suggestion.data, value: item.suggestion.data };
}));
}
});
}
});
</script>
</head>
<body>
<label for="term">Search term: </label>
<input id="term" />
</body>
</html>
It is working good online at JsBin: JsBin preview
However when I copy code to desktop so I can work with it it doesn't work (it used to work however) What am I doing wrong?? Why is this not working except online??
try wrapping the javascript code inside the ready handler, jsbin does it automatically
$(document).ready(function(){
//your code here
});
or the short cut
$(function(){
//your code here
});
this wil execute the script once the DOM has finished loading, or as an alternative you can place the javascript at the end of the document so it is executed when the DOM has loaded
You are referring to the input element before it has been created. Perform your autocompletion initialization after the DOM elements have been set up.
...
<script type="text/javascript">
$(function() {
$("#term").autocomplete({
source: function(request, response) {
$.ajax({
url: 'http://query.yahooapis.com/v1/public/yql',
dataType: 'JSONP',
data: {
format: 'json',
q: 'select * from xml where url="http://google.com/complete/search?output=toolbar&q=' + encodeURIComponent(request.term) + '"'
},
success: function(data) {
response($.map(data.query.results.toplevel.CompleteSuggestion, function(item) {
return {
label: item.suggestion.data,
value: item.suggestion.data
};
}));
}
});
}
});
});
</script>
...