Getting data from API with AJAX - javascript

I am trying to get data from API and display them using AJAX
I have this code
$(document).ready(function(){
$('.show').click(function(){
$.ajax({
url: 'url',
dataType: 'json',
success: function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'interest-list',
html: items.join('')
}).appendTo('body');
},
statusCode: {
404: function() {
alert('There was a problem with the server. Try again soon!');
}
}
});
});
});
I have this result:
[object Object],[object Object],[object Object],[object Object],
What must I fix in my code?

$.each iterates over the array, and key was the index of the array, and val was the entire object
You could change this line of code
items.push('<li id="' + key + '">' + val + '</li>');
to
var key = Object.keys(val)[0];
items.push('<li id="' + key + '">' + val[key] + "</li>");
to just get the first key directly.
Here is the documentation for
Object.keys.

First of all, you'd better add the type:'GET' field to define what kind of call are you doing.
Then you can use var json = JSON.parse(data) to read all the incoming data from data like this:
var time = json['foo'];
or if you have an array:
var time = json[index]['foo'];
you can find more details here https://www.w3schools.com/js/js_json_parse.asp and here https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

Related

Create nested menu via 3 json files

I am trying to make a nested menu from 3 json files, but In the first step I stuck, it return nothing:
var json = {};
$.getJSON("/api/category.json", function(data){
json.category = data;
});
$.getJSON("/api/subcat.json", function(data){
json.subcat = data;
});
$.getJSON("/api/subsubcat.json", function(data){
json.subsubcat = data;
});
$.each(json, function(i,v) {
console.log(json[i]); // it return nothing
});
But when I tried console.log(json) it return object, but even when I get console.log(json.category) It return nothing, no error in console log.
If I solve this issue I want to make a nested menu with this three json file in a loop, something like this:
var obj = '';
$.each(json.category, function(i, v) {
obj += '<li data-id="' + data[i]['id'] + '">' + data[i]['name'] + '<ul>';
$.each(json.subcat, function(i, v) {
if (json.subcat["cat_id"] == json.category["id"]) {
obj += '<li data-id="' + data[i]['id'] + '">' + data[i]['name'] + '</li>';
}
});
obj += '</ul>';
// also subsub cat
$('.simulate-cat').append($(obj));
});
<ul class="simulate-cat"></ul>
Is this way right to make nested menu?
Thanks in advance
Problem is that you're not waiting for the requests to complete. Because of that json properties aren't populated yet
It should look like this
$.when($.getJSON("/api/category.json"), $.getJSON("/api/subcat.json") , $.getJSON("/api/subsubcat.json")).done(function( a1, a2, a3 ) {
json.category = a1[0];
json.subcat = a2[0];
json.subsubcat = a3[0];
// create menu here
});
See $.when for more info about how to wait for multiple async callbacks

Client call JSON result show as undefined

I have a set of json data which is generated in php with json_decode function, here is the results:
I then create a html document and try to call the result using jquery $.getJSON:
var apiSrc = 'http://localhost/api/ws-data';
var showData = $('#result');
$(function(){
$.getJSON(apiSrc, function(data) {
console.log(data);
var items = data.blog.map(function (item) {
return item.key + ': ' + item.value;
});
showData.empty();
if(items.length) {
var content = '<li>' + items.join('</li><li>') + '</li>';
var list = $('<ul />').html(content);
showData.append(list);
}
});
showData.text('Loading...');
});
and the results for above is:
REST - Get JSON from PHP file on the server side
undefined: undefined
undefined: undefined
undefined: undefined
undefined: undefined
..
Its shown the key and value as undefined: undefined
What's goes wrong in the script?
I think you should access the correct properties such as pid,category etc of response,
var items = data.blog.map(function (item) {
return item.pid + ': ' + item.category;
});

TypeError: invalid 'in' operand a from ajax

I try to get a new list for each country select, in symfony, with jquery.
For this i use ajax, but i have this error :
TypeError: invalid 'in' operand a
My jquery :
$('.country').change(function(){
var val = $(this).val();
$.ajax({
type: "POST",
url: "{{ path('ajax') }}?country_id=" + val,
success: function(data) {
$('.extension').html('');
$.each(data, function(k, v) {
$('.extension').append('<option value="' + v + '">' + k + '</option>');
});
}
});
return false;
});
My path ajax call my function ajax in controller :
public function ajaxAction(Request $request) {
if (!$request->isXmlHttpRequest()) {
throw new NotFoundHttpException();
}
// Get extension ID
$numCountry = $request->query->get('country_id');
$result = array();
$extensions = $this->get('extension')->getExtensionByCountry($numCountry, array('name' => 'asc'));
foreach ($extensions as $extension) {
//$result[$extension->getName()] = $extension->getId();
$result['test'] = 1;
}
return new JsonResponse($result);
}
You are trying to iterate over a string, that is causing this error.Try using $.parseJSON(data)
success: function(data) {
$('.extension').html('');
data = $.parseJSON(data);
$.each(data, function(k, v) {
$('.extension').append('<option value="' + v + '">' + k + '</option>');
});
}
Read more $.parseJson
Are you sure your data is an array ? this normaly happen when you use "each" on a non array element.
I would like to suggest you few more things :
use FOS js routing : http://symfony.com/doc/current/bundles/FOSJsRoutingBundle/usage.html . It will be better for you to put you ajax in js files
you shoudln't name you method 'ajax' but instead use a clearer name

pull json data with ajax requests

I'm trying to pull in some json data using ajax. I am able to successfully pull data from the first 2 items but its the data under "placemark" that I really need. I need to be able to display this in a list much like an rssfeed. I'm not sure how to drill down deeper into the json to pull the data I need. any help greatly appreciated.
$.ajax({
type: 'GET',
url: rssAPI,
success: function(data){
console.log(data);
$.each(data, function(index, item) {
$.each(item, function(key, value) {
$('.listing').append(key + ': ' + value + '</br>');
});
});
}
});
here's what my json looks like
and this is my output
You need to either output, if the property value is a string, or iterate further (i.e. another loop) if it's an array, as is the case with the Placemark properties.
So:
$.each(data, function(index, item) {
$.each(item, function(key, value) {
if (typeof value != 'object')
$('.listing').append(key + ': ' + value + '</br>');
else
$.each(value, function(key, value) {
//these are your items under Placemark
});
});
});
Here placemark contains array of json objects. So you need to access it as below :
for(i=0; i<Document.Placemark; i++){
console.log(Document.Placemark[i].name);
console.log(Document.Placemark[i].description);
}

How to decode a JSON string?

On the server side do I have 2 hashes I encode into JSON strings like so
my $j = JSON->new;
$j = $j->utf8;
my $data;
$data->{users} = $j->encode(\%user_result);
$data->{owners} = $j->encode(\%owner_result);
$json_string = to_json($data);
print $cgi->header(-type => "application/json", -charset => "utf-8");
print $json_string;
On the client side I have
$(document).ready(function(){
$('form').live('submit', function(){
$.ajax({
type: "GET",
url: "/cgi-bin/ajax_confirm.pl",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: $(this).serialize(),
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('div#create_result').text("responseText: " + XMLHttpRequest.responseText +
", textStatus: " + textStatus +
", errorThrown: " + errorThrown);
$('div#create_result').addClass("error");
},
success: function(result){
if (result.error) {
$('div#create_result').text("result.error: " + result.error);
$('div#create_result').addClass("error");
} else { // perl script says everything is okay
var users = result.users;
var owners = result.owners;
...
users contains
{"ss":"Sandra Schlichting","fn":"Full name"}
but it is not an array. When I use $.each() it takes on character at a time.
Problem
How do I turn it into an array, so I can use
function makeTable(users) {
var result = '<table>\n<tr><td>Initials</td><td>Full Name</td></tr>\n';
$.each(users, function(index, value) {
result += '<tr><td>' + index + '</td><td>' + value + '</td></tr>\n';
});
result += '</table>';
return (result);
}
which should produce
Initials Full Name
ss Sandra Schlichting
fn Full name
You should use jQuery.getJSON() as mentioned at http://api.jquery.com/jQuery.getJSON/.
There is also $.parseJSON() method to parse string to json if you want to go that way.
You don't need to turn it into an array. According to the jQuery.each() documentation it takes both arrays or objects and JSON is a subset of the object literal notation of JavaScript.
Edit: Here's an example: http://jsfiddle.net/pedrocorreia/s5UrZ/2/
You can use the JSON parser created by douglas crockford:
https://github.com/douglascrockford/JSON-js
include the json2.js in your page, the you can do:
var object = JSON.parse(string);
Then you can use it as an array.
you can use for in statement
var index = 0;
for(user in users){
result += '<tr><td>' + index + '</td><td>' + user['fn'] + '</td></tr>\n';
index++;
}

Categories

Resources