I have a an array that has been json encoded from php
The array looks like this(called $jsonGraphData;):
[{"Type":"Category","Name":"games","TotalClicks":"162"},{"Type":"Category","Name":"apps","TotalClicks":"29"},{"Type":"Category","Name":"music","TotalClicks":"28"},{"Type":"Category","Name":"video","TotalClicks":"25"}]
I would like to use the array values in a loop within a jquery function that generates a graph. These are the hard coded values that allows the graph to work:
series: [{
name: 'games',
data: [162]
}, {
name: 'apps',
data: [29]
}, {
name: 'video',
data: [25]
}]
What I would like to do is to use jquery 'each' to loop through the array so that defining the series is dynamic this is what I am trying to achieve:
var totalClicks = $jsonGraphData; (this is the array, the alert works fine).
series: [{
$.each(totalClicks, function(index, val) {
alert('name: ' + val.Name + ' ' + 'data: ' + val.TotalClicks);
//here is where I need the format to be the same as the example above.
});
}]
I lack the knowledge of jquery syntax to achieve this and do not know what to search for on Google.
Try this code
var series = [];
$.each(totalClicks, function(index, val) {
series.push({name: val.Name, data: val.TotalClicks});
});
Or if data should still be an array with only one value in it.
var totalClicks = [{ "Type": "Category", "Name": "games", "TotalClicks": "162" }, { "Type": "Category", "Name": "apps", "TotalClicks": "29" }, { "Type": "Category", "Name": "music", "TotalClicks": "28" }, { "Type": "Category", "Name": "video", "TotalClicks": "25"}]
var series = [];
$(totalClicks).each(function (index, val) {
series.push({ "name": val.Name, "data": [val.TotalClicks] });
});
You don't need to use jQuery for looping through the regular array.
for(var obj in yourArray){
// do whatever you need with it.
alert(obj.Name + " " + obj.TotalClicks);
}
Related
when we pass static list of data like [{category":"a","data:"3"},"category":"b","data":"1"}]
then its working fine, but when we pass page url like {"url": "abc.php","format": "json"} in dataprovider section then chart not populate.
This is my code:
var chart = AmCharts.makeChart("chartdiv", {
"type": "pie",
"dataProvider":{ "
url": "abc.php",
"format": "json" },
"labelRadius": -35,
"labelText": "[[percents]]%",
"titleField": "category",
"valueField": "column-1",
"allLabels": [],
"balloon": {},
"legend": {
"enabled": true,
"align": "center",
"markerType": "circle" }
});
Any solution?
Using amCharts with "static" data
If you have "static" data, use the dataProvider setting, like this:
var chart = AmCharts.makeChart("chartdiv", {
"type": "pie",
"dataProvider": [{
"category": "a",
"data": 3
}, {
"category": "b",
"data": 1
}],
// ...
});
Using amCharts with AJAX data
If you want the data to be loaded using AJAX, one way is to make use of amCharts' Data Loader plugin.
Make sure to include it in your HTML:
<script src="amcharts/plugins/dataloader/dataloader.min.js" type="text/javascript"></script>
Leave out the dataProvider setting, and use dataLoader instead.
var chart = AmCharts.makeChart( "chartdiv", {
"type": "pie",
"dataLoader": {
"url": "abc.php",
"format": "json"
},
// ...
});
Your abc.php file should return valid JSON, like this:
[{
"category": "a",
"data": 3
}, {
"category": "b",
"data": 1
}]
You can find a complete list of options for the Data Loader plugin here: https://www.amcharts.com/kbase/using-data-loader-plugin/.
I successfully (tested) call an ajax request to a php script. This is the portion of code i need to make working:
success: function (response, status) {
$.each(response, function (i, item) {
alert(item.id);
item.id is just...nothing.
This is the generated - json_encoded array by php page:
[
{
"conto": "1"
},
{
"id": "4",
"activity_id": "50",
"path": "Testo/base.png",
"title": "Ffgf",
"descrizione": "Tttt"
},
{
"id": "8",
"activity_id": "50",
"path": "Testo/61FCFUX_IMG_0536.PNG",
"title": "Hggggg",
"descrizione": "Tgg"
}
]
What do I do wrong?
p.s: if you noticed, this is an array merge between two arrays: the first one just reports "conto" in in, the other one is a list generated by fetching elements by database.
Your first array not containing id so you are getting undefined value. Skip first array:
$.each(response, function (i, item) {
if(i==0)
{
alert(item.costo);
}
else
{
alert(item.id);
//Or better to use console
console.log(item.id);
}
});
I believe your issue is with your reference. Since your JSON object contains an array you will need to reference it with subscripts. Try changing item.id to item[i].id. That way as the each function iterates through the array, it can reference the id field in each object.
Edit: Here's working code.
$(document).ready(function (){
var source = '[{"conto":"1"},{"id":"4","activity_id":"50","path":"Testo\/base.png","title":"Ffgf","descrizione":"Tttt"},{"id":"8","activity_id":"50","path":"Testo\/61FCFUX_IMG_0536.PNG","title":"Hggggg","descrizione":"Tgg"}]';
source = JSON.parse(source);
var cellcount = length(source);
for(var i = 0; i < cellcount; i++){
console.log(source[i].id);
}
});
function length(obj) {
return Object.keys(obj).length;
}
I am using jquery and getJSON to GET a data feed constructed by PHP. The Feed displays fine when visiting the PHP page. The problem I am running into is that the JSON feed returns as multiple objects when it is GET requested in jQuery, and I don't know how to write the jQuery to display all objects and their data.
jQuery:
$(document).ready(function () {
$("#display_results").hide();
$("#searchButton").click(function (event) {
$("#display_results").show();
event.preventDefault();
search_ajax_way();
});
$("#search_results").slideUp();
$("#searchBox").keyup(function (event) {
$("#display_results").show();
});
});
function search_ajax_way() {
//var search_this=$("#searchBox").val();
//$.post("http:/url.com/folder/cl/feed.php", {city : search_this}, function(data){
//$("#display_results").html(data);
//});
var search_this = $("#searchBox").val();
$.getJSON('http://url.com/app/cl/disp_byowner_feed.php', {
city: search_this
}, function (result) {
$.each(result, function (i, r) {
console.log(r.seller);
window.title = r.title;
window.seller = r.seller;
window.loc = r.location;
(Plan on listing all keys listed in the data feed below here)
});
console.log(result);
$("#display_results").html(window.seller + < need to list all keys / values here > );
});
}
PHP (Constructs JSON Feed):
$city = 'Kanosh';
$s = "SELECT * FROM `list` WHERE `city` LIKE '%".$city."%'";
$res = $mysqli->query($s) or trigger_error($mysqli->error."[$s]");
$a = array();
while($row = $res->fetch_array(MYSQLI_BOTH)) {
$a[] = array(
'title' => $row['title'],
'price' => $row['price'],
'rooms' => $row['rooms'],
'dimensions' => $row['dimensions'],
'location' => preg_replace('pic\u00a0map', '', $row['location']),
'price' => $row['price'],
'address' => $row['address'],
'seller' => $row['seller'],
'href' => $row['href'],
'date' => $row['date']
);
}
header('Content-Type: application/json');
echo json_encode($a);
$res->free();
$mysqli->close();
Sample JSON Feed:
[{
"title": "Great Ski-In Location with Seller Financing Available ",
"price": " (Park City near the Resort) ",
"rooms": "",
"dimensions": "",
"location": "",
"address": "Crescent Road at Three Kings Dri",
"seller": "real estate - by owner",
"href": "http:\/\/saltlakecity.craigslist.org",
"date": "20140811223115"
}, {
"title": "Prospector Building 1 - Tiny Condo, Great Location - Owner Financing",
"price": "$75000",
"rooms": false,
"dimensions": "",
"location": " Prospector Square Park City Ut",
"address": "",
"seller": "real estate - by owner",
"href": "http:\/\/saltlakecity.craigslist.org",
"date": "20140811223115"
}]
Your output is an Array of JSON objects.
Fortunately, JavaScript is convenient for manipulating JSON (actually, that is why JSON was created..), and jQuery is convenient for manipulating the DOM.
To parse the result, you can just iterate through that Array, construct whatever HTML string that you need within the Array, and then insert it into the DOM using jQuery.
Here a simple example with lists :
var html = "";
for (var i = 0; i < result.length; i++) { //assuming result in the JSON array
html += '<ul id = 'house_' + i>';
for (var property in result[i]) { //read all the object properties
html += '<li>' + property + ' : ' + result[i][property] + '</li>';
}
html += '</ul>';
};
$("whatever_div").html(html);
If you only want to display some of the properties, you can read them separately and do additional formatting (for the date for example).
It is also useful to give the different HTML objects ids corresponding to what they represent.
function search_ajax_way(){
//var search_this=$("#searchBox").val();
//$.post("http:/url.com/folder/cl/feed.php", {city : search_this}, function(data){
//$("#display_results").html(data);
//});
var search_this=$("#searchBox").val();
$.getJSON('http://hooley.me/scraper/cl/disp_byowner_feed.php', { city : search_this }, function(result) {
var output = '';
$.each(result, function(i,r) {
output+= r.title + " " + r.seller
});
$("#display_results").html(output);
});
}
I have a JSON filed named items.json. I need to create a small search box in which I can input the name OR the category and perform a live search as I type. The return should be:
If I search for AXE it should display all items as I type that start with AXE.
If I search for Hygene it should list all products under that category.
So basically it should be a HTML field, with a live search field, that gets the data from a JSON file via Ajax. If I could use PHP with this too, that would be great.
[
{
"product": "132431",
"productName": "AXE Body Spray",
"categoryName": "Hygene"
},
]
If you have any ideas I would be forever grateful.
I'm really bad at this, and the more specific the better.
Both ideas on how to implement either this: http://blog.comperiosearch.com/wp-content/uploads/2012/06/instantsearch.html or jQuery Autocomplete. I've spent hours reading through the docs but I'm doing something wrong, I'm not experienced enough.
You'd better perform the search client side, and if your data is this simple, there's no need for a plugin. Here you are a working example in Javascript you can elaborate on:
var Test = {
Items : [ { "product": "132431",
"productName": "AXE Body Spray 1",
"categoryName": "Hygene"
},
{ "product": "132432",
"productName": "AXE Body Spray 2",
"categoryName": "Hygene"
},
{ "product": "132433",
"productName": "AXE Body Spray 3",
"categoryName": "Hygene"
},
{ "product": "11",
"productName": "Bacon",
"categoryName": "Food"
},
{ "product": "12",
"productName": "Eggs",
"categoryName": "Food"
},
{ "product": "9",
"productName": "Beer",
"categoryName": "Beverages"
}
],
searchProduct: function(search) {
var founds = $.grep(Test.Items, function(value, index) {
return value.productName.substring(0, search.length) == search;
});
Test.printResults(founds);
},
searchCategory: function(search) {
var founds = $.grep(Test.Items, function(value, index) {
return value.categoryName.substring(0, search.lenght) == search;
});
Test.printResults(founds);
},
printResults: function(founds) {
var html = "";
$.each(founds, function(key, item) {
html += "<option>" + item.productName + "</option>\n";
});
alert(html);
}
};
You can test it like that: Test.searchProduct("AXE"); or Test.searchCategory("Food");.
Good luck!
You can use this:http://w3schools.com/php/php_ajax_livesearch.
(or just google for:"php autocompleat ajax")
Good luck
I havent tried this before and my solution hasnt worked.
In mysql I would be able to write it using a while loop but im trying to pull the data through ajax.
Can someone help
var qString = 'country=' +country+'&continent='+continent;
$.post('/assets/inc/get-country.php', qString, function (data) {
$('#'+continent).append('<li>'+data[0].country+' '+data[0].company+'</li>');
}, "json");
The above returns in console.log's ajax response the following
[{
"continent": "Europe",
"country": "Spain",
"company": "Universidade de Vigo CITI",
"comments": "We are very satisfied with the disrupter. It's equipment is very easy to use and effective in breaking cells. I also would like to thank Constant System for for the assistance provided."
}, {
"continent": "Europe",
"country": "Spain",
"company": "IPLA",
"comments": "The Constant Systems cell disruptor has made extraction of membrane proteins from Gram positives a reproducible and efficient task in our lab."
}]
How can I get this to display as an li list on my page?
Thanks in advance
EDIT
$("#comments-tabs div.country a").click(function(e){
e.preventDefault();
var continent = $(this).parent().attr("id");
var country = $(this).attr("name");
console.log(continent+country);
var qString = 'country=' +country+'&continent='+continent;
$.post('/assets/inc/get-country.php', qString, function (data) {
for(company_nr in data){
$('#'+continent).append('<li>'+data[company_nr].country+' '+data[company_nr].company+'</li>')
}
}, "json");
});
Just loop it in javascript:
function (data)
{
for(company_nr in data)
{
$('#'+continent).append('<li>'+data[company_nr].country+' '+data[company_nr].company+'</li>')
}
}