I have a little problem with iterating through JSON objects. I have a JSON file which I get with AJAX, I have there 15 objects. In HTML I have a DIV in which are 3 sections: header, body and date. Every 15 sec I should update this sections with data from JSON file.
HTML:
<div class="blog">
<span id="header">
Blog
</span>
<span id="body">
20+ Best Examples of <br>
Coming Soon Page Design
</span>
<span id="date">
May 28, 2013
</span>
</div>
JavaScript:
$(function() {
$.ajax({
url: "news.json",
success: function(result) {
var headCont = $('#header');
var bodyCont = $('#body');
var dateCont = $('#date');
var res = result.news;
$.each(res, function(index, element) {
for (header in res) {
setInterval(function() {
headCont.html(element.header);
}, 15000)
}
});
}
});
});
JSON:
{
"news": [{
"header": "Microsoft is starting a private beta for its iPhone keyboard",
"body": "Microsoft has its own mobile operating system, but that hasn't stopped it from opening a public beta for a new iPhone keyboard.",
"date": "2016-04-14T08:40:23.449Z"
}, {
"header": "Microsoft sues U.S. government over data gag orders",
"body": "Microsoft wants a federal court to invalidate part of a 1986 law that it alleged has been abused by the government when authorities demand customers' data.",
"date": "2016-03-14T08:40:23.449Z"
}]
}
You should never run interval on AJAX
In your case you only call the server once and loop over the same data
Assuming your JSON works with your loop, perhaps you meant
function updateIt() {
var headCont = $('#header');
var bodyCont = $('#body');
var dateCont = $('#date');
$.ajax({
url: "news.json",
success: function(result) {
var res = result.news;
$.each(res, function(index, element) {
for (header in res) {
headCont.append(element.header);
}
});
});
setTimeout(updateIt,15000); // run after success. use always or complete if needed
}
}
If you need to update the DIV every 15 seconds with the list of stories gotten with ONE AJAX call, then you need to loop with
var news,cnt=0,tId;
function render() {
if (cnt >= news.length) {
clearInterval(tId); // OR set cnt to 0 and do not return to re-iterate
return;
}
var item = news[cnt];
$('#header').append(item.header);
$('#body').append(item.body);
$('#date').append(item.date);
cnt++;
}
$(function() {
.
succes: function(result) {
news = result.news;
render(); // run immediately
var tId = setInterval(render,150000); // and schedule next run
}
.
});
result = {
"news": [{
"header": "Microsoft is starting a private beta for its iPhone keyboard",
"body": "Microsoft has its own mobile operating system, but that hasn't stopped it from opening a public beta for a new iPhone keyboard.",
"date": "2016-04-14T08:40:23.449Z"
}, {
"header": "Microsoft sues U.S. government over data gag orders",
"body": "Microsoft wants a federal court to invalidate part of a 1986 law that it alleged has been abused by the government when authorities demand customers' data.",
"date": "2016-03-14T08:40:23.449Z"
}]
}
var news, cnt = 0, tId;
function render() {
console.log(cnt,news[cnt]);
if (cnt >= news.length) cnt = 0; // rerun
var item = news[cnt];
$('#header').html(item.header);
$('#body').html(item.body);
$('#date').html(item.date);
cnt++;
}
$(function() {
news = result.news;
render();
var tId = setInterval(render, 5000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="header"></div>
<div id="body"></div>
<div id="date"></div>
EDIT
Check this example. It itterates over an array of objects and updates the content every 2 seconds:
var result = [
{ header: 'header0', body: 'body0' },
{ header: 'header1', body: 'body1' },
{ header: 'header2', body: 'body2' },
{ header: 'header3', body: 'body3' },
{ header: 'header4', body: 'body4' },
{ header: 'header5', body: 'body5' },
{ header: 'header6', body: 'body6' },
{ header: 'header7', body: 'body7' }
]
i = 0;
var update = setInterval(function() {
if (result[i]) {
$('#header').html(result[i].header);
$('#body').html(result[i].body);
i++;
} else {
clearInterval(update);
}
}, 2000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<h1>Header: <span id="header"></span></h1>
<h1>Body: <span id="body"></span></h1>
Related
Hello I am trying to figure out how to get the "changes" value from
{ data: { sequenceStart: 1613141716565, symbol: 'KCS-BTC', changes: { asks: [Array], bids: [] }, sequenceEnd: 1613141716565 }, subject: 'trade.l2update', topic: '/market/level2:KCS-BTC', type: 'message' }
The data is stored in let data = JSON.parse(msg)
I have tried console.log(data.data.changes) but get undefined, im lost because console.log(data.data) seems to get me part way there but not when I add .changes?
Can you check my code below.
I think your msg is not formated correctly , you can compare with my code
<body >
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($){
var msg = '{"data": { "sequenceStart": "1613141716565", "symbol": "KCS-BTC", "changes": { "asks":[["0","0","1613141798456"]],"bids":[]}, "sequenceEnd": 1613141716565 }, "subject": "trade.l2update", "topic": "/market/level2:KCS-BTC", "type": "message" }';
var data = JSON.parse(msg);
console.log(data.data.changes);
var msg1 = '{"sequenceStart":1613141798456,"symbol":"KCS-BTC","changes":{"asks":[["0","0","1613141798456"]],"bids":[]},"sequenceEnd":1613141798456}';
var data1 = JSON.parse(msg1);
console.log(data1.changes);
});
</script>
</body>
when i run solr, I got output like that, but i need show "response":{"numFound":4,"start":0,"maxScore":0.21373023,"docs"} line and all lines have id
this is my html
<div id="response">
<pre class="syntax language-{{lang}} content"><code ng-bind-html="response.data | highlight:lang | unsafe "></code></pre>
<div id="result">
<a ng-show="response.data" id="url" class="address-bar addressblock" ng-href="{{url}}">{{hostPortContext}}{{url}}</a>
</div>`
this is my query.js that In connection with the result (here "data" is result object)
var url = Query.url(params);
Query.query(params, function(data) {
$scope.lang = $scope.query.wt;
if ($scope.lang == undefined || $scope.lang == '') {
$scope.lang = "json";
}
$scope.response = data ;
$scope.filterdata=$filter('uppercase') ($scope.response);
$scope.url = url;
$scope.hostPortContext = $location.absUrl().substr(0,$location.absUrl().indexOf("#"));
});`
and got this result
{
"responseHeader":{
"zkConnected":true,
"status":0,
"QTime":21,
"params":{
"q":"sed",
"_":"1580536766390"}},
"response":{"numFound":4,"start":0,"maxScore":0.21373023,"docs":[
{
"id":"/home/sama/sama_installer/masternode",
"attr_stream_size":["15732"],
"attr_x_parsed_by":["org.apache.tika.parser.DefaultParser",
"org.apache.tika.parser.txt.TXTParser"],
"attr_stream_content_type":["application/octet-stream"],
"attr_content_encoding":["ISO-8859-1"],
"attr_resourcename":["/home/sama/sama_installer/masternode"],
"content_type":"application/x-sh; charset=ISO-8859-1",
"language":"en",
...
"_version_":1657306606928396288,
"content":" #!/bin/bash\n#installetion sama project on master\n#cheeke exits sama
{
"id":"/home/sama/sama_installer/start.sh",
"attr_stream_size":["290"],
"attr_x_parsed_by":["org.apache.tika.parser.DefaultParser",
"org.apache.tika.parser.txt.TXTParser"],
"attr_stream_content_type":["application/octet-stream"],
"attr_content_encoding":["ISO-8859-1"],
"attr_resourcename":["/home/sama/sama_installer/start.sh"],
"content_type":"application/x-sh; charset=ISO-8859-1",
"content":" #!/bin/bash\nstart-all.sh\nt=$(cat /var/sama/nodelist)\nfor i in ,
"language":"en",
"content_type_type_s":"application",
"content_type_subtype_s":"x-sh",
"url_ss":["start-all.sh",
"zkServer.sh"],
"_version_":1657306608004235264}]
}}
I am Assuming data realated to your Question. You Can fetch data in following manner. If it return undefined it means there is not parameter named 'id' else 'id' is present
var data = {
"responseHeader": {
"zkConnected": true,
"status": 0,
"id": 101,
"QTime": 21
},
"response": {
"numFound": 4,
"start": 0,
"maxScore": 0.21373023,
"id": 102
},
"response1": {
"numFound": 4,
"start": 0,
"maxScore": 0.21373023
}
}
console.log(data.response)
console.log(data.responseHeader["id"])
console.log(data.response["id"])
console.log(typeof(data.response1["id"]) == "undefined") //This way you can check if id is present or not.
if (typeof(data.response["id"]) != "undefined") {
console.log(data.response)
}
I have a problem with running VueJS on mobile devices. I created a weather prediction app on copepen.io
Here is the link for the project:
http://codepen.io/techcater/pen/xOZmgv
HTML code:
<div class="container-fluid text-center">
<h1>Your Local Weather</h1>
<p>
{{location}}
</p>
<p>
{{temperature}}
<a #click="changeDegree">{{degree}}</a>
</p>
<p>
{{weather | capitalize}}
</p>
<img :src="iconURL" alt="" />
<br>
by Dale Nguyen
<!-- <pre>{{$data | json}}</pre> -->
</div>
JS code:
new Vue({
el: '.container-fluid',
data: {
location: "",
temperature: "",
degree: "C",
weather: "",
iconURL: ""
},
created: function(){
this.getWeather();
},
methods: {
getWeather: function(){
var that = this;
this.$http.get("http://ipinfo.io").then((response) => {
console.log(response.data);
that.location = response.data.city + ", " + response.data.country;
// Get weather informaiton
var api = 'ebd4d312f85a230d5dc1db91e20c2ace';
var city = response.data.city;
var url = "http://api.openweathermap.org/data/2.5/weather?q={CITY}&APPID={APIKEY}&units=metric";
url = url.replace("{CITY}",city);
url = url.replace("{APIKEY}", api);
that.$http.post(url,{dataType: 'jsonp'},{
headers : {
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
}}).then((response) => {
console.log(response.data);
that.temperature = response.data.main.temp;
that.weather = response.data.weather[0]['description'];
that.iconURL = "http://openweathermap.org/img/w/" + response.data.weather[0]['icon'] + ".png";
}, (response) => {
// error callback
});
}, (response) => {
console.log(response.data);
});
},
changeDegree: function() {
if(this.degree == "C"){
this.degree = "F";
this.temperature = Math.round((this.temperature*9/5 + 32)*100)/100;
}else {
this.degree = "C";
this.temperature = Math.round(((this.temperature - 32)*5 /9)* 100)/100;
}
}
}
})
It works well on my laptop but not on mobile. At first, I thought that it is because of Codepen. It may cause something when running through the site. However, when I created a project on my website, it also doesn't work.
Can you help to find the issue? Thanks,
Your code seems to be working well, except that on codepen it gives me error XMLHttpRequest cannot load http://ipinfo.io/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://s.codepen.io' is therefore not allowed access..
You can put your domain name on headers options to enable cross-origin, here is example:
this.$http.get('http://ipinfo.io', {
'headers': {
'Origin': 'http://yourdomain.com'
}
})
See example: http://bozue.com/weather.html
I also noticed you put vue.min.js and vue-resource.js scripts in wrong order that might trigger some error, vue.min.js should be on the first place.
I found a solution for this. I works on my mobile now. I believe that I will work on other browses too. The problem is that some browsers doesn't recognize the operation ">", so I changed it.
Here is the new code:
getWeather: function(){
var that = this;
this.$http.get('http://ipinfo.io', {'headers': {
'Origin': 'http://yourdomain.com'}
}).then(function(response) {
console.log(response.data);
that.location = response.data.city + ", " + response.data.country;
// Get weather informaiton
var api = 'ebd4d312f85a230d5dc1db91e20c2ace';
var city = response.data.city;
var url = "https://crossorigin.me/http://api.openweathermap.org/data/2.5/weather?q={CITY}&APPID={APIKEY}&units=metric";
url = url.replace("{CITY}",city);
url = url.replace("{APIKEY}", api);
that.$http.post(url,{dataType: 'jsonp'},{
headers : {
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
}}).then(function(response) {
console.log(response.data);
that.temperature = response.data.main.temp;
that.weather = response.data.weather[0]['description'];
that.iconURL = "http://openweathermap.org/img/w/" + response.data.weather[0]['icon'] + ".png";
}).then(function(){
// error callback
});
}).then(function(){
console.log(response.data);
});
},
I have a Library angularJS application and a JSON Data file that contains an array of book's information like this
[
{
"name" : "test1",
"pages": 0,
"author": "author1",
"year": 1940,
"section": "history",
"current": 0,
"description": "bla bla bla",
"bookUrl": "data/book.pdf"
},
{
"name" : "test1",
"pages": 0,
"author": "author1",
"year": 1940,
"section": "history",
"current": 0,
"description": "bla bla bla",
"bookUrl": "data/book.pdf"
}
]
"current" is for the current page of the current book that i'm reading
and there is a "next" and "prev" buttons in the reading view
when i press "next" it adds "+1" to the "current" num page
the question is (How to send this +1 to the "current" in JSON file with PHP?)
I have this PHP code :
<?php
$jsonString = file_get_contents('library.json');
$data = json_decode($jsonString, true);
$data[0]['current'] = 3;
$newJsonString = json_encode($data);
file_put_contents('library.json', $newJsonString);
?>
See the ($data[0]) is for the index of the first book, how do i send to PHP the index of the current book so it updates the "current" data of the current book?
Here is the "next" function :
scope.goNext = function() {
if (scope.pageToDisplay >= pdfDoc.numPages) {
return;
}
scope.pageNum = parseInt(scope.pageNum) + 1;
$http.get("data/insert.php")
.success(function(data, status, headers, config) {
console.log("data inserted successfully");
});
};
And here is the reading Controller :
app.controller('read', ['$scope','books', '$routeParams',function($scope,books, $routeParams) {
books.success(function(data){
$scope.book = data[$routeParams.bookId]
$scope.pdfUrl = data[$routeParams.bookId].bookUrl;
$scope.pdfName = data[$routeParams.bookId].name;
});
//the pdf viewer options
//$scope.pdfUrl = 'data/tohfa12.pdf';
$scope.scroll = 0;
$scope.loading = 'Loading file please wait';
$scope.getNavStyle = function(scroll) {
if(scroll > 100) {
return 'pdf-controls fixed';
} else {
return 'pdf-controls';
}
};
$scope.onError = function(error) {
console.log(error);
};
$scope.onLoad = function() {
$scope.loading = '';
};
$scope.onProgress = function(progress) {
console.log(progress);
};
$scope.currentBookIndex = parseInt($routeParams.bookId);
}]);
I know it's complicated but i really need that , thanks.
How do you expect your application to behave?
You need to send the bookId and the pageNum with your request!
scope.goNext = function() {
if (scope.pageToDisplay >= pdfDoc.numPages) {
return;
}
scope.pageNum = parseInt(scope.pageNum) + 1;
$http.get("data/insert.php", {
param : {
bookId: $scope.bookId,
pageNum: $scope.pageNum
}
})
.success(function(data, status, headers, config) {
console.log("data inserted successfully");
});
};
BTW. By REST design a GET http request should never change a resource. GET is for READING. If you want to update a resource you should use POST, PUT or DELETE
The json returns from the two ajax functions seem to download complete when I check with Chrome Network inspector. However the jQuery each is not going through all items of both json files. It only goes through the first three items of the json files. So that jQuery each only builds the movie titles of the first three movies.
If I use $.when with only one function it works and returns all items.
I commented out the two areas that work as a single function.
jquery 1.11.0
Here is the javascript:
$(document).ready(function()
{
var movieCollectionUrl = 'json/movie_collection.json';
var movieFavoritesUrl = 'json/movie_favorites.json';
var movieCollectionElement = $('#collection ul');
var movieFavoritesElement = $('#favorites ul');
function getList(url)
{
return $.ajax(
{
dataType: "json",
type: "get",
url: url
});
}
function buildList(data, element)
{
$.each(data, function(i)
{
var title = data[0][i].title;
//var title = data[i].title; //this returns all items but only with a single function with $.when
var html = '<li>' + title + '</li>';
element.append(html);
});
}
function myExecute(movieCollectionData, movieFavoritesData)
{
buildList(movieCollectionData, movieCollectionElement);
buildList(movieFavoritesData, movieFavoritesElement);
}
/*
function executeSingle(movieFavoritesData)
{
buildList(movieFavoritesData, movieFavoritesElement);
}
*/
function myFail()
{
alert("FAILED TO LOAD");
}
$.when(getList(movieCollectionUrl), getList(movieFavoritesUrl)).then(myExecute, myFail);
//$.when(getList(movieFavoritesUrl)).then(executeSingle, myFail); //This one works. Using only one function here
}); //document ready
index.html
<!DOCTYPE HTML>
<head>
<title>Movies</title>
</head>
<body>
<div id="favorites">
<h2>Favorite Movies</h2>
<ul></ul>
</div>
<div id="collection">
<h2>Movie Collection</h2>
<ul></ul>
</div>
</body>
</html>
movie_collection.json
[
{
"title": "127 Hours",
"poster": "http://slurm.trakt.us/images/posters_movies/6646.1.jpg"
},
{
"title": "2012",
"poster": "http://slurm.trakt.us/images/posters_movies/463.jpg"
},
{
"title": "The 40 Year Old Virgin",
"poster": "http://slurm.trakt.us/images/posters_movies/658.1.jpg"
},
{
"title": "A Better Life",
"poster": "http://slurm.trakt.us/images/posters_movies/182444.1.jpg"
},
{
"title": "A Moment To Remember",
"poster": "http://slurm.trakt.us/images/posters_movies/162086.jpg"
}]
movie_favorites.json
[
{
"title": "A Seperation",
"poster": "http://slurm.trakt.us/images/posters_movies/176861.2.jpg"
},
{
"title": "Abraham Lincoln Vampire Hunter",
"poster": "http://slurm.trakt.us/images/posters_movies/184657.2.jpg"
},
{
"title": "The Adventures of Tin Tin",
"poster": "http://slurm.trakt.us/images/posters_movies/13066.2.jpg"
},
{
"title": "Agore",
"poster": "http://slurm.trakt.us/images/posters_movies/223.jpg"
}]
Have a look at the example of $.when in the documentation:
$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).done(function( a1, a2 ) {
// a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively.
// Each argument is an array with the following structure: [ data, statusText, jqXHR ]
var data = a1[ 0 ] + a2[ 0 ]; // a1[ 0 ] = "Whip", a2[ 0 ] = " It"
if ( /Whip It/.test( data ) ) {
alert( "We got what we came for!" );
}
});
As explained, the arguments passed to the callback function are arrays of the form [ data, statusText, jqXHR ]. The first element of the arrays contains the actual response. So you have to change your function to
function myExecute(movieCollectionData, movieFavoritesData)
{
buildList(movieCollectionData[0], movieCollectionElement);
buildList(movieFavoritesData[0], movieFavoritesElement);
}
The single case works because $.when doesn't create a new promise, it simply returns the one that $.ajax returns, so it doesn't aggregate the results of multiple promises.