jQuery getJSON Undefined Error - javascript

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).

Related

Unable to retrieve JSON value from PHP and Javascript

I have the following JSON below that I want to parse and get the value of the TotalRows. However, in my PHP and JavaScript it returns an error or undefined when I try to access it and I am not sure why.
For JavaScript:
var data = <?php echo json_encode($customers); ?>;
console.log(data.TotalRows)
I even placed console.log(data) and it gave me the JSON I posted and then I did console.log(data[0].TotalRows) and it give me undefined.
My code for PHP is, where $customers returns the JSON below:
$customers = $customerDB->findCustomer(5, 1);
$arr = json_decode($customers, true);
echo $arr["TotalRows"];
[
{
"TotalRows":91,
"Rows":[
{
"CompanyName":"Ana Trujillo Emparedados y helados",
"ContactName":"Ana Trujillo",
"ContactTitle":"Owner",
"City":"M\u00e9xico D.F.",
"Country":"Mexico"
},
{
"CompanyName":"Antonio Moreno Taquer\u00eda",
"ContactName":"Antonio Moreno",
"ContactTitle":"Owner",
"City":"M\u00e9xico D.F.",
"Country":"Mexico"
},
{
"CompanyName":"Around the Horn",
"ContactName":"Thomas Hardy",
"ContactTitle":"Sales Representative",
"City":"London",
"Country":"UK"
},
{
"CompanyName":"Berglunds snabbk\u00f6p",
"ContactName":"Christina Berglund",
"ContactTitle":"Order Administrator",
"City":"Lule\u00e5",
"Country":"Sweden"
},
{
"CompanyName":"Blauer See Delikatessen",
"ContactName":"Hanna Moos",
"ContactTitle":"Sales Representative",
"City":"Mannheim",
"Country":"Germany"
}
]
}
]
Its an array of object, so you would get TotalRows by
console.log(data[0].TotalRows);
Actually, I figured it out. The following worked:
var data = <?php echo json_encode($customers); ?>;
var data = JSON.parse(data);
console.log(data[0].TotalRows);

Snipcart Return JSON

Any guidance or an example of exactly what I need to do to return the information below would be great.
I'm using js, jquery & HTML
I need to add this: Content-Type header is application/json
When the request comes I need to reply with the Json below
https://docs.snipcart.com/configuration/json-crawler#validating-the-request
When Snipcart makes the request to the URL, if your response
Content-Type header is application/json, we'll use our JSON validator
instead of the HTML one.
You must return us a JSON having the following properties.
{
"id": "20",
"price": 50.00,
"url": "https://snipcart.com/products/1.json"
}
I ended up doing this in PHP and getting the values using the URL.
<?php
header('Content-Type: application/json');
$myID = $_REQUEST['scene'];
$myPrice = $_REQUEST['price'];
$data = [
"id" => $myID,
"price" => $myPrice,
"url" => "https://yoursite.com/shop/test/snipcart.php"
];
echo json_encode( $data );
?>

"Loading Data" Stuck on AMChart

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

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/

Categories