Get data from JSON API and display it in HTML - javascript

I'm trying to use this minecraft server API (JSON), to show in my webpage, something like... Right now there are (players) connected.
The JSON file looks like this (external):
{
"status": true,
"players": {
"online": 534,
"max": 900
},
"cache": 1442690473 }
I want to fetch the data players (online) and display it on a html paragraph.... Using JavaScript or Jquery. I searched some solutions, using getJSON, but I couldn't make it work..
I tried using AJAX to make a request...
// AJAX Request to JSON
$.ajax({
url: "https://mcapi.ca/query/mythalium.com/players",
// Handle as Text
dataType: "text",
success: function(data) {
// Parse JSON file
var json = $.parseJSON(data);
//Store data into a variable
// Display Players
$('#players').html('Currently there are: ' + json.players.now ' users');
}
});
And then display it using:
<span id="results"></span>
Why is not working? Nothing is being showed...

You should change your AJAX success callback to:
success: function(data) {
// Parse JSON file
var json = $.parseJSON(data);
//Store data into a variable
// Display Players
$('#results').html('Currently there are: ' + json.players.online' + users');
}
The problems are you're selecting the wrong span element - #players instead of #results and you're referencing the wrong JSON property - json.players.now instead of json.players.online like in the sample response you provided.

Datatype should be JSON.
Check this video here: https://www.youtube.com/watch?v=fEYx8dQr_cQ
You should be fine then.

Related

Better way to load Large json object client side

I have a large json file (ldap) that I need to populate client side. This needs to load the nested groups and then load the members associated with that group.
My first thought was to use jquery and an Ajax call to load the json:
$(function displayGroupItems() {
$('.group-submit').click(function(event) {
$.ajax({
url:'ldap/groups',
method: 'GET',
success: function (data) {
$("#dropdown").append('<div>' + data.cn +'</div><div>' + data.ou '</div>');
}
"error": function (result) {
var response = result.responseText;
alert('Error loading: ' + response);
}
});
});
});
This method does respond with the json data. However, it won't populate the entire list in my dom elements and frankly takes to long to parse the thousands of lines we have.
Is there a better way to load a large json object?
Thank you
If you cannot control the service and the data that is returned, you might consider:
Only loading the portions you need
Use local storage to save this data and only perform the query once per session. Jquery local storage

How to parse JSON in PHP and pass it to Javascript?

This is my goal: Use twitter api to populate some slides with recent tweets without reloading the page.
The way I have it right now is this: I'm making an ajax call every few seconds from a javascript on my page to a php page. The php page sets up and authenticates a connection to Twitter and gets a responce in JSON format. Now here is my problem, the JSON responces I get are all mix and match some are arrays some are stdClass objects. Ideally I would like to pass this JSON directly to Javascript as an object, so inside Javascript I can do something like this, jsonresponce->statuses->text.
Keeping that in mind here is the same structure I described but in code:
Front End->
// JavaScript Document
function AJAXToTwitter(){
console.log("making ajax call");
$.ajax({
url: '../php/twiter-stream.php',
type: 'GET',
success: function(responce) {
$.each(responce, function(i, obj){
$(".LiveSlide1 .text").html(obj.text);
});
console.log("ajax call successful");
},
error: function(errors) {
console.log("ajax call failed");
}
})
}
$(document).ready(AJAXToTwitter);
Back End ->
//PHP Document
<?php
require "../vendor/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
$consumerKey = "iNol________________n5uVZcAB";
$consumerSecret = "o_______________________l1_J";
$accessToken = "142480736-jlOVy___________________________________tm5b7ZN";
$accessTokenSecret = "K___________________________________________wF__V";
function getToken( $apiKey, $apiKeySecret, $axToken, $axTokenSecret ) {
$connection = new TwitterOAuth( $apiKey, $apiKeySecret, $axToken, $axTokenSecret );
return $connection;
}
$connection = getToken($consumerKey, $consumerSecret, $accessToken,
$accessTokenSecret);
$urlQuery = "#WebDesign";
$search = $connection->get("search/tweets", ["q" => $urlQuery]);
echo (json_encode($search));
?>
The problem here is that I think that the responce in the case of search/tweets query is a class so json_encode produces a string and I'm unable to use $.each function. The exact error in Chrome Dev Tools Console says
Uncaught TypeError: Cannot use 'in' operator to search for '70806' in
{"statuses":[{"created_at":"Sun Jun 11 17:15:40 +0000 .......
and it goes on to spit out the whole json string that I encoded.
My question is what is the proper way to handle JSON in general when dealing with an API like this, should I just avoid using PHP and do a direct call from JavaScript? Should I manually extract every responce and encode it in a smaller, handmade json? Or is there a way to just pass the response unmodified back to javascript?
So after some trial and error I got it to work. The PHP file is the same, in the JavaScript I had to do this:
$.ajax({
url: '../php/twiter-stream.php',
type: 'GET',
success: function(responce) {
//added this line to parse the json string into JS object
var parsedJSON = JSON.parse(responce);
//now just iterating over the object to extract the info
$.each(parsedJSON.statuses, function(i, obj) {
var slideIndex = (i + 1) % 7;
$(".LiveSlide" + slideIndex+ " .text").html(obj.text);
$(".LiveSlide" + slideIndex+ " .Date").html(obj.created_at);
});
console.log("ajax call successful");
},
error: function(errors) {
console.log("ajax call failed");
}
})
This is the way I think it works, inside the PHP the TwitterOAuth::get() function retrieves a JSON string from the Twitter server, encodes it into a class. In order to pass it to javascript I needed to convert that class back to a string, that's done with json_encode(). Then inside the javascript we convert it back into an object using either JSON.parse() like I did here or you can also probably specify " dataType: 'json' " in the jQuery ajax call as #Joe Black suggested.

Extract JSON response from jquery ajax to html div

I could not retrieve data to jquery div element but i can see ajax response in firebug.
$(document).ready(function () {
$.ajax({
url: "https://m.lowes.com/CatalogServices/product/nvalue/v1_0?nValue=4294857975&maxResults=6&showURL=1&rollUpVariants=1&showUrl=true&storeNumber=0595&priceFlag=rangeBalance&showMarketingBullets=1&callback",
dataType: "jsonp",
success: function (data) {
var returnedData = JSON.parse(data);
$('#result').html(returnedData);
}
});
})
this is my response.for example my url contains data productCount:64 ,I should extract productCount from ajax success and display it in html div id result
When you parse out the JSOn data you use it like so:
var parsed_data = JSON.parse(JSON_DATA);
$('#result').html(parsed_data.key);
So if your parsed_data is somewhat like:
{name:"test",age:12}
then you use it like:
$('#result').html(parsed_data.name); //it will give you test
if you really want to print out the whole data use JSON.stringify(obj) like so:
$('#result').html(JSON.stringify(parsed_data));
In your code you are returning a json and you are trying to insert ino the div it, into the div you can only insert html code instead json.
Try to inspect the json you are returning and in case you need to insert each element into the div, do it, but don't do for all.
The html() method doesn't know what you want to assign, it only insert an html.
You need to iterate over your json data in returnData. You are not able to put json directy into html. You need to convert / parse / iterate it before. So, for example:
$.each(returnedData, function (index, value) {
// do stuff with it, e. g.:
// $('#result').html($('#result').html() + value);
});
https://jsfiddle.net/m8udusps/
The code here actually works. However it says there is a problem when it is parsing the JSON. You needed to add crossDomain: true, to allow it to actually get the results.
Having received a supposed JSON struct like:
{
"Field1": "value1",
"Field2": "value2"
}
This code gets the values of the keys (just first key in this example). Result is an alert message with Data: value1:
$.ajax({
'url' : './localurl',
'type' : 'GET',
'success' : function(data) {
alert("Data: "+data.Field1);
},
'error' : function(request,error) {
alert("Error in response: "+JSON.stringify(data));
}
});
In this case Field1 is the key received and it is directly accesible through data variable, so it is not necessary to do the JSON.parse(data) (in fact this JSON.parse produce an error)

Passing JavaScript variable between pages works fine, but DataTables is still erroring

For the LIFE of me I cannot figure this out.
Setup:
page 1: add.php
page 2: upload.php
page 3: return.php
On page one, the user uploads a spreadhseet from Excel:
<div id="return"></div>
~~~~~
$(document).ready(function (e) {
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
jsonResponse = data;
$("#return").load("return.php")
}
});
}));
});
The Excel sheet is sent over to upload.php and a JSON response is returned with the data from the cells.
echo json_encode($out);
This is exactly how it looks in console.log
jsonResponse = [
{"dateReceived":"2015-01-01","designCustomer":"MULTITEST 1","designCustomerLocation":"SUNNYVALE, CA"},
{"dateReceived":"2016-04-05","designCustomer":"MULTITEST 2","designCustomerLocation":"SUNNYVALE, CA"},
{"dateReceived":"1982-04-18","designCustomer":"MULTITEST 3","designCustomerLocation":"SUNNYVALE, CA"}
]
On success, return.php is loaded into the #return div that exists on this first page and it attempts to build a dataTable with the JSON output... :
var table = $('#ltc-table').DataTable( {
"data" : jsonResponse,
"columns" : [
{ data : 'designCustomer' },
{ data : 'designCustomerLocation' },
{ data : 'dateReceived' }
]
});
However, I get the error: Uncaught Error: DataTables warning: table id=ltc-table - Requested unknown parameter 'designCustomer' for row 0.
What I don't understand:
jsonResponse is a variable that contains JSON, and when I use console.log(jsonResponse); on return.php, I get the exact string that I pasted above (so I assume jsonResponse is a variable I can on this page if console.log is reporting it), however, datatables says it can't find the variable, as it's issuing me this error.
If, on return.php, I create new code that flat out defines jsonResponse there instead:
jsonResponse = [
{"dateReceived":"2015-01-01","designCustomer":"MULTITEST 1","designCustomerLocation":"SUNNYVALE, CA"},
{"dateReceived":"2016-04-05","designCustomer":"MULTITEST 2","designCustomerLocation":"SUNNYVALE, CA"},
{"dateReceived":"1982-04-18","designCustomer":"MULTITEST 3","designCustomerLocation":"SUNNYVALE, CA"}
];
it works.
What am I doing wrong? Is this a problem of me passing the data from one page to another page loaded into a div on that first page? This is driving me crazy.....
Your ajax reply will be returning text won't it? I don't see any "json" type specified in the ajax.
Does the data property support JSON. Or does it need javascript objects?
Looking at the docs under "ajax sourced", it implies to use the "ajax" property of the datatable function:
e.g
Ajax Sourced Datatable

get json data with jquery

Hey guys I would like to know how can I get json data with ajax call.
I tried this but seems won't work :P
First I created a JavaScript file to put inside my json data elements :
var food = [
{'name':'bread', 'price':'7,25'},
{'name':'fish', 'price':'9,00'}
];
I saved it as food.js.
Then I tried to make an ajax call from an another file, this is my code :
$(document).ready(function(){
$.ajax({
async: false,
dataType: "json",
type:'GET',
url:"food.js",
success: function(data) {
var result = data.food.name;
alert(result);
});
}});
});
Any ideas?
Thanks in advance ;)
Firstly, you have a syntax error in your example - there's too many closing braces on the $.ajax call, although I guess that's just a typo.
In your JSON, food is an array, so you need to use an indexer to get the properties of the objects within it:
success: function(data) {
var result = data.food[0].name; // = "bread"
alert(result);
});
try this
$(document).ready(function() {
$.ajax({
async: false,
dataType: "json",
type:'GET',
url:"food.js",
success: function(data) {
var result = data.food[0].name;
alert(result);
}
});
});
You need to loop through the returned data since it's an array:
$.each(data,function(i,val) {
alert(data[i].name);
});
I love how people are completely ignoring the fact that your "food.js" is not a JSON string, it's JavaScript code. This might work on old-school eval-based "JSON", but with jQuery AJAX your target file should be plain JSON. Remove the var food = from the start, and the ; from the end.
Then you can access data.food[0].name;
In this case, you are trying to get an another javascript file via ajax. For do this, you can "include" your script ( of food.js ) in your page, using Ajax GetScript ( see here ).
Your code is mucth better when you request directly json files.
You probably want to use the getJSON function in jquery : http://api.jquery.com/jquery.getjson/
$.getJSON( "food.json", function( data ) {
//here your callback
}
It will set the datatype to json and the method to GET by default.
You should also use the .json extension and not the js extension for you jsons. And format it like a proper json :
{
"food": [
{
"name": "bread",
"price": 7.25
},
{
"name": "fish",
"price": 9.00
}
],
}
You can use this website to help you format jsons : http://www.jsoneditoronline.org/
The way you are trying to call your element won't work. The data you obtain is an array. In the callback, you can try this :
console.log(data)
console.log(data.food)
console.log(data.food[0])
console.log(data.food[0].name)
console.log(data.food[0].price)
Finally, note that you formatted your numbers with a coma, this is not the way you format numbers in javascript. Use a dot, that way you'll be able to manipulate it as a number.

Categories

Resources