Grabbing JSON data properly - javascript

So I'm working on jQuery for the first time. When I use this:
var data = $.getJSON("https://hackernews.firebaseio.com/v0/item/14279870.json", function(data) {
data = JSON.stringify(data)
});
console.log(data);
I get this guy in the log: object view
But if I try to log data.text, data.responseText, or anything like that I just get undefined. How do I get the data?

The problem is that console.log executes before data = JSON.stringify(data) because $.getJSON call is asynchronous.
That means that what you see in the console is not the object that you get inside your success callback.
To get a proper representation of your data object (after the server call), put the console log inside the callback function:
$.getJSON("https://hackernews.firebaseio.com/v0/item/14279870.json", function(data) {
console.log(data);
data = JSON.stringify(data)
console.log(data);
});
Live example with a sample JSON file (your URL returns null):
$.getJSON("http://echo.jsontest.com/key/value/one/two", function(data) {
console.log("JSON: ", data);
data = JSON.stringify(data)
console.log("Stringified: ", data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related

Correct way to handle the data from a post with JQuery

I have an issue converting the data coming from a server with post with JQuery because of the data received from the server is a "type of" [object Object]
Notes: the data received from the server is supposed to be a JSON
I tried to convert directly the response from the server to JSON I have an error, thus I tried first to convert the response into a string and then into JSON but this fails as well, the code is the following:
// THE FOLLOWING CODE IS FROM A HTML PAGE
$('#login-form').submit(function(event){
event.preventDefault();
// Get some values from elements on the page:
let $form = $(this),
email = $form.find("input[name='email']").val(),
password = $form.find("input[name='password']").val(),
url = $form.attr('action');
// Send the data using post
let posting = $.post(url, {useremail: email, userpassword: password},
function(data, status, xhr){ // catch response from the server
let responseString = JSON.stringify(data); // convert response from [object Object] to String
let responseJSON = JSON.parse(responseString); // convert response string to JSON type
});
});
/// THE FOLLOWING CODE IS FROM THE SERVER SIDE
res.json({
status: 'some status',
message: 'some message'
});
The expected results are that the data is converted to a JSON dictionary
Your server is already sending the response in JSON, so on the frontend (Client side) there is no need to JSON.stringify() response and again using JSON.parse() on it.
Try to log data, you should be able to access the status and message directly using the data response.
So try removing the following line from your .js file
let responseString = JSON.stringify(data);
Instead, try
console.log(data.status);
console.log(data.message);
Check if you get the appropriate log on the browser console.
Use JSON.parse() so your code will look like this:
let responseJSON;
$('#login-form').submit(function(event){
event.preventDefault();
// Get some values from elements on the page:
let $form = $(this),
email = $form.find("input[name='email']").val(),
password = $form.find("input[name='password']").val(),
url = $form.attr('action');
// Send the data using post
let posting = $.post(url, {useremail: email, userpassword: password},
function(data, status, xhr){ // catch response from the server
let responseString = JSON.stringify(data); // convert response from [object Object] to String
responseJSON = JSON.parse(responseString); // convert response string to JSON type
});
});
console.log(responseJSON.message);
if(responseJSON.hasOwnProperty('message') {
console.log(responseJSON['message']);
} else {
console.log("'message' not found in response");
}
Both will work. And if by "Dictionary" you mean key-value pairs with unique keys, JSON object keys should always be unique. You can check whether a key exists in an object using the hasOwnProperty() method as described above.
As long as your server is returning valid JSON content, the data returned by jQuery POST will be a JavaScript JSON object you don't need to process, for example:
$.post(url, data, function(data, status, xhr) {
// data is a JSON object with the server response
let id = data.id;
alert("Your new post was saved with id: " + id);
});
Note how I access the data directly.
Please check this simple jsfiddle I created for a quick demo; it uses a dummy API to make a POST request:
https://jsfiddle.net/danyalejandro/x46wzjdy/11/

How can I capture the Array object returned by an api call through HTTP GET?

The API call
https://myhost.net/api/get_global_search_result/methods/test
returns an Array object. I am trying to hold it in an Array object in order to read the attributes and values in it.
var queryResult = [];
queryResult = browser.get('https://myhost.net/api/get_global_search_result/methods/test/');
console.log('result length: ' + queryResult.length);
This is what I see on my console:
result length: undefined
If I load the above specified URL directly in a browser instance, it shows the Array with its contents.
What is the better way of capturing the array object returned by this call?
What about using JQuery ajax request.
it would be some thing like :
$(document).ready(function() {
$("#testbutton").click(function() {
$.ajax({
url: 'http://localhost:9200/xyz/xyz/xfSJlRT7RtWwdQDPwkIMWg',
dataType: 'json',
success: function(data) {
alert(JSON.stringify(data));
},
error: function() {
alert('error');
}
});
});
});

Unable to loop through JSON reponse in JQuery with .each method

I'm unable to extract object properties using the . each() method in Jquery. I'm able to view the full response with console.log (result), but I'm unable to extract from that response. I receive an undefined or [Object object] message when I attempt to use result.snippet in the .each method. When I use the .each for other json responses I'm able to extract by using data.value, but for this response it doesn't work.
(function getArticles(){
var url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
url += '?' + $.param({
'api-key': "",
'q': "obama"
});
$.ajax({
url: url,
type:"GET",
data:{
}
}).done(function(result) {
console.log(result);
$.each(result, function () {
document.write(result.snippet); // This is not working, but works with other json responses from other API's//
})
});
})();
The response you're getting is an object, not an array. You can't iterate over an object. You can iterate over the keys of an object and then reference each key. In either case, you don't need jQuery to do the iteration.
var response = {
"hello": "world",
"foo": "bar"
};
for (var key in response) {
console.log(key, response[key]);
}
In your case, to get to the snippet:
response.docs[0].snippet
You could iterate each document:
response.docs.forEach(function(doc) {
console.log(doc.snippet);
});

Return String From XHRGet

I'm creating a tree using Dojo and two seperate sets of data. One set of data makes up the main tree structure. The second set of data is dependent on a value from the first set. I'm using xhrGet and Dojo 1.7.3 to get the data.
Once the second set of data has been returned, I'm looking at the values of the JSON to determine a value of a variable, that's then passed into the tree. The variable displays a "!" if an "alert" value is present in the JSON returned and blank if there isn't.
var theAlert = dojo.xhrGet({
url: proxy + serviceurl + targetId,
handleAs: 'json',
load: function(data){
if(typeof data.alerts[0] != 'undefined'){
var hello = "!";
return hello;
}
else{
console.log("There is nothing there");
},
error: function(error){
console.log(error)
}
});
The problem I'm having is that when I write "theAlert" variable where I need to, it appears as "[object Object]" and not as "!".
I feel like I'm doing something wrong, but I can't figure out what.
I have already tried using theAlert.valueOf(); to no success. Help?
The data is received correctly as well, I can view it via console log.
dojo.xhrGet() returns a Deferred - http://dojotoolkit.org/reference-guide/1.9/dojo/Deferred.html
You need to do something like:
var deferred = dojo.xhrGet({
url: proxy + serviceurl + targetId,
handleAs: 'json'
});
deferred.then(
function(data){
if(typeof data.alerts[0] != 'undefined'){
processAlert("!");
} else{
console.log("There is nothing there");
}
},
function(error){
console.log(error)
}
);
function processAlert(a) {
alert(a);
}
Look at the docs.
You need to return data, not hello.

GetJSON's data : clarification needed

Given JSON containing:
[
{"myKey":"A","status":0,"score":1.5},{"myKey":"C","status":1,"score":2},
{"myKey":"D","status":0,"score":0.2},{"myKey":"E","status":1,"score":16},
{"myKey":"F","status":0,"score":0.4},{"myKey":"G","status":1,"score":3}
]
Given JS such:
MyJSON = $.getJSON('http://d.codio.com/hugolpz/getJson--/App/data/statusStarter2.json' );
How to get the JSON's content (stringified) into localStorage.data ?
Note: localStorage.data = JSON.stringify(MyJSON); returns {"readyState":1}, which is not my wish. I looked into jQuery.getJSON/, but I'am quite confused by the function (data).
getJSON works asynchronously and what it returns is AJAX request object. So use success callback function of getJSON to recieve the data
$.getJSON('http://d.codio.com/hugolpz/getJson--/App/data/statusStarter2.json', function(data) {
// do JSON.stringify(data) here
});
Did you try :
localStorage.setItem('data', JSON.stringify(MyJSON));
and
var JSON = localStorage.getItem('data');
and as ajax is async :
$.getJSON('url', function(MyJSON) {
localStorage.setItem('data', JSON.stringify(MyJSON));
});

Categories