If document.getElementById("countdowntimer").innerHTML is '0' then move to next recordset, i have set div class="area" with 100% height 100% with overflow hidden in html, body, i want show recordset one by one with interval time.
<?php
$mysqli = new mysqli("localhost", "root", "", "learningbydoing");
$result = mysqli_query($mysqli, "SELECT * FROM question");
while($record = mysqli_fetch_array($result)){
echo '<div class="area">
<div class="boxquestion">
<label>'.$record['no'].'</label><br>
<label>'.$record['question'].'</label><br>
<label id="countdowntimer">'.$record['time'].'</label><br>
</div></div>';
}?>
If you were to fetch the entire recordset using fetch_all() you could use that to generate a JSON variable which you could then process easily with Javascript using an interval / timer of some sort. For instance, your PHP might look like:
<?php
$db=new mysqli( 'localhost', 'root', '', 'learningbydoing' );
$results=$db->query( 'select * from question' )->fetch_all( MYSQLI_ASSOC );
$json=json_encode( $results );
printf('
<script>
const json=%s;
</script>',
$json
);
?>
The generated json ( the following is random sports from one of my databases to emulate possible data from your database. ) could then be used as in the following snippet. Try running the snippet...
const json = [{
"id": "70",
"question": "Beach Golf",
"time": "25"
},
{
"id": "81",
"question": "Belt Wrestling",
"time": "30"
},
{
"id": "421",
"question": "Lumberjack",
"time": "15"
},
{
"id": "144",
"question": "Chilean Rodeo",
"time": "10"
},
{
"id": "706",
"question": "Swamp Football",
"time": "40"
},
{
"id": "570",
"question": "Rollball",
"time": "1"
},
{
"id": "136",
"question": "Canopy Piloting",
"time": "9"
},
{
"id": "14",
"question": "Air Racing",
"time": "29"
},
{
"id": "402",
"question": "Kurash",
"time": "20"
},
{
"id": "465",
"question": "Northern Praying Mantis",
"time": "16"
},
{
"id": "53",
"question": "Ball Hockey",
"time": "3"
},
{
"id": "156",
"question": "Corkball",
"time": "13"
},
{
"id": "478",
"question": "Outrigger Canoeing",
"time": "7"
},
{
"id": "310",
"question": "Harness Racing",
"time": "9"
},
{
"id": "515",
"question": "Playboating",
"time": "8"
},
{
"id": "500",
"question": "Patball",
"time": "9"
},
{
"id": "202",
"question": "Dog Sledding",
"time": "14"
},
{
"id": "510",
"question": "Pigeon Racing",
"time": "16"
},
{
"id": "697",
"question": "Strongman",
"time": "18"
},
{
"id": "691",
"question": "Stock Car Racing",
"time": "19"
},
{
"id": "522",
"question": "Pommel Horse",
"time": "3"
},
{
"id": "237",
"question": "Field Hockey",
"time": "9"
},
{
"id": "312",
"question": "Heptathlon",
"time": "18"
},
{
"id": "324",
"question": "Horse Racing",
"time": "23"
},
{
"id": "7",
"question": "Aerobatics",
"time": "18"
}
];
const number = document.querySelector('i[data-name="number"]');
const question = document.querySelector('i[data-name="question"]');
const countdown = document.querySelector('i[data-name="countdown"]');
number.textContent = json[0].id;
question.textContent = json[0].question;
let _time = json[0].time;
(function(time) {
let t = NaN;
let i = 0;
(function() {
time--;
if (json[i]) {
countdown.textContent = time + 1;
number.textContent = json[i].id;
question.textContent = json[i].question;
}
t = setTimeout(arguments.callee, 1000);
if (time <= 0) {
if (i > Object.keys(json).length) {
clearTimeout(t);
number.textContent = '-';
question.textContent = 'Finished';
countdown.textContent = '-';
return false;
}
i++;
if (json[i]) time = json[i].time;
}
})();
})(_time);
[data-name] {
padding: 1rem;
margin: 1rem 0;
display: inline-block;
}
[data-name='number'] {
color: white;
background: green;
}
[data-name='question'] {
color: blue;
background: gold;
min-width: 15rem
}
[data-name='countdown'] {
color: white;
background: red;
}
<div class='area'>
<div class='boxquestion'>
<i data-name='number'></i>
<i data-name='question'></i>
<i data-name='countdown'></i>
</div>
</div>
example:
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<style>
[data-name]{padding:1rem;margin:1rem 0;display:inline-block;}
[data-name='number']{color:white;background:green;}
[data-name='question']{color:blue;background:gold;min-width:15rem}
[data-name='countdown']{color:white;background:red;}
</style>
<?php
$db=new mysqli('localhost', 'root', '', 'learningbydoing');
$results=$db->query( 'select * from question' )->fetch_all( MYSQLI_ASSOC );
$json=json_encode( $results );
printf('
<script>
const json=%s;
</script>',
$json
);
?>
</head>
<body>
<div class='area'>
<div class='boxquestion'>
<i data-name='number'></i>
<i data-name='question'></i>
<i data-name='countdown'></i>
</div>
</div>
<script>
const number=document.querySelector('i[data-name="number"]');
const question=document.querySelector('i[data-name="question"]');
const countdown=document.querySelector('i[data-name="countdown"]');
number.textContent=json[0].id;
question.textContent=json[0].question;
let _time=json[0].time;
(function( time ){
let t=NaN;
let i=0;
(function(){
time--;
if( json[i] ){
countdown.textContent=time + 1;
number.textContent=json[i].id;
question.textContent=json[i].question;
}
t=setTimeout( arguments.callee, 1000 );
if( time <= 0 ){
if( i > Object.keys( json ).length ){
clearTimeout( t );
number.textContent='-';
question.textContent='Finished';
countdown.textContent='-';
return false;
}
i++;
if( json[ i ] ) time=json[ i ].time;
}
})();
})( _time );
</script>
</body>
</html>
<?php
$mysqli = new mysqli("localhost", "root", "", "learningbydoing");
$result = mysqli_query($mysqli, "SELECT * FROM question");
while($record = mysqli_fetch_array($result)){
if( $record['time'] > 0 ){ // assuming the column is actually a number
echo '<div class="area">
<div class="boxquestion">
<label>'.$record['no'].'</label><br>
<label>'.$record['question'].'</label><br>
<label id="countdowntimer">'.$record['time'].'</label><br>
</div></div>';
}
}?>
Related
This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 2 years ago.
I want to loop through the allData and search if the id matches 12345,
I want to remove the Offer Object and insert the newOffer Object
$(document).ready(function () {
var newOfferToInsert = {
"id": "12345",
"name": "ssfd Offer"
}
var idToSearch = '12345'
var allData = [{
"id": {
"Street": "555 92nd St S",
"id": "12345"
},
"Offer": {
"id": "12345"
}
}, {
"id": {
"Street": "666 DFTYY",
"id": "345"
},
"Offer": {
"id": "345"
}
}];
});
https://jsfiddle.net/9avwsm1p/
You can do it like this:
allData.forEach(function(cartObj) {
if(cartObj.id.id === idToSearch){
cartObj.Offer = newOfferToInsert;
}
});
const newOfferToInsert = {
"id": "12345",
"name": "ssfd Offer"
}
const idToSearch = '12345'
const allData = [{
"id": {
"Street": "555 92nd St S",
"id": "12345"
},
"Offer": {
"id": "12345"
}
}, {
"id": {
"Street": "666 DFTYY",
"id": "345"
},
"Offer": {
"id": "345"
}
}];
console.log(replaceOffer(allData, idToSearch, newOfferToInsert))
function replaceOffer(allData, idToSearch, newOfferToInsert) {
return allData.map(element => {
if (element.Offer.id === idToSearch) {
element.Offer = newOfferToInsert
}
return element
})
}
var newOfferToInsert = {
"id": "12345",
"name": "ssfd Offer"
}
var idToSearch = '12345'
var allData = [{
"id": {
"Street": "555 92nd St S",
"id": "12345"
},
"Offer": {
"id": "12345"
}
}, {
"id": {
"Street": "666 DFTYY",
"id": "345"
},
"Offer": {
"id": "345"
}
}];
allData.forEach((obj)=>{
if(obj.Offer.id===idToSearch)
{
obj.Offer=newOfferToInsert
}
})
console.log(allData)
Aim: On click of a next/previous button the label changes to the next/previous category of that current slide. Category Slider Wireframe of what I want to achieve.
Background: I previously attempted this 'Obtain Next/Previous Value from Object'. However I had issues where I had to have this in my ng-repeat and even though the data I wanted was produced it did not function with the bxSlider plugin (I could not duplicate the arrows). Therefore I need to maintain these arrows and labels outside of my ng-repeat.
Next Solution: I realised potentially the best solution for this would be to keep this outside the ng-repeat. In order to do so I believe I would have to variable attached to the scope that will increment/decrement. So the appropriate Next/Previous buttons can be viewed.
I naively attempted ng-click="activeCat = activeCat + 1" however that obviously just added ones to the end of the category.
Any help is greatly appreciated :)
HTML
<!-- Next & Previous Buttons -->
<div class="btn-nextprev">
<div class="next-container">
<a href="" class="btn btn-next" id="next" ng-click="nextCat = nextCat + 1">
{{ employees[getNextCategoryIndex($index)].category }} {{nextCat}}
</a>
</div>
<div class="prev-container">
<a href="" class="btn btn-prev" id="prev">
{{ employees[getPrevCategoryIndex($index)].category }} {{prevCat}}
</a>
</div>
</div>
<!-- END Next & Previous Buttons -->
Controller:
var personControllers = angular.module('personControllers', ['ngAnimate']);
//PersonSearch Controller
personControllers.controller('PersonList', ['$scope', '$http',
function($scope, $http) {
$http.get('../static/scripts/data2.json').
success(function(data) {
console.log("JSON file loaded");
console.log(data);
$scope.employees = data;
$scope.activeCat = data[0].category;
$scope.nextCat = data[0 + 1].category;
//$scope.prevCat = data[0 - 1].category;
}).
error(function(){
console.log("JSON file NOT loaded");
});
}]);
JSON:
[
{
"category": "Technology",
"shortname": "tech",
"icon": "fa-desktop",
"cat_id": 0,
"cards": [
{
"id": "card-1",
"name": "George Sofroniou",
"shortname": "G_Sof",
"age": "23",
"company": "Pirean Ltd.",
"role": "Graduate UI Developer"
},
{
"id": "card-2",
"name": "Steve Jobs",
"shortname": "S_Jobs",
"age": "56 (Died)",
"company": "Apple Inc.",
"role": "Former CEO"
},
]
},
{
"category": "Motors",
"shortname": "mot",
"icon": "fa-car",
"cat_id": 1,
"cards": [
{
"id": "card-1",
"name": "Elon Musk",
"shortname": "E_Musk",
"age": "43",
"company": "Tesla Motors",
"role": "CEO"
},
{
"id": "card-2",
"name": "Henry Ford",
"shortname": "H_Ford",
"age": "83 (Died)",
"company": "Ford Motor Company",
"role": "Founder"
}
]
},
{
"category": "Football",
"shortname": "foot",
"icon": "fa-futbol-o",
"cat_id": 2,
"cards": [
{
"id": "card-1",
"name": "Sir Alex Ferguson",
"shortname": "A_Fer",
"age": "73",
"company": "N/A",
"role": "Retired"
},
{
"id": "card-2",
"name": "Bobby Moore",
"shortname": "B_Moor",
"age": "51 (Died)",
"company": "N/A",
"role": "Footballer"
}
]
},
{
"category": "Law",
"shortname": "law",
"icon": "fa-gavel",
"cat_id": 3,
"cards": [
{
"id": "card-1",
"name": "Harvey Specter",
"shortname": "H_Spec",
"age": "43",
"company": "Pearson Specter Litt",
"role": "Name Partner"
},
{
"id": "card-2",
"name": "Saul Goodman (James Morgan McGill)",
"shortname": "S_Good",
"age": "48",
"company": "Better Call Saul",
"role": "Criminal Defence Attorney"
}
]
}
]
You could just store each objects data in an array, and have the array index increment or decrement depending on which button they press.
var i = 0
$scope.dataArray = [];
//sift the data into the array
$scope.next = function () {
i++
};
$scope.prev = function () {
i--
};
Here is an example:
http://plnkr.co/edit/SVXhxvwJqnO8Uarjkxx2?p=preview
GSof Edit:
//Next & Previous Button Category Label
$scope.i = 0;
$scope.j = $scope.employees.length;
$scope.nextCat = $scope.i + 1;
$scope.prevCat = $scope.j - 1;
$scope.getNext = function(){
//console.log($scope.nextCat);
$scope.nextCat++;
if( $scope.nextCat >= $scope.employees.length ){
$scope.nextCat = 0;
}
$scope.prevCat++;
if( $scope.prevCat >= $scope.employees.length ){
$scope.prevCat = 0;
}
};
$scope.getPrev = function(){
//console.log($scope.nextCat);
$scope.prevCat--;
if( $scope.prevCat < 0 ){
$scope.prevCat = $scope.employees.length - 1;
}
$scope.nextCat--;
if( $scope.nextCat < 0 ){
$scope.nextCat = $scope.employees.length - 1;
}
};
This if statement will insure that when the end of the array is reached the item will return to the beginning. The next and previous values are now in sync with each other so on press of the next button both the next and previous labels update and vice versa.
Again thank you for help.
On ng-click call function and in that function do the increment.
Like this
<a href="" class="btn btn-next" id="next" ng-click="increment()">
and in controllerjs
$scope.increment=function(){
$scope.flag=false;
angular.forEach($scope.employees,function(employe){
if(flag){
$scope.nextCat = employe.category;
return;
}
if($scope.nextCat === employe.category){
flag=true;
}
});
}
I'm using the foursquare venues API to populate a select menu and list in my web app. I'd like to sort the venues alphabetically by name.
Here is a JSON response from the foursquare API, which has some venues:
[ { "reasons": { "count": 1, "items": [ { "summary": "This spot is popular on foursquare", "type": "general", "reasonName": "globalInteractionReason" } ] }, "venue": { "id": "4c6ee03fb5a5236a74744b52", "name": "Peninsular Paper Dam", "contact": {}, "location": { "address": "1265 Leforge Rd", "crossStreet": "at Huron River Rd", "lat": 42.256628, "lng": -83.623933, "distance": 892, "postalCode": "48198", "city": "Ypsilanti", "state": "MI", "country": "United States", "cc": "US" }, "categories": [ { "id": "4bf58dd8d48988d165941735", "name": "Scenic Lookout", "pluralName": "Scenic Lookouts", "shortName": "Scenic Lookout", "icon": { "prefix": "https://foursquare.com/img/categories_v2/parks_outdoors/sceniclookout_", "suffix": ".png" }, "primary": true } ], "verified": false, "stats": { "checkinsCount": 31, "usersCount": 12, "tipCount": 0 }, "likes": { "count": 0, "groups": [] }, "specials": { "count": 0, "items": [] }, "photos": { "count": 2, "groups": [] } } }, { "reasons": { "count": 1, "items": [ { "summary": "This spot is popular on foursquare", "type": "general", "reasonName": "globalInteractionReason" } ] }, "venue": { "id": "4ba58202f964a520cb0d39e3", "name": "Benito's Pizza", "contact": { "phone": "7349610707", "formattedPhone": "(734) 961-0707" }, "location": { "address": "1088 N Huron River Dr", "lat": 42.256532, "lng": -83.629082, "distance": 1035, "postalCode": "48197", "city": "Ypsilanti", "state": "MI", "country": "United States", "cc": "US" }, "categories": [ { "id": "4bf58dd8d48988d1ca941735", "name": "Pizza Place", "pluralName": "Pizza Places", "shortName": "Pizza", "icon": { "prefix": "https://foursquare.com/img/categories_v2/food/pizza_", "suffix": ".png" }, "primary": true } ], "verified": false, "stats": { "checkinsCount": 50, "usersCount": 34, "tipCount": 0 }, "url": "http://www.benitospizza.com/", "likes": { "count": 0, "groups": [] }, "menu": { "type": "foodAndBeverage", "url": "https://foursquare.com/v/benitos-pizza/4ba58202f964a520cb0d39e3/menu", "mobileUrl": "https://foursquare.com/v/4ba58202f964a520cb0d39e3/device_menu" }, "specials": { "count": 0, "items": [] }, "photos": { "count": 0, "groups": [] } } } ]
I'm able to parse this response with this code:
for (var i = 0; i < venues.length; i++) {
name = venues[i]['venue']['name'];
category = venues[i]['venue']['categories'][0]['name'];
icon = venues[i]['venue']['categories'][0]['icon']['prefix'];
icon = icon.slice(0, -1); // remove trailing "_" character
icon = icon + venues[i]['venue']['categories'][0]['icon']['suffix'];
address = venues[i]['venue']['location']['address'];
city = venues[i]['venue']['location']['city'];
state = venues[i]['venue']['location']['state'];
distance_meters = venues[i]['venue']['location']['distance'];
distance_miles = distance_meters / 1609.34;
distance_miles = Math.round(distance_miles*100)/100;
x = 1; // in the product use i for index below
HTMLmarkupList += "<li><img src=\"" + icon + "\" class=\"ui-li-thumb\" style=\"margin: 23px 10px\" onerror=\"ImgError(this);\">" + "<h3 style=\"margin-left: -40px\">" + name + "</h3><p style=\"margin-left: -40px\">" + category + "</p><p style=\"margin-left: -40px\">" + address + ", " + city + ", " + state + "</p><p style=\"margin-left: -40px\">" + distance_miles + " miles from you.</p></li>";
HTMLmarkupSelect += "<option value\"" + i + "\">" + name + "</option>";
}
Right now, the value of the select is just i, but as I'll be needing to store other variables along with the name in my database I may update the value in each select option to include things like the address, city, state, etc.... I mention this because if I was only using the name in the select, I could just build an array of names and use the javascript sort method.
Can anyone help with how to sort the venues alphabetically by name? Thanks.
Information:
http://www.w3schools.com/jsref/jsref_sort.asp
Example:
venues.sort(function(a,b){
if(a.venue.name == b.venue.name) return 0;
return (a.venue.name < b.venue.name) ? -1 : 1;
});
May be you can help me with my task. I have a JSON string:
{
"chats":[
{"id":"1","time":"13:02", "from_id":"2692","text":"1","to_id":"62"},
{"id":"2","time":"13:48", "from_id":"62","text":"Hello!","to_id":"2692"},
{"id":"12","time":"15:47", "from_id":"2692","text":"3","to_id":"62"},
{"id":"13","time":"15:48", "from_id":"62","text":"4","to_id":"2692"},
{"id":"30","time":"08:57", "from_id":"2692","text":"To me","to_id":"62"},
{"id":"31","time":"09:28", "from_id":"66","text":"From user1","to_id":"2692"},
{"id":"32","time":"09:29", "from_id":"66","text":"From user1","to_id":"2692"},
{"id":"32","time":"09:29", "from_id":"2692","text":"From user1","to_id":"66"}
],
"lastid": "32"
}
var my_id = 2692 /*My chats*/
/*Success JSON request below*/
onSuccess: function(m){
var messages = [];
var chanels = [];
var chanels_u = [];
for(var i=0; i<m.chats.length;i++){
if (my_id != '' && m.chats[i].from_id != parseInt(my_id)){
chanels.push(m.chats[i].from_id);
}
}
chanels_u = chanels.unique(); /*We get id's: 62,66*/
}
My Question:
How can I create a new arrays dynamically (2 for this example for: 62 and 66) and push messages?
To 1 (62):
{"id":"1","time":"13:02", "from_id":"2692","text":"1","to_id":"62"},
{"id":"2","time":"13:48", "from_id":"62","text":"Hello!","to_id":"2692"},
{"id":"12","time":"15:47", "from_id":"2692","text":"3","to_id":"62"},
{"id":"13","time":"15:48", "from_id":"62","text":"4","to_id":"2692"},
{"id":"30","time":"08:57", "from_id":"2692","text":"To me","to_id":"62"}
To 2 (66):
{"id":"31","time":"09:28", "from_id":"66","text":"From user1","to_id":"2692"},
{"id":"32","time":"09:29", "from_id":"66","text":"From user1","to_id":"2692"},
{"id":"32","time":"09:29", "from_id":"2692","text":"From user1","to_id":"66"}
Thanks!
You are already identifying your chat ID and pushing it into the chanels array in your code:
if (my_id != '' && m.chats[i].from_id != parseInt(my_id)){
chanels.push(m.chats[i].from_id);
}
You are also identifying unique IDs in your code:
chanels_u = chanels.unique();
All you need to do is locate your chats from the JSON object by comparing them to the IDs in chanels_u and if there's a match, push the text field to the messages array. This is should be close to what you require:
for(var i=0; i<m.chats.length;i++){
for(var j=0; j<chanels_u.length;j++){
if (my_id !== '' && m.chats[i].from_id === chanels_u[j]){
messages.push(m.chats[i].text);
}
}
}
this will do what you want, i believe - create a new object with keys of the to_id and from_id in a way that allows you to loop them whichever way you want. it would probably make more sense to have a toUser and fromUser objects that you can loop independently and cross reference as you build the replies but it's trivial to do so.
var chats = {
"chats":[
{"id":"1","time":"13:02", "from_id":"2692","text":"1","to_id":"62"},
{"id":"2","time":"13:48", "from_id":"62","text":"Hello!","to_id":"2692"},
{"id":"12","time":"15:47", "from_id":"2692","text":"3","to_id":"62"},
{"id":"13","time":"15:48", "from_id":"62","text":"4","to_id":"2692"},
{"id":"30","time":"08:57", "from_id":"2692","text":"To me","to_id":"62"},
{"id":"31","time":"09:28", "from_id":"66","text":"From user1","to_id":"2692"},
{"id":"32","time":"09:29", "from_id":"66","text":"From user1","to_id":"2692"},
{"id":"32","time":"09:29", "from_id":"2692","text":"From user1","to_id":"66"}
],
"lastid": "32"
};
var newchats = {}, my_id = 2692;
chats.chats.each(function(chat) {
if (!chat.id || !chat.id.length || chat.from_id == my_id)
return;
newchats["from" + chat.from_id] = newchats["from" + chat.from_id] || [];
newchats["from" + chat.from_id].push(chat);
newchats["to" + chat.to_id] = newchats["to" + chat.to_id] || [];
newchats["to" + chat.to_id].push(chat);
});
console.log(newchats, JSON.encode(newchats));
see on jsfiddle http://jsfiddle.net/dimitar/7j2SN/, outputs:
{
"from62": [{
"id": "2",
"time": "13:48",
"from_id": "62",
"text": "Hello!",
"to_id": "2692"},
{
"id": "13",
"time": "15:48",
"from_id": "62",
"text": "4",
"to_id": "2692"}],
"to2692": [{
"id": "2",
"time": "13:48",
"from_id": "62",
"text": "Hello!",
"to_id": "2692"},
{
"id": "13",
"time": "15:48",
"from_id": "62",
"text": "4",
"to_id": "2692"},
{
"id": "31",
"time": "09:28",
"from_id": "66",
"text": "From user1",
"to_id": "2692"},
{
"id": "32",
"time": "09:29",
"from_id": "66",
"text": "From user1",
"to_id": "2692"}],
"from66": [{
"id": "31",
"time": "09:28",
"from_id": "66",
"text": "From user1",
"to_id": "2692"},
{
"id": "32",
"time": "09:29",
"from_id": "66",
"text": "From user1",
"to_id": "2692"}]
}
I guess, JSON is invalid. You missed to close the JSON properly.
{
"chats": [
{
"id": "1",
"time": "13:02",
"from_id": "2692",
"text": "1",
"to_id": "62"
},
{
"id": "2",
"time": "13:48",
"from_id": "62",
"text": "Hello!",
"to_id": "2692"
},
{
"id": "12",
"time": "15:47",
"from_id": "2692",
"text": "3",
"to_id": "62"
},
{
"id": "13",
"time": "15:48",
"from_id": "62",
"text": "4",
"to_id": "2692"
},
{
"id": "30",
"time": "08:57",
"from_id": "2692",
"text": "To me",
"to_id": "62"
},
{
"id": "31",
"time": "09:28",
"from_id": "66",
"text": "From user1",
"to_id": "2692"
},
{
"id": "32",
"time": "09:29",
"from_id": "66",
"text": "From user1",
"to_id": "2692"
}
]
}
Use JSONLINT to validate your data. You can update(get/set) this array dynamically as you wish.
var msgBox={"chats":[]};
var msg={"id":1,"time":(new Date()).getTime(),"from_id":"","text":"","to_id":""};
var info={ // whole JSON data }
var chats=info['chats'];
for(m in chats){
console.log(chats[m].text) // will display the text
console.log(chats[m].time) // will display the time of chat
chat[m].to_id=32424; // you can modify the to_id value
}
You can make chanels and object instead of array.
onSuccess: function(m){
var messages = [];
var chanels = {};
var chanels_u = [];
for(var i=0; i<m.chats.length;i++){
if (my_id != '' && m.chats[i].from_id != parseInt(my_id)){
var fromID = m.chats[i].from_id;
if(!chanels[fromID]){
chanels[fromID] = [];
}
chanels[fromID].push(m.chats[i]);
}
}
//chanels_u = chanels.unique(); /*We get id's: 62,66*/
}
From the below JSON, how can I retrieve title from the note and notes using a for loop and ajax to retrieve?
{
"infos": {
"info": [
{
"startYear": "1900",
"endYear": "1930",
"timeZoneDesc": "daweerrewereopreproewropewredfkfdufssfsfsfsfrerewrBlahhhhh..",
"timeZoneID": "1",
"note": {
"notes": [
{
"id": "1",
"title": "Mmm"
},
{
"id": "2",
"title": "Wmm"
},
{
"id": "3",
"title": "Smm"
}
]
},
"links": [
{ "id": "1", "title": "Red House", "url": "http://infopedia.nl.sg/articles/SIP_611_2004-12-24.html" },
{ "id": "2", "title": "Joo Chiat", "url": "http://www.the-inncrowd.com/joochiat.htm" },
{ "id": "3", "title": "Bake", "url": "https://thelongnwindingroad.wordpress.com/tag/red-house-bakery" }
]
}
I tried out the code below but it doesn't work - it either says:
is null
not an object
length is null
r not an object
var detail = eval(xmlhttprequest.responseText)
var rss = detail.infos.info
for(var i = 0; i<rss.length; i++)
startyear += rss[i].startyear
Use
for (i = 0; i < 3; i++) {
alert(JSON.infos.info[0].note.notes[i].title);
}
TRY IT HERE: JSFIDDLE WORKING EXAMPLE
BTW your JSON is not valid. Use this JSON:
var JSON = {
"infos": {
"info": [
{
"startYear": "1900",
"endYear": "1930",
"timeZoneDesc": "daweerrewereopreproewropewredfkfdufssfsfsfsfrerewrBlahhhhh..",
"timeZoneID": "1",
"note": {
"notes": [
{
"id": "1",
"title": "Mmm"
},
{
"id": "2",
"title": "Wmm"
},
{
"id": "3",
"title": "Smm"
}
]
},
"links": [
{
"id": "1",
"title": "Red House",
"url": "http://infopedia.nl.sg/articles/SIP_611_2004-12-24.html"
},
{
"id": "2",
"title": "Joo Chiat",
"url": "http://www.the-inncrowd.com/joochiat.htm"
},
{
"id": "3",
"title": "Bake",
"url": "https://thelongnwindingroad.wordpress.com/tag/red-house-bakery"
}
]
}
]
}
}
EDIT:
Here is what you want:
var infoLength= JSON.infos.info.length;
for (infoIndex = 0; infoIndex < infoLength; infoIndex++) {
var notesLength= JSON.infos.info[infoIndex].note.notes.length;
for (noteIndex = 0; noteIndex < notesLength; noteIndex++) {
alert(JSON.infos.info[infoIndex].note.notes[noteIndex].title);
}
}
Putting your json into an var called obj, use the following:
obj.infos.info[0].note.notes[0].title
http://jsfiddle.net/Znq34/
Well the "path" to the JSON notes array-like object is:
json.infos.info[0].note.notes;
So you could do something like:
var notes = json.infos.info[0].note.notes;
var titles = [];
for (var i = 0, len = notes.length; i < len; i++)
{
titles.push(notes[i].title);
}
alert('titles is: ' + titles.join(', '));
Fiddle: http://jsfiddle.net/garreh/uDxqD/
Are you using jQuery? ;-)
// Assuming your using "success" in ajax response
success: function(json)
{
var titles = $(json.infos.info[0].note.notes).map(function() {
return this.title;
}).get();
alert(titles.join(', '));
}
First count the length of notes
var len = jsonobject.infos.info.note.notes.length;
Then loops through and get
var title = jsonobject.infos.info.note.notes[i].title;