Using JSON data in a javascript function - javascript

I am returing JSON data as a response in a web service I am writing.
I am wondering what is the best way to consume the data, returned to a Javascript function (passed as an argument).
Do I:
use eval()
use Doug Crawfords jSon parser to parse the JSON data into a Javascript object
simply use the returned data as an object literal
BTW, I am still learning Javascript, (just started reading the Definitive Guide 2 days ago) so if my question seems a bit naive or asinine - bear with me.

I would suggest a few things, first, on the web service side:
If a callback=functionName parameter is passed in the query string, then return the properly serialized JSON as the only parameter to the callback function (In this case functionName
If no callback was requested, then simply return the properly serialized JSON string. (This is helpful for when other languages consume the JSON. PHP or Ruby for instance)
Then, as far as consuming it, if you are on the same domain as the web service, you can retrieve the code and use the json2.js parser to parse it. If you are on a separate domain, use the callback parameter when requesting the data, and make sure you set up a function to handle the callback.
Simple example (Using PHP):
<?php
$callback = null;
if( isset($_REQUEST['callback']) ){
$callback = $_REQUEST['callback'];
}
$fakeData = array( 'key' => 'value');
$json = json_encode( $fakeData );
echo $callback ? "$callback($json)" : $json;
?>
JS (On different domain than the web service):
function handleCallback( data ){
alert( data.key );
}
function get_json(){
// Dynamically create the script element
var script = document.createElement('script');
script.type = "text/javascript";
script.src = "http://yourwebservice.com/service/?callback=handleCallback";
document.getElementsByTagName('head')[0].appendChild( script );
}
Calling get_json would dynamically create the request (as a script element due to cross domain restrictions. You can't use XMLHttpRequest to make cross domain requests in most browsers), and the PHP returned script would correctly call the handleCallback function when the script returns.

If you are using jQuery you can set it up so it returns as a JSON object.
http://api.jquery.com/jQuery.getJSON/

Assuming that your webservice is decorated with ScriptService attribute:
I would suggest using json2.js to handle the json clientside. It defers to native implementations when they are available.

(1). use eval()
Only if you're certain the data is clean. I'd never trust anything from an outside source.
(2). use Doug Crawfords jSon parser to parse the JSON data into a Javascript object
Best idea overall. Even jQuery uses plain old eval() to parse JSON.
(3). simply use the returned data as an object literal
When it's returned, it's just a string, not an object unless passed through one of the two aforementioned functions, or wrapped in a function ala JSONP.

Related

What do I do after I json_encode() my php array?

I am new to both php and javascript and having trouble understanding how to communicate between the two. I have a php array and I used json_encode() to turn it into json and now I just don't know what to do from there. I have just been looking around and haven't been able to find an answer of what to do from there. Do I print it? If I do print it... how do I used javascript to grab it. I can't use the php variable name since javascript doesn't understand it. I am just not grasping this concept.
The most popular way to make a Javascript script communicate with a PHP script is via Asynchronous Javascript And XML (AJAX) requests.
In AJAX requests, your javascript code calls the PHP script needed, sending to it any required parameters. Then, your PHP script should print (echo) the result (the JSON encoded array in your case), and when it does, an event gets fired in your javascript code, which you can handle accordingly.
In Javascript, there are two main ways of performing AJAX requests:
1- Using the XMLHTTPRequest object:
In this method, we are using a Javascript XMLHTTPRequest object to send the request to our PHP script, and we handle its onload event to get the response and do something with it :
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "some_url.php?param1=123");
xmlhttp.send();
xmlhttp.onload = function() {
//here the response from the PHP script is saved in the this.responseText variable
//parsing the JSON string we got into an actual array
var myArray = JSON.parse(this.responseText);
//do something with the array
}
(note that we can also handle the object's onreadystatechange, but onload is a bit simpler to handle)
2- Using a promise (fetch):
fetch("some_url.php?param1=123")
.then(function(response) {
return response.text();
})
.then(function(data)) {
var myArray = JSON.parse(data);
//do something with the array
});

How can I make HTML fill itself with the content from the JSON file using handlebars?

I need to make HTML fill itself with content from JSON file using Mustache or Handlebars.
I created two simple HTML templates for testing (using Handlebars) and filled them with content from an external JavaScript file. http://codepen.io/MaxVelichkin/pen/qNgxpB
Now I need content to lay initially in a JSON file.
I ran into two problems, but they both lie at the heart of solutions of the same main problem - creating a link between the content in the JSON file and HTML, so I decided to ask them in the same question.
How can I connect JSON and HTML? As far as I know there is a way, using AJAX, and there's a way that uses a server. AJAX is a new language for me, so I would be grateful for an explanation of how can I do it, using local HTTP server, that I created using Node.JS.
What should be the syntax in a JSON file? The script in the JSON file must be the same, as a script in JavaScript file, but then it should be processed with the help of JSON.parse function, is that correct? Or syntax in JSON file should be different?
For example, if we consider my example (link above), the code for the first template in the JSON file must be the same as in the JavaScript file, but before the last line document.getElementById('quoteData').innerHTML += quoteData;, I have to write the following line var contentJS = JSON.parse(quoteData);, and then change the name of the variable in the last line, so it will be: document.getElementById('quoteData').innerHTML += contentJS;, Is it right?
Try this:
HTML:
<!-- template-1 -->
<div id="testData"></div>
<script id="date-template" type="text/x-handlebars-template">
Date:<span> <b>{{date}}</b> </span> <br/> Time: <span><b>{{time}}</b></span>
</script>
JS:
function sendGet(callback) {
/* create an AJAX request using XMLHttpRequest*/
var xhr = new XMLHttpRequest();
/*reference json url taken from: http://www.jsontest.com/*/
/* Specify the type of request by using XMLHttpRequest "open",
here 'GET'(argument one) refers to request type
"http://date.jsontest.com/" (argument two) refers to JSON file location*/
xhr.open('GET', "http://date.jsontest.com/");
/*Using onload event handler you can check status of your request*/
xhr.onload = function () {
if (xhr.status === 200) {
callback(JSON.parse(xhr.responseText));
} else {
alert(xhr.statusText);
}
};
/*Using onerror event handler you can check error state, if your request failed to get the data*/
xhr.onerror = function () {
alert("Network Error");
};
/*send the request to server*/
xhr.send();
}
//For template-1
var dateTemplate = document.getElementById("date-template").innerHTML;
var template = Handlebars.compile(dateTemplate);
sendGet(function (response) {
document.getElementById('testData').innerHTML += template(response);
})
JSON:
JSON data format derives from JavaScript, so its more look like JavaScript objects, Douglas Crockford originally specified the JSON format, check here.
JavaScript Object Notation has set of rules.
Starts with open curly braces ( { ) and ends with enclosing curly braces ( } )
ex: {}
Inside baces you can add 'key' and its 'value' like { "title" : "hello json"}
here "title" is key and "hello json" is value of that key.
"key" should be string
"value" can be:
number
string
Boolean
array
object
Can not add JavaScript comments inside JSON (like // or /**/)
there are many online JSON validators, you can check whether your JSON is valid or not, check here.
When comes to linking JSON to js file, its more like provide an interface to get JSON data and use it in your JavaScript.
here XMLHttpRequest our interface. we usually call XMLHttpRequest API.
In the given js code, to get JSON from the server using an REST API (http://date.jsontest.com/)
for more information on REST API you can check here
from the url: http://date.jsontest.com/ you can get JSON object like below.
{
"time": "03:47:36 PM",
"milliseconds_since_epoch": 1471794456318,
"date": "08-21-2016"
}
Note: data is dynamic; values change on each request.
So by using external API you can get JSON, to use it in your JavaScript file/ code base you need to convert JSON to JavaScript object, JSON.parse( /* your JSON object is here */ ) converts JSON to js Object
`var responseObject = JSON.parse(xhr.responseText)`
by using dot(.) or bracket ([]) notation you can access JavaScript Object properties or keys; like below.
console.log(responseObject.time) //"03:47:36 PM"
console.log(responseObject["time"]) //"03:47:36 PM"
console.log(responseObject.milliseconds_since_epoch) //1471794456318
console.log(responseObject["milliseconds_since_epoch"])//1471794456318
console.log(responseObject.date) //"08-21-2016"
console.log(responseObject["date"]) //"08-21-2016"
So to link local JSON file (from your local directory) or an external API in your JavaScript file you can use "XMLHttpRequest".
'sendGet' function updatedin the above js block with comments please check.
In simple way:
create XMLHttpRequest instance
ex: var xhr = new XMLHttpRequest();
open request type
ex: xhr.open('GET', "http://date.jsontest.com/");
send "GET" request to server
ex: xhr.send();
register load event handler to hold JSON object if response has status code 200.
ex: xhr.onload = function () {
for more info check here
Know about these:
Object literal notation
difference between primitive and non-primitive data types
Existing references:
What is JSON and why would I use it?
What are the differences between JSON and JavaScript object?
Basically, JSON is a structured format recently uses which would be preferred due to some advantages via developers, Like simpler and easier structure and etc. Ajax is not a language, It's a technique that you can simply send a request to an API service and update your view partially without reloading the entire page.
So you need to make a server-client architecture. In this case all your server-side responses would be sent in JSON format as RESTful API. Also you can simply use the JSON response without any conversion or something else like an array object in JavaScript.
You can see some examples here to figure out better: JSON example

Different types of methods to read JSON

I want to load JSON when the page is loading. I found two methods but what is the difference between following two methods to read JSON.
<script type="text/javascript" src="assets/json/mainpage.json"></script>
//code for what to do with this
another method is
$.getJSON("assets/json/mainpage.json")
You did not find two different methods.
The first version is not how it works.
You can load a JavaScript object that is using object notation using a script tag, so
<script type="text/javascript" src="assets/json/mainpage.js"></script>
could contain
var myJSObject = { "key":"value" };
whereas the second method will call something that returns (static or generated) content like
{ "key":"value" }
For example
$.getJSON("assets/json/mainpage.php");
would call a server process that would do
header("content-type: application/json");
echo '{ "key":"value" }';
If the assets/json/mainpage.json returns a pure JSON, the first method is totally wrong because the tag <script> is intended to serve some sort of scripting language, and a JSON is not a scripting language. It's not impossible to see something like this method, though. If the assets/json/mainpage.json supports JSON padding, mainly knows as JSONP, the following snippet is completely valid:
<script type="text/javascript" src="assets/json/mainpage.json?callback=fn"></script>
You can keep the .json extension (or any extension you like) as long as the server returns the result as a Content-Type: javascript/text on the response header and wraps the result in the callback function. Note that the value of the callback param must be a name of a function that is globally accessible.
The second method is the same as doing an ajax call to the JSON and parsing its content. This is the one you should use, between the two. Although it's kind of useless without a callback or promise for response.
$.getJSON("assets/json/mainpage.json").done(function(res) { /* handle response */ });
Hope it helps.

Extract data from JSON API using Javascript

How do I extract the data below. I only want to print out the value number after "networkdiff" in this API.
This is the URL for the API from a different website:
http://21.luckyminers.com/index.php?page=api&action=getpoolstatus&api_key=8dba7050f9fea1e6a554bbcf4c3de5096795b253b45525c53562b72938771c41
I want the code to automatically retrieve the data from the URL above, and display the value after "networkdiff" to display on my other webpage.
Here's my code so far that I will put in my own webpage:
<HTML>
<body>
<script>
I don't know what I should put in this script part.
</script>
</body>
</html>
Below is the data the URL showed up as:
{
"getpoolstatus":{
"version":"1.0.0",
"runtime":10.684967041016,
"data":{
"pool_name":"21 Coin Pool # Luckyminers.com",
"hashrate":0,
"efficiency":97.79,
"workers":0,
"currentnetworkblock":0,
"nextnetworkblock":1,
"lastblock":40544,
"networkdiff":1,
"esttime":0,
"estshares":4096,
"timesincelast":1240429,
"nethashrate":0
}
}
}
Since the data is coming from an external domain, you can't use Ajax to get the data, unless the server enabled CORS. This doesn't seem to be the case, but it seems to support JSONP:
<script>
function processResponse(data) {
console.log(data);
}
</script>
<script src="http://21.luckyminers.com/index.php?page=api&...&callback=processResponse></script>
The callback=parseResponse makes the server return JS consisting of a function call to processResponse. How to access the information you actually want is explained in Access / process (nested) objects, arrays or JSON.
You need to include JSON.js in your web page to use JSON function in javascript. Here is the URL for download
https://github.com/douglascrockford/JSON-js
And then you can use beloe code to parse the JOSN string into javascript object.
var objectJSON = JSON.parse(jsonStr);
You can alse used stringify fucntion to the viceversa.
In which way you call the JSON?
You can call it with a callback function (working example), including it as a script:
updateResult=function()
{
var s=document.createElement('script');
s.src=domain+"/index.php?page=api&callback=showResult&action=getpoolstatus&api_key="+api_key;
document.body.appendChild(s);
}
You must have the callback defined like:
showResult=function(data)
{
document.getElementById('result').innerText=data.getpoolstatus.data.networkdiff;
}
If you call it with JQuery and get the JSON object, you can define the callback in the argument like the following example, but you must have same-origin (your script must run with the same domain (21.luckyminers.com in this case):
$.getJSON(
domain+"/index.php?page=api&action=getpoolstatus&api_key="+api_key,
function(data)
{
document.getElementById('result').innerText=data.getpoolstatus.data.networkdiff;
}
);
But in any case, be careful. Where did you get the API key? If you put it on a client-side script (like JavaScript) anybody can read the key, and with that key maybe do some damageā€¦ :S

How to use MS Ajax PageMethods to call a function on the server

I have a project that uses PageMethods to call functions on the server.
The server functions (written in C#) return the values as array of strings, without doing any kind of serialization and in the client side (from Js) the accessing of the return values is by using static variable called arguments.
I found that sometimes for some users (cases are not repro) sometimes an exception occured
"WebServiceFailedException the server method 'Foo' returned invalid data.
the 'd' property is missing from JSON."
Some searching on google I found that people are serializing the return values using DataContractJsonSerializer class and in js accessing the return value using one of the callback function
Example:
function OnRequestComplete(result,
userContext, methodName) {
var Person = eval('(' + result + ')');
alert(Person.Forename);
alert(Person.Surname); }
So is the first technique is correct? or what?
P.S:
the function on the server is defined on the default.aspx.cs file as follows:
[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
public static string[] Foo(string s);
from the client side the calling is as follows
PageMethods.Foo("value",OnSuccess);
Also all the users have the same browser version (IE8)
I don't know if it's the entire problem, but your first issue is manually serializing the return value. PageMethods and ScriptServices automatically JSON serialize their return values. Nesting two levels of JSON could definitely be throwing a wrench in the framework's client-side deserialization process (which is also happening automatically, before your eval() code).
To return an instance of your Person class, this is all you need:
public static Person GetPerson() {
Person p = new Person();
// Populate the Person object here.
return p;
}
Then, on the client-side you can work with the object's properties as expected:
function OnRequestComplete(result, userContext, methodName) {
console.log('Person name: ' + result.Forename + ' ' + result.Surname);
}
Alternatively, if you're using jQuery for other tasks and already have it on the page, you don't even need the ScriptManager and MS AJAX to call page methods. You can directly call page methods with jQuery and skip all that overhead.
Without knowing how the request is made and how the server end is coded, my answer may not be accurate.
Where is the WebMethod decorated method in your server side code? If it is an a separate class with the ScriptService attribute, and if JSON is specified while making the request, then the JSON values should have been automatically serialized and dont need to be serialized manually again. With this set up ASP.NET 3.5 wraps the response in a "d" object
Some users getting the exception might be due to the browser that they are using. If you are using jQuery, I'd specify the content type as so in the ajax request body
contentType: "application/json; charset=utf-8",
Hakeem
This is a bit funky. ASP.NET always adds the "d" to all results. So it either should work or not. Here is some background on the "d" issue:
http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/

Categories