"Loading Data" Stuck on AMChart - javascript

Hello,
I am using the AMCharts framework to make charts from data in MySQL database. I get stuck with "Loading Data" instead of an actual chart. (http://gyazo.com/b72693484ab39e2635c0a0ab21c889a5)
And no, it's not actually loading the data. I went to launch and came back an hour later and it's yet to be loaded. When I used the data the AMCharts website provided, it worked just fine, but with my own data, no such luck.
Also, I have checked this link and it isn't answering my question. So this question shouldn't be a duplicate.
The Data :
For my data, I am using a section of Starbucks stock close prices for 100 dates in 2007. It's basically test data before I start the real part of the project. Just to get things rolling. Originally I started with 2100 rows, but when I first got the "Loading Data" message, I cut down my data to a simple 100 rows. But still, no such luck.
If you'd like to get the data I used, the way I got it, here is the R code I used.
require('quantmod')
getSymbols("SBUX")
starbucks <- data.frame(SBUX)
starbucks[,7] <- row.names(starbucks)
starbucks <- data.frame(starbucks[,c(7,6)])
row.names(starbucks) <- NULL
colnames(starbucks) <- c("Dates","Values")
starbucks <- data.frame(starbucks[1:100,])
write.table(starbucks, file="path\\to\\file\\starbucks.csv", sep=",")
Upload:
I created a new database called "charts" and under it made a table named "starbucks". There were two columns under starbucks named "Dates" (set as Date) and "Values" (set as float) each given a length of 10.
I then went to import and uploaded the CSV to this table and all imported well.
PHP
This is the code I used for the PHP side of things.
<?php
// Connect to MySQL
$link = mysql_connect( 'localhost', 'root', '' );
if ( !$link ) {
die( 'Could not connect: ' . mysql_error() );
}
// Select the data base
$db = mysql_select_db( 'charts', $link );
if ( !$db ) {
die ( 'Error selecting database \'test\' : ' . mysql_error() );
}
// Fetch the data
$query = "
SELECT *
FROM starbucks";
$result = mysql_query( $query );
// All good?
if ( !$result ) {
// Nope
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die( $message );
}
// Print out rows
$data = array();
while ( $row = mysql_fetch_assoc( $result ) ) {
$data[] = $row;
}
echo json_encode( $data );
// Close the connection
mysql_close($link);
?>
Javascript
Then there is the Javascript side of things.
var chart = AmCharts.makeChart( "chartdiv", {
"type": "serial",
"dataLoader": {
"url": "../scripts/data.php"
},
"pathToImages": "http://www.amcharts.com/lib/images/",
"categoryField": "category",
"dataDateFormat": "YYYY-MM-DD",
"startDuration": 1,
"rotate": false,
"animationDuration": 0,
"minSelectedTime": 100,
"categoryAxis": {
"parseDates": true
},
"graphs": [ {
"valueField": "value1",
"bullet": "square",
"bulletBorderColor": "#FFFFFF",
"bulletBorderThickness": 2,
"lineThickness ": 2,
"lineAlpha": 0.5
} ]
} );
HTML
Theres is of course, HTML.
<div id="chartdiv" style="width:100%; height:400px;"></div>
So back to the problem
After copy/pasting all that code, back to the actual question of this post. Why am I getting "Loading Data" instead of an actual chart?
IF there is anything else needed, let me know. I've done my best to not be vague in this question.

I'm having a similar issue. If I save the json output, remove the preceding square braces, and use this as my input, it works:
JSON that doesn't work:
[
[],
{"Key1":"Val1","Key2":"Val1"},
{"Key1":"Val2","Key2":"Val2"},
...
]
JSON that works:
[
{"Key1":"Val1","Key2":"Val1"},
{"Key1":"Val2","Key2":"Val2"},
...
]
Modify your AmChart.makeChart bit to test json:
"dataLoader": {
"url": "test.json",
"format": "json"
},
..but I don't know how to remove the preceding braces in my PHP code.. Hopefully this will get you a step closer to resolution...

I tried everything, in the end I used AJAX to retrive content and insert it in dataprovider.
jQuery.ajax({
url: "api/chartdata,
type: "GET",
contentType: 'application/json; charset=utf-8',
success: function (resultData) {
console.log(resultData);
lineChart.dataProvider = JSON.parse(resultData);
lineChart.validateData();
},
error: function (jqXHR, textStatus, errorThrown) {
}
});

finally I have solution
i don't know why amchart output "data loading..." but don't output real problem
if someone don't use browser(me is chrome) ctrl+shift+J to look up error message,
he would never found why always "data loading..."
two problem that cause "data loading" situation is confirmed
1.you open local html and browser(or amchart) block javascript to read local file
2.your file doesn't exist at all
you need something like apache to simulate amchart work at real enviroment
put html,json,lib to httpdoc

Related

geojson data loaded into leaflet map and php/html page

I currently have an html page divided into 2 columns - the right side is a Leaflet map with markers and the left hand side describes a bit more about the markers. I load the Leaflet map using geoJson data on the right side and the map and markers display fine. Now I want to take the same geoJson data and use it to fill in the left side of the php page. This way, only one file needs to be updated as we add sites.
Here is a sample of my geoJson data:
var historicalMarkers = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-77.423603, 38.865608 ]
},
"properties": {
"id": 1,
"siteName": "House14"
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [ -77.416770, 38.923650]
},
"properties": {
"id": 2,
"siteName": "Meeting House"
}
}..........
On the main php page, I simply include my geoJson file (places.js) and my geoJson/Leaflet code (map-geoJson.js).
On this main php page, I would like descriptions of each of the markers. In map-geoJson.js I am passing the data back to php via ajax like this:
// get stuff ready for php
var historicalData = [];
for (var i = 0; i < historicalMarkers.features.length; i++) {
var currentFeature = historicalMarkers.features[i];
var id = currentFeature.properties.id;
var siteName = currentFeature.properties.siteName;
console.log(id, siteName);
historicalData.push({ id: id, siteName : siteName });
}
var historicalJson = JSON.stringify(historicalData);
$.ajax({
url: location.pathname, //current page
type: 'POST',
data: historicalJson
});
The data is displayed on the console and is correct. On my php page, I want to grab the data and put it into several different divs on the page:
$phpArray = json_decode($_POST['historicalJson']);
var_dump ($phpArray); // NULL is displayed
foreach ( $phpArray as $value )
{ ?>
<div class="id">
<h4><?php echo $value['id']; ?></h4>
</div>
<div class="siteName">
<h4><?php echo $value['siteName']; ?></h4>
</div>
......
<?php } ?>
But nothing is displayed. I've also tried echo'ing
echo $value[0]->id;
echo $value['id']
Somehow I am not grabbing the data correctly in the php page and echo'ing it into the div.
Can anyone lend a suggestion? I'm sure it is something small I am missing, but I've tried many, many ways to grab the data in php.
Thanks
json_decode() returns an object (stdClass) per default. If you want to use the data as an array, you need to set the second parameter of the function to true :
$phpArray = json_decode($_POST['historicalJson'], true);
See json_decode documentation

Error in performing ajax post data and echoing those data on the console log

i was asked to perform ajax post data to the php script which will include the another script which perform sql connection to the database and get all data and convert data to json format. then the json data will be shown on the console. also i also was asked to modify the ajax to post the values such as name and the religion such as abdullah and muslim respectively.. I want to perform coding on the passwrapper to get and show data on the console.log..
in ajax.html
<html>
<head>
<script type="text/javascript" src="/Cesium-1.34/ThirdParty/jquery-1.11.3.min.js"></script>
</head>
<div id="resulte"</div>
<script type="text/javascript">
showData();
function showData()
{
$.ajax({
type: "post",
url: "passwrapper.php",
dataType: "json",
data: {
lastName: 'Abdullah',
lastReligion: 'Muslim',
},
success: function(data){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('An error occurred... Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information!');
$('#resulte').html('<p>Status Code: '+jqXHR.status+'</p><p>ErrorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p><div>'+jqXHR.responseText + '</div>');
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('errorThrown:');
console.log(errorThrown);
},
});
};
</script>
</body>
</html>
in passwrapper.php
<?php
include 'student.php';
executePass();
receivePost();
function receivePost()
{
if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"])))
{
//do nothing
}
else
{
echo '<script>console.log("Last='.$_POST["lastName"].' lastReligion='.$_POST["lastReligion"].'");</script>';
}
}
?>
in student.php
<?php
function executePass()
{
$conn = mysqli_connect('localhost','root','netwitness') or die ("Could not connect database");
$db = mysqli_select_db($conn,'abdpractice') or die ('Could not select database');
$result = mysqli_query($conn,"select * from student");
$json_array = array();
while ($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
echo json_encode($json_array);
}
?>
my question is how to show all data on the console log and also show the post data on the console.log.. please do not modify the student.php... only modify the passwrapper.php
This should output the data from both functions combined, as JSON which your ajax "success" function can log. Your existing code has an issue because one part of it tries to return JSON, and the other part tries to return a <script> block, which is not valid JSON, and also would likely not be executed by the browser anyway for security reasons.
I've also modified the two functions so they return their output to the caller as PHP variables, rather than directly echo-ing JSON strings to the browser. This makes them more re-usable, and also makes it much simpler to then combine the results into a single coherent JSON object to output to the browser.
The console.log(data); command in your existing ajax "success" function will take care of logging all the returned data to your browser console.
$studentArr = executePass();
$postArr = receivePost();
echo json_encode(array("students" => $studentArr, "postvars" => $postArr));
function receivePost()
{
if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"])))
{
//do nothing
}
else
{
return array ("lastName" => $_POST["lastName"], "lastReligion" => $_POST["lastReligion"]);
}
}
function executePass()
{
$conn = mysqli_connect('localhost','root','netwitness') or die ("Could not connect database");
$db = mysqli_select_db($conn,'abdpractice') or die ('Could not select database');
$result = mysqli_query($conn,"select * from student");
$json_array = array();
while ($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
return $json_array;
}
Now, I don't know the exact structure of your "students" data, so I can't give you an exact example of the output you'll receive, but if I were to assume that your students table had 3 simple fields - "id", "firstname", and "lastname", and there were 4 rows in the table, you would get a final JSON output something like this:
{
"students":
[
{
"id": 1,
"firstname": "firstname1",
"lastname": "lastname1"
},
{
"id": 2,
"firstname": "firstname2",
"lastname": "lastname2"
},
{
"id": 3,
"firstname": "firstname3",
"lastname": "lastname3"
},
{
"id": 4,
"firstname": "firstname4",
"lastname": "lastname4"
}
],
"postvars": {
"lastName": "Abdullah",
"lastReligion": "Muslim"
}
}
You have a JSON object with two properties. The "students" property contains an array of all the students in your table. The "postvars" property is another object containing properties matching the two POST variables you wanted to capture.

How to extract parts of response of AJAX from PHP

Need some help here, i've been searching for related issues here but nothing seems to answer my problem. Ok so here how it goes
I have a simple search function that search through my database and I used an ajax to pass the data and get back the response and I manage to do that but my problem is that I can't seem to display the response the way I wanted to.
Here's my Ajax
$.ajax({
url: url, /// defined url
type: type, ///defined type
data: data, ///defined data
success: function(response){
//here I want to display something like
$('#display').html(the name of the employee);
}
});
Here's the ajax response
{
"employee": [{
"badgeno": "123 ",
"name": "John G. Doe",
"success": true
}]
}
{
"employee": [{
"badgeno": "456 ",
"name": "Jane G. Doe",
"success": true
}
I want to get the employee Name in there and display it in my page. How exactly am I gonna do that?
Thanks in advance. I'm still a newbie BTW
Here's the PHP
$getEmp = $this->Employee_model->search_emp($employee);
$count = count($getEmp);
if($getEmp){
for ($i=0; $i < $count; $i++) {
$data['employee'][$i] = array(
'badgeno' => $getEmp[$i]->BADGENO,
'name' => $getEmp[$i]->NAME,
'success' => true
);
echo json_encode($data);
}
print_r($data);
//$this->load->view('admin/home', $data);
}
Try:
employee_name= data.employee[0].name;
$('#display').html(employee_name);
Link to fiffle:
https://jsfiddle.net/fcz53htw/
If you have more then one name, first add them to array, only then print then json_encode of the array.
Now its wont wont work because you printing twice.
Try change your php to this:
$getEmp = $this->Employee_model->search_emp($employee);
$count = count($getEmp);
if($getEmp){
for ($i=0; $i < $count; $i++) {
$data['employee'][$i] = array(
'badgeno' => $getEmp[$i]->BADGENO,
'name' => $getEmp[$i]->NAME,
'success' => true
);
//echo json_encode($data);
}
echo json_encode($data);
//$this->load->view('admin/home', $data);
}
On php you are write the results twice delete the printr only use json_encode

How to easily use the Facebook API Realtime Updates feature?

First off, apologies for posting yet another question on Facebook Realtime Updates. I have read many existing stackoverflow answers and useful articles which helped, but I still can't seem to figure out how to put everything together.
All I'm trying to do is get a trigger when there's a user or page updates (be it status/comment/like/etc.) in realtime.
I started with the Realtime Updates documentation and found these two blog posts handy:
Facebook Realtime Updates
FaceBook Real-Time Updates API Tutorial - Part I
From what I understood, to register for Realtime Updates, I need to:
Create a WWW Facebook app
Point the Facebook app to a callback_url
Add a php script at the callback_url to handle a GET request (for verification) and POST requests when Facebook calls.
Register the callback with the Graph API (v2.3/APP_ID/subscriptions)
Add the Facebook Login button to the page (including the scope/permissions needed) and perform the login action
In theory, after this point, Facebook should POST to the callback_url based on the registered object and fields.
I think I've successfully registered the callback. Here roughly the output I get(with MY_CB_URL replacing the actual URL):
{
"data": [
{
"object": "user",
"callback_url": "MY_CB_URL",
"fields": [
"statuses"
],
"active": true
},
{
"object": "page",
"callback_url": "MY_CB_URL",
"fields": [
"feed"
],
"active": true
}
]
}
The callback php script looks like so:
<?php
define('VERIFY_TOKEN', 'vToken');
$method = $_SERVER['REQUEST_METHOD'];
if ($method == 'GET' && $_GET['hub_mode'] == 'subscribe' && $_GET['hub_verify_token'] == VERIFY_TOKEN) {
echo $_GET['hub_challenge'];
} else if ($method == 'POST') {
$out = "";
try {
$updates = json_decode(file_get_contents("php://input"), true);
$out = print_r($updates, true);
error_log('updates = ' . $out);
} catch (Exception $e) {
error_log('Caught exception: '.$e->getMessage());
$out = $e->getMessage();
}
$file = './log.txt';
$current = file_get_contents($file);
$current .= $out;
file_put_contents($file, $current);
}
?>
The problem I have is I got a single POST request when I first set this up, but none after that. I don't get any errors and the API confirms the callback is correctly registered, so I am clueless on what I may be missing.
I've spotted this answer and make a call as suggested to
https://graph.facebook.com/PAGE_ID/tabs?app_id=APP_ID&access_token=PAGE_ACCESS_TOKEN
and got this response:
{
"data": [
{
"id": "PAGE_ID/tabs/likes",
"name": "Likes",
"link": "https://www.facebook.com/pages/PAGE_NAME/PAGE_ID?sk=likes",
"is_permanent": true,
"position": 2,
"is_non_connection_landing_tab": false
},
{
"id": "PAGE_ID/tabs/photos",
"image_url": "https://fbcdn-photos-c-a.akamaihd.net/hphotos-ak-xaf1/t39.2080-0/851586_10151609549247733_1069686154_n.gif",
"name": "Photos",
"link": "https://www.facebook.com/pages/PAGE_NAME/PAGE_ID?sk=photos",
"application": {
"name": "Photos",
"id": "PHOTO_ID"
},
"is_permanent": false,
"position": 1,
"is_non_connection_landing_tab": false
}
]
}
So now I'm further confused.
Making a POST request to https://graph.facebook.com/PAGE_ID/tabs is outdated – you need to use /PAGE_ID/subscribed_apps now to subscribe to updates from a page.
https://developers.facebook.com/docs/graph-api/reference/page/subscribed_apps/

jQuery getJSON Undefined Error

Alright, so I've done a bit of searching and trying with no luck. I'm hoping that someone here can point me in the right direction. I have a JSON feed that I'm working with, which is supposed to output a variety of data. Currently, it just sends back and "UNDEFINED" response for all variables. Here is the JS I'm using:
$("#loaduserdata").click(function(){
$("#userdata tbody").html("");
$.getJSON("trendFetch", function(data){
$.each(data.list, function(i, data){
var jsondata = data.action;
console.log (jsondata);
});
}
);
I'm not sure where the problem exists, because console isn't giving me any kind of errors or any reason to think that the JSON isn't formatted correctly: http://i.imgur.com/ySpdR.png
For whatever it's worth, here is the code I'm using to generate the JSON - maybe there is an issue on that end?
$curl = curl_init();
$url = 'http://api.site.com';
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url
));
$resp = curl_exec($curl);
if($resp){
echo $resp;
header("Content-Type: application/json", true);
}
else {
echo 'Error - no response!';
}
curl_close($curl);
EDIT - including JSON output:
{
"status": "ok",
"list": {
"list_id": "2gz",
"title": "Test List",
"description": "description text...",
"image": [
"http://t2.gstatic.com/images?q=tbn:ANd9GcTz6_4aV6oHsI2kgJRRoSFCTWbew5ChTeBrAmXYh4Gez2J7usm8nwMOsA",
"http://cdn.list.ly/logos/default-list-image.png"
],
"views": 0,
"item_count": 1,
"curator_count": 1,
"follower_count": 1,
"listly_url": "http://api.list.ly/list/2gz-test-list",
"items": [
{
"item": {
"name": "Link 1",
"image": "http://t2.gstatic.com/images?q=tbn:ANd9GcTz6_4aV6oHsI2kgJRRoSFCTWbew5ChTeBrAmXYh4Gez2J7usm8nwMOsA",
"note": null,
"url": null,
"likes": 0,
"dislikes": 0
}
}
],
"suggested_items": []
}
}
echo $resp;
header("Content-Type: application/json", true);
should be:
header("Content-Type: application/json", true);
echo $resp;
You need to send HTTP headers before you output any content.
Set the header before any output
header("Content-Type: application/json", true);
echo $resp;
Musa was able to solve this for me, so in case someone Googles, the problem was that I was trying to use $.each when I didn't need to. Here is the correct code in case anyone is interested:
$.getJSON("trendFetch",function(data){
var tblRow =
"<tr>"
+"<td>"+data.list.list_id+"</td>"
+"<td>"+data.list.title+"</td>"
+"<td>"+data.list.description+"</td>"
+"</tr>"
$(tblRow).appendTo("#userdata tbody");
}
);
It'd help if you provided the JSON response.
When I'm having these types of issues, I typically take a step back (in the code) and console.log() earlier. For example, console.log(data) within the function(data) {}.
I think -- from looking at the output -- that your problem is that list isn't actually a list. data.list is, in fact, an object. Therefore .each() will iterate over the individual items (like list_id, title, etc). None of these have a .action property.
I can't see any action property, so I can't make a solution suggestion. It's possible that it's within the list object -- but you're still treating it like an array (as if it's list: [{}, {}] rather than list: {}). In this case, you either need to fix the returned JSON or get rid of the $.each(), and just console.log(data.list.action).

Categories