Right now I am displaying all rows from Mysql DB to front end and I am using React JS as part of my project. I am struck with
1) How to get first 10 rows, then next 10 rows, then next 10 rows, till last row from Mysql DB using hibernate?
2) How can I invoke the ajax call in UI after 10 rows are scrolled.
The React JS code I am using now
<script type="text/babel">
var CommentBox = React.createClass({
loadCommentsFromServer: function(){
$.ajax({
url:this.props.url,
dataType: 'json',
cache: false,
success: function(data){
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err){
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
getInitialState: function(){
return {data: []};
},
componentDidMount: function(){
this.loadCommentsFromServer();
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
},
render: function(){
return (
<div className="commentBox">
<CommentList data={this.state.data}/>
</div>
);
}
});
var CommentList = React.createClass({
render:function(){
var commentNodes = this.props.data.map(function(comment) {
return(
<Comment >
{comment}
</Comment>
);
});
return(
<div className="commentList">
{commentNodes}
</div>
);
}
});
var Comment = React.createClass({
rawMarkup: function() {
var rawMarkup = marked(this.props.children.toString(), {sanitize: true});
return { __html: rawMarkup };
},
render: function(){
return (
<div className="comment">
<span dangerouslySetInnerHTML={this.rawMarkup()} />
</div>
)
}
});
ReactDOM.render(
<CommentBox url="/url/abc" pollInterval={10000}/>,
document.getElementById('content')
);
</script>
I came across the following piece of code w.r.t Infinite scroll, but not sure how to use this along with React JS
$(document).ready(function(){
$contentLoadTriggered = false;
$("#content-box").scroll(function(){
if($("#content-box").scrollTop() >= ($("#content-wrapper").height() - $("#content-box").height()) && $contentLoadTriggered == false)
{
$contentLoadTriggered = true;
$.get("infinitContentServlet", function(data){
$("#content-wrapper").append(data);
$contentLoadTriggered = false;
});
}
});
});
3) Also right now I am using .setFetchSize(10) in Hibernate. Not sure whether it will add next 10, and then next 10 as I am not able to test the scenario as my UI is not yet ready. I am struck and helpless. Please help me. Thanks.
You don't need to use setFetchSize(10) for a pagination. It is for an optimization purposes. For a pagination with Hibernate you can use this simply class (pageSize = 10 for your example)
public class Pagination {
public static final Pagination EMPTY = new Pagination(0, 0);
/** Page index, begins from 0. */
private final int pageIndex;
/** Objects on page count. */
private final int pageSize;
public Pagination(int pageIndex, int pageSize) {
this.pageIndex = pageIndex;
this.pageSize = pageSize;
}
public void addToCriteria(final Criteria criteria) {
if (this == EMPTY) {
return;
}
criteria.setMaxResults(pageSize);
criteria.setFirstResult(pageIndex * pageSize);
}
}
An example of using with Criteria.
Related
I'm making a code to fetch content from contentful using AJAX. I've success retrieve data and display it, but something is not quite what I want. Because the content that I get is not in the same order as the contentful cms, so I add another field called sequence. So in my code I added a sort() and Object.keys() function before forEach(), but there is no error and data not appears ,does anyone know why data not appears?
If you want to try debugging, you can look at This Codepen.
function renderContentBySection(sectionName, appendElement, numberOfSkeleton, elementAttribute, elementClass){
$.ajax({
url : 'https://cdn.contentful.com/spaces/r5mgd95bqsb5/environments/master/entries/1bI13SpZBBvgOgIk4GhYEg?access_token=CVel_r57GUqeTeaLyIsseXEAM1z1f-spXNKR-a2-huA',
type: 'GET',
success: function(data){
const getData = data.fields
if(getData[sectionName]) {
if(getData[sectionName] && getData[sectionName].length) {
getData[sectionName].forEach((item, index) => {
getSingleEntry(item.sys.id)
});
}
}
}
});
}
function getSingleEntry(contentId){
$.ajax({
url : `https://cdn.contentful.com/spaces/r5mgd95bqsb5/environments/master/entries/${contentId}?access_token=CVel_r57GUqeTeaLyIsseXEAM1z1f-spXNKR-a2-huA`,
type: 'GET',
success: function(dataKat){
getAssetData(dataKat.fields.image.sys.id, dataKat.fields.sequence)
$('.data-banner').append(JSON.stringify(dataKat.fields, null, 4))
$('.data-banner').append('<br>');
}
});
}
function getAssetData(assetsId, sequenceId){
$.ajax({
url : `https://cdn.contentful.com/spaces/r5mgd95bqsb5/environments/master/assets/${assetsId}?access_token=CVel_r57GUqeTeaLyIsseXEAM1z1f-spXNKR-a2-huA`,
type: 'GET',
success: function(getAssetsData){
$('.data-image').append(JSON.stringify(getAssetsData.fields, null, 4))
$('.data-image').append('<br>');
}
});
}
$(document).ready(function(){
renderContentBySection('mainBannerImage', '#carousel-inner', 1, 'banner', 'main-banner-item');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<pre class="data-banner">
<h4>Get Data Main Banner:</h4>
</pre>
<br>
<pre class="data-image">
<h4>Get Data for Each Image in Main Banner:</h4>
</pre>
Because you completely changed the criteria, I will provide an answer for your second ask.
The key to working with multiple batches of asynchronous requests is to gather all the requests, and then listen for them all to complete. Then, do the same thing again with the next batch of requests.
Otherwise, your HTML will print in the order the responses are returned and it will seem random.
Once you have gathered all the completed requests, you can sort() them, then do a forEach through them.
function listenForEntries(arrAllEntryRequests) {
//set up a listener for when all requests have finished, using "spread operator" (...) to send all requests as parameters to when():
$.when(...arrAllEntryRequests).done(
//done:
function (...arrAllEntryResponses) {
let arrAllEntries = [];
//console.log("arrAllEntryResponses", arrAllEntryResponses);
arrAllEntryResponses.forEach((e) => {
arrAllEntries.push(e[0].fields);
});;
//all images loaded, sort:
arrAllEntries.sort((a, b) => (a.sequence < b.sequence ? -1 : 1));
//sorting done, get asset data for each. This is also asyncronous so you need to do the same thing as above:
let arrAllAssetRequests = [];
arrAllEntries.forEach((entryData) => {
//console.log("entryData", entryData);
$('.data-sequence').append(`
<ul>
<li>
Sequence ID: ${entryData.sequence}<br>
Title Banner: ${entryData.title}
</li>
</ul>`)
let assetReqObj = getAssetData(entryData.image.sys.id, entryData.sequence);
arrAllAssetRequests.push(assetReqObj);
});
listenForAssets(arrAllAssetRequests);
}
);
}
function listenForAssets(arrAllAssetRequests) {
$.when(...arrAllAssetRequests).done(
//done:
function (...arrAllAssetResponses) {
//all assets loaded, sort:
arrAllAssetResponses.sort((a, b) => (a[2].sequence < b[2].sequence ? -1 : 1));
arrAllAssetResponses.forEach((assetData) => {
//console.log("assetData", assetData);
if(assetData.length > 0) {
$('.data-assets').append(`
<ul>
<li>
Sequence ID: ${assetData[2].sequence}<br>
Title Banner: ${assetData[0].fields.title}<br>
<img class="img-fluid" src="${assetData[0].fields.file.url}">
</li>
</ul>`);
} else {
console.error("Something wrong with assetData", assetData);
}
});
}
);
}
function renderContentBySection(sectionName, appendElement, numberOfSkeleton, elementAttribute, elementClass) {
$.ajax({
url: 'https://cdn.contentful.com/spaces/r5mgd95bqsb5/environments/master/entries/1bI13SpZBBvgOgIk4GhYEg?access_token=CVel_r57GUqeTeaLyIsseXEAM1z1f-spXNKR-a2-huA',
type: 'GET',
success: function (data) {
const getData = data.fields
//move array to inside this function as it's the only place it will be used:
let arrAllEntryRequests = [];
if (getData[sectionName]) {
if (getData[sectionName] && getData[sectionName].length) {
getData[sectionName].forEach((item, index) => {
arrAllEntryRequests.push(getSingleEntry(item.sys.id));
});
//once array of requests is created, listen for it to finish:
listenForEntries(arrAllEntryRequests);
}
}
}
});
}
function getSingleEntry(contentId) {
return $.ajax({
url: `https://cdn.contentful.com/spaces/r5mgd95bqsb5/environments/master/entries/${contentId}?access_token=CVel_r57GUqeTeaLyIsseXEAM1z1f-spXNKR-a2-huA`,
type: 'GET',
success: function (dataKat) {
//do nothing
}
});
}
function getAssetData(assetsId, sequenceId) {
let $xhr = $.ajax({
url: `https://cdn.contentful.com/spaces/r5mgd95bqsb5/environments/master/assets/${assetsId}?access_token=CVel_r57GUqeTeaLyIsseXEAM1z1f-spXNKR-a2-huA`,
type: 'GET',
success: function (assetData) {
//do nothing
}
});
$xhr.sequence = sequenceId; //store the sequence for later
return $xhr;
}
$(document).ready(function () {
renderContentBySection('mainBannerImage', '#carousel-inner', 1, 'banner', 'main-banner-item');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container-fluid">
<div class="row">
<div class="col-6">
<div class="data-sequence">
<span> This is sequence data:</span>
</div>
</div>
<div class="col-6">
<div class="data-assets">
<span> This is assets data:</span>
</div>
</div>
</div>
</div>
Because your data is loaded asyncronously, you will need to create a queue of your requests, and listen for them to all finish.
I have commented my code below so you can understand how it works.
First, you need to use the spread operator a lot ..., to work with an unknown number of array elements.
(https://stackoverflow.com/a/35169449/1410567)
Second, you need to use $.when(...array).done(function(...results) { to know when the requests have finished.
(https://blog.kevinchisholm.com/javascript/jquery/using-jquery-deferred-to-manage-multiple-ajax-calls/)
Third, you need to use Array.sort() to sort the array of objects, comparing their sequence, and returning 1 or -1 to sort them.
(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
//create an empty array to hold the queue:
let allImageRequests = [];
function listenForImages() {
//set up a listener for when all requests have finished, using "spread operator" (...) to send all requests as parameters to when():
$.when(...allImageRequests).done(
//done:
function (...arrAllImagesResp) {
let arrAllImages = [];
console.log("arrAllImagesResp", arrAllImagesResp);
arrAllImagesResp.forEach((e) => {
console.log(e);
arrAllImages.push(e[0].fields);
});;
//all images loaded, sort:
arrAllImages.sort((a, b) => (a.sequence < b.sequence ? -1 : 1));
console.log("done", arrAllImages);
//sorting done, display results:
$('.data-image').append("\n\n<strong>All Images Sorted:</strong> \n\n" + JSON.stringify(arrAllImages, null, 4));
}
);
}
$.ajax({
url: 'https://cdn.contentful.com/spaces/r5mgd95bqsb5/environments/master/entries/1bI13SpZBBvgOgIk4GhYEg?access_token=CVel_r57GUqeTeaLyIsseXEAM1z1f-spXNKR-a2-huA',
type: 'GET',
success: function (data) {
console.log("got data", data);
const getData = data.fields.mainBannerImage
$('.data-banner').append(JSON.stringify(getData, null, 4))
$('.data-banner').append('<br>');
getData.forEach((item, index) => {
//add requests to our queue:
allImageRequests.push(getImageAssets(item.sys.id));
});
listenForImages();
}
})
function getImageAssets(assetId) {
//I added a return here, so the XHR objects will be push()'d to the allImageRequests queue array:
return $.ajax({
url: `https://cdn.contentful.com/spaces/r5mgd95bqsb5/environments/master/entries/${assetId}?access_token=CVel_r57GUqeTeaLyIsseXEAM1z1f-spXNKR-a2-huA`,
type: 'GET',
success: function (assetsData) {
const getAssetsData = assetsData.fields
$('.data-image').append(JSON.stringify(getAssetsData, null, 4))
$('.data-image').append('<br>');
}
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<pre class="data-banner">
<h4>Get Data Main Banner:</h4>
</pre>
<br>
<pre class="data-image">
<h4>Get Data for Each Image in Main Banner:</h4>
</pre>
i have problem. When I click the button, it receives an entire database, but I want laod part database. How can I do this?
For example: After every click I would like to read 10 posts.
Thx for help.
Messages.vue:
<div class="chat__messages" ref="messages">
<chat-message v-for="message in messages" :key="message.id" :message="message"></chat-message>
<button class="btn btn-primary form-control loadmorebutton" #click="handleButton">Load more</button>
</div>
export default{
data(){
return {
messages: []
}
},
methods: {
removeMessage(id){...},
handleButton: function () {
axios.get('chat/messagesmore').then((response) => {
this.messages = response.data;
});
}
},
mounted(){
axios.get('chat/messages').then((response) => {
this.messages = response.data
});
Bus.$on('messages.added', (message) => {
this.messages.unshift(message);
//more code
}).$on('messages.removed', (message) => {
this.removeMessage(message.id);
});
}
}
Controller:
public function index()
{
$messages = Message::with('user')->latest()->limit(20)->get();
return response()->json($messages, 200);
}
public function loadmore()
{
$messages = Message::with('user')->latest()->get();
// $messages = Message::with('user')->latest()->paginate(10)->getCollection();
return response()->json($messages, 200);
}
paginate(10) Loads only 10 posts
You can do it like this:
<div class="chat__messages" ref="messages">
<chat-message v-for="message in messages" :key="message.id" :message="message"></chat-message>
<button class="btn btn-primary form-control loadmorebutton" #click="handleButton">Load more</button>
</div>
export default{
data(){
return {
messages: [],
moreMessages: [],
moreMsgFetched: false
}
},
methods: {
removeMessage(id){...},
handleButton: function () {
if(!this.moreMsgFetched){
axios.get('chat/messagesmore').then((response) => {
this.moreMessages = response.data;
this.messages = this.moreMessages.splice(0, 10);
this.moreMsgFetched = true;
});
}
var nextMsgs = this.moreMessages.splice(0, 10);
//if you want to replace the messages array every time with 10 more messages
this.messages = nextMsgs
//if you wnt to add 10 more messages to messages array
this.messages.push(nextMsgs);
}
},
mounted(){
axios.get('chat/messages').then((response) => {
this.messages = response.data
});
Bus.$on('messages.added', (message) => {
this.messages.unshift(message);
//more code
}).$on('messages.removed', (message) => {
this.removeMessage(message.id);
});
}
}
-initialize a data property morMsgFetched set to false to indicate if more messages are fetched or not
if morMsgFetched is false make the axios request and st the response to moreMessages, then remove 10 from moreMessages and set it to messages[]..
After that set morMsgFetched to true
on subsequest click remove 10 from moreMessages and push it to 'messages[]`
Use Laravels built in pagination.
public function index()
{
return Message::with('user')->latest()->paginate(20);
}
It returns you next_page url which you can use to get more results calculated automatically
This might be too late but i believe the best way to do it is using pagination, Initially onMounted you'll send a request to let's say /posts?page=1, the one is a variable let's say named 'pageNumber', each time the user clicks on the "Load More" button, you'll increment the pageNumber and resent the request, the link will page /posts?page=2 this time, at this point you can append the results you've got to the already existing one and decide if the Load More button should be shown based on the last_page attribute returned by laravel paginator...
I'm sure you already solved your problem or found another alternative, this might be usefull for future developers.
I'm trying to implement something with jQuery and Vue.js:
And here is my script part:
<script>
function initVM(result) {
// alert(result.num)
var vm2 = new Vue({
el: '#vm2',
data: {
// ③bind one item of the result as example
rrr: result.num
}
});
$('#vm2').show();
}
$(function() {
var vm = new Vue({
el: '#vm',
data: {
content: ''
},
methods: {
submit: function(event) {
event.preventDefault();
var
$form = $('#vm'),
content = this.content.trim();
// ①post textarea content to backend
$form.postJSON('/api/parse', {
content: content
}, function(err, result) {
if (err) {
$form.showFormError(err);
}
else {
// ②receive a result dictionary
$('#vm').hide();
initVM(result);
}
});
}
}
});
});
</script>
Here is my html part:
<html>
<form id="vm", v-on="submit: submit">
<textarea v-model="content" name="content"></textarea>
<button type="submit">Have a try!</button>
</form>
<div id="vm2" style="diplay:none;">
<!-- ④show the result-->
The result:
{{ rrr }}
</div>
</html>
Here is the definition of postJSON
<script>
// ...
postJSON: function (url, data, callback) {
if (arguments.length===2) {
callback = data;
data = {};
}
return this.each(function () {
var $form = $(this);
$form.showFormError();
$form.showFormLoading(true);
_httpJSON('POST', url, data, function (err, r) {
if (err) {
$form.showFormError(err);
$form.showFormLoading(false);
}
callback && callback(err, r);
});
});
// ...
// _httpJSON
function _httpJSON(method, url, data, callback) {
var opt = {
type: method,
dataType: 'json'
};
if (method==='GET') {
opt.url = url + '?' + data;
}
if (method==='POST') {
opt.url = url;
opt.data = JSON.stringify(data || {});
opt.contentType = 'application/json';
}
$.ajax(opt).done(function (r) {
if (r && r.error) {
return callback(r);
}
return callback(null, r);
}).fail(function (jqXHR, textStatus) {
return callback({'error': 'http_bad_response', 'data': '' + jqXHR.status, 'message': 'something wrong! (HTTP ' + jqXHR.status + ')'});
});
}
</script>
The process can be described as:
Post the content to backend
Receive the result and hide the form
Create a new Vue with the result
Show the result in a div which is binding with the new Vue instance
Actually, I do receive the result successfully, which is proved by the alert(result.num) statement, but nothing find in vm2's div except The result:
Where is the problem? Or please be free to teach me a simpler approach if there is, because I don't think what I am using is a good one.
Here's questioner.
Finally I found where is the problem.
The problem lays in Mustache: {{ }}
I use jinja2, a template engine for Python and Vue.js, a MVVM frontend framework. Both of them use {{ }} as delimiters.
So if anyone got trapped in the same situation with me, which I don't think there will be, please:
app.jinja_env.variable_start_string = '{{ '
app.jinja_env.variable_end_string = ' }}' # change jinjia2 config
OR
Vue.config.delimiters = ['${', '}'] # change vue config
I am having trouble actioning a callback function in one of my React classes. Basically I call checkSource on click and then if it meets a specific requirement I want to call handleSubmitClick. I have a feeling this has to do with me calling this.handleSubmitClick, but I don't understand. My understanding is that the this is referring to the component object that I created. If this is the case, shouldn't it just call that function and execute?
The full component is here:
var React = require('react');
module.exports = React.createClass({
getInitialState: function() {
return {
text: ''
}
},
handleTextInput: function(event){
this.setState({text: event.target.value})
},
checkSource: function(){
var clientId = 'xxxx';
var resolve = 'http://api.soundcloud.com/resolve?url=';
$.get(resolve + this.state.text + '&client_id=' + clientId, function(data) {
$.get('http://api.soundcloud.com/users/' + data.user.id + '/?client_id=' + clientId, function(data) {
if(data.followers_count < 3000) {
console.log("handleSubmitClick now");
this.handleSubmitClick();
} else {
return false;
}
});
});
},
handleSubmitClick: function() {
console.log('handleSubmitClick going')
console.log(this.state.text)
var linkStore = this.props.linkStore
linkStore.push(this.state.text)
this.setState({text: ''})
this.props.handleListSubmitClick(linkStore)
console.log(this.props.linkStore)
},
render: function() {
return <div className="row">
<div className="col-md-8 col-md-offset-2">
<div className="text-center">
<h1>Soundcloud3k</h1>
</div>
<div className="input-group">
<input
onChange = {this.handleTextInput}
type="text"
className="form-control"
placeholder="Search fr..."
value={this.state.text} />
<span className="input-group-btn">
<button
onClick={this.checkSource}
className="btn btn-default"
type="button">Submit!</button>
</span>
</div>
</div>
</div>
}
});
This is the render function with the checkSource call
The console logs for the checkSource function works as intended, but I can't get the handleSubmitClick to do anything. I don't get an error or anything in the console. Any ideas?
In $.get callback this does not refer to your component, you should set this for each callback. Also return false in ajax callback does not make sense so you can remove it
checkSource: function(){
var clientId = 'xxxx';
var resolve = 'http://api.soundcloud.com/resolve?url=';
$.get(resolve + this.state.text + '&client_id=' + clientId, function(data) {
$.get('http://api.soundcloud.com/users/' + data.user.id + '/?client_id=' + clientId, function(data) {
if(data.followers_count < 3000) {
this.handleSubmitClick();
}
}.bind(this));
}.bind(this));
},
The below added code is working fine in React js 0.10.0. I wanna run same code in 0.13.0 version also. My main requirement is accessing nested object as default object like "this.state.data.query.results.channel.item.condition.temp".
<!doctype html>
<html>
<head>
<title>Weather Widget</title>
<link rel="stylesheet" href="weather.css" />
<script src="http://fb.me/react-0.10.0.js"></script>
<script src="http://fb.me/JSXTransformer-0.10.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<script type="text/jsx">
/*** #jsx React.DOM */
var weatherWidget = React.createClass({
loadData: function(){
$.ajax({
url: 'http://query.yahooapis.com/v1/public/yql?q=select%20item%20from%20weather.forecast%20where%20location%3D%2222102%22&format=json',
dataType : "jsonp",
cache: false,
success: function(data) {
console.log(data)
this.setState({data: data});
}.bind(this)
});
},
getInitialState: function(){
return {data: []};
},
componentWillMount: function(){
this.loadData();
},
render: function(){
return(
<div className="ww-container">
<div className="ww-current-condition">
<div className="ww-current-temperture">{this.state.data.query.results.channel.item.condition.temp}°</div>
</div>
</div>
)
}
});
React.renderComponent(<weatherWidget />, document.body);
</script>
</body>
</html>
http://jsfiddle.net/xJvY5/
You should set initial state, like so
getInitialState: function(){
return {
data: {
query: {
results: {
channel: {item: {condition: {temp: 0}}}
}
}
}
};
},
Example - (v 0.10.0)
Example - (v 0.13.3) - Note - that in version 0.13.3 you should use .render method instead of .renderComponent
or you can check data in render method, if data is undefined - show loading...., if state was updated you will see your data
getInitialState: function(){
return {};
},
render: function() {
if (!this.state.data) {
return <div>Loading...</div>;
}
....
}
Example - (v 0.13.3)