How to get to the bottom of a JSON tree - javascript

I come to you today with maybe a noob-ish question. I'm trying to parse a JSON response from the server on my client side but I seem to have hit a wall as I can't actually acces the data inside of it. Here's the JSON content I'm trying to go through. I just need the name as in name:"Topic3"
'{
links: [ ],
content: [
{
links: [ ],
content: {
name: "Topic3",
technology: {
name: "Java",
technology_id: 1
},
topic_id: 3
},
id: null
},
],
id: null
}'
Any help would be greatly appreciated. Also this is my JS code that I tried to work on it with.
$.ajax({
type:'GET',
dataType: 'json',
url: "technologies/"+ option+ "/topics"
}).then(function(data)
{
for(i=0;i<data.content.length;i++)
{
var topic = document.createElement("button");
var content= (Object.keys(data.content[i]));
topic.name= content.content.name;
AddTopic.appendChild(topic);
}
});

To set button text use innerHTML property
var topic = document.createElement("button");
var content = data.content[i];
topic.innerHTML = content.content.name;
AddTopic.appendChild(topic);

So I'm assuming you need to iterate through and find every available topic - in that case I believe this should work
$.ajax({
type:'GET',
dataType: 'json',
url: "technologies/"+ option+ "/topics"
}).then(function(data)
{
for(i of data.content)
{
var topic = document.createElement("button");
topic.name= i.content.name;
AddTopic.appendChild(topic);
}
});

Related

Wikipedia API extract returning Edit Link in Text

I am attempting to pull the json from the wikipedia API. When I extract the main content it shows up on my page but the edit links show up next to the <h2> header. I've included the param "disableeditsection": false, as both true and false but to no avail. According to these docs: docs
Any ideas on how to remove the 'edit' text from the extract?
Thank you in advance for your help
$(document).ready(function ($) {
console.log('ready1!');
var wikiSearch = "Blue Spring State Park";
var queryURL = "https://en.wikipedia.org/w/api.php";
var params = {
"disableeditsection": false,
"action": "query",
"format": "json",
"prop": "links|images|extlinks|imageinfo|info|url|extracts|text",
"iiprop": "timestamp|user|url|comment",
"meta": "url",
"origin": "*",
"iwurl": 1,
"titles": wikiSearch,
"redirects": 1,
"inprop": "url"
};
queryURL += "?" + $.param(params);
$.ajax({
url: queryURL,
method: "GET"
}).done(function (response) {
console.log('ready2!');
console.log('response', response);
var objResult = response
console.log(objResult);
$.each(response.query.pages, function (c) {
var hey = response.query.pages[c].extract;
$("#wikipediaImages").html(hey);
}); //End .each
}); //End .done
}); //End Document.ready
It seems that you use the output from extract. This generally doesn't include edit links. But there seems to be a bug on some pages. disableeditsection doesn't apply on prop=extracts.
If you want the html as it is, without edit on section links, then use action parse: https://en.wikipedia.org/w/api.php?action=parse&format=json&page=Blue%20Spring%20State%20Park&disableeditsection=1
In general your question is unclear what exactly do want to display.

Get JSON data with AJAX and then modify raphael.js script

This is what I want to achieve:
I want to create an interactive map using raphael.js.
Using Php, I get datas from MySql DB and converted into a JSON file.
So far so good.
Inside my raphael js file, I must now:
get those datas
use them in order to modify my raphael file.
I am currently stuck at this first step.
Here's my simplified JSON file (let's call it countries.json) :
[
{
"id": "1",
"type": "Country",
"title": "France",
"published": "1",
"description": "Republic"
},
{
"id": "2",
"type": "Country",
"title": "Belgium",
"published": "0",
"description": "Monarchy"
}
]
Here comes the simplified raphael.js
var rsr = Raphael('map', '548', '852');
var countries = [];
var france = rsr.path("M ... z");
france.data({'published': '1', 'type': '', 'title': '', 'description':''});
var belgium = rsr.path("M ... z");
belgium.data({'published': '0', 'type': '', 'title': '', 'description':''});
countries.push(france,belgium);
At the end of the raphael js, I make an Ajax request (using jquery) to get my JSON datas :
$.ajax({
type : 'GET',
url : 'system/modules/countries.json',
data: {get_param: 'value'},
dataType : 'json',
success : function(data, statut){
console.log(statut);
},
error : function(data, statut,erreur){
console.log(statut);
},
complete: function (data) {
var json = $.parseJSON(data);
$(json).each(function(i,val){
$.each(val,function(k,v){
console.log(k+" : "+ v);
});
});
}
});
Here come the troubles:
I get a 'success' status trough the success function.
BUT I got an error while completing the script :
Uncaught SyntaxError: Unexpected token o
What did I miss? Can't figure out what is different from http://jsfiddle.net/fyxZt/4/ (see how to parse json data with jquery / javascript?)
That was just for part 1 :-)
Assuming someone could help me to fix that, I still then have no idea how to write js loop that will set the raphael vars attributes as it:
var rsr = Raphael('map', '548', '852');
var countries = [];
var france = rsr.path("M ... z");
france.data({'published': '1', 'type': 'Country', 'title': 'France', 'description':'Country'});
var belgium = rsr.path("M ... z");
belgium.data({'published': '0', 'type': 'Country', 'title': 'Belgium', 'description':'Monarchy'});
communes.push(france,belgium);
Thanks an advance for your help and please excuse my unperfect english!
Vinny
There is no data argument passed to the complete callback,
according to jQuery API:
complete
Type: Function( jqXHR jqXHR, String textStatus )
(...)The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "nocontent", "error", "timeout", "abort", or "parsererror").
So you only need to use the success callback :
$.ajax({
type: 'GET',
url: 'system/modules/countries.json',
data: {
get_param: 'value'
},
dataType: 'json',
success: function (data, statut) {
var json = data;
$(json)
.each(function (i, val) {
$.each(val, function (k, v) {
console.log(k + " : " + v);
});
});
},
error: function (data, statut, erreur) {
console.log(statut);
}
});
Concerning your second question, you cannot interact directly with variable name (accessing dynamic variable) in js, so you'll need to create an object where values are indexed by one of your json's values. However, the cleanest way to handle this would probably be to add your paths to the json...
var rsr = Raphael('map', '548', '852');
var countries = [];
//here I used the "id" property from the json
var paths={
"1":rsr.path("M ... z"),
"2":rsr.path("M ... z")
};
countries.push(france,belgium);
$.ajax({
type: 'GET',
url: 'system/modules/countries.json',
data: {
get_param: 'value'
},
dataType: 'json',
success: function (data, statut) {
datas.forEach(function (country) {
paths[country.id].data(country);
});
},
error: function (data, statut, erreur) {
console.log(statut);
}
});

Typeahead format source

I'm trying to use Typeahead. I'm using AJAX to get my source :
$(document).ready(function() {
$('input.typeahead').typeahead(
{
hint: true,
highlight: true,
minLength: 1
},
{
source: function(query, process) {
jQuery.ajax({
url: 'suggestion.php',
dataType: "json",
data: {
type: 'abc'
},
success: function(data) {
suggestion = [];
for(var i in data)
{
suggestion.push(data[i]);
}
console.log(data);
}
});
process(suggestion);
return suggestion;
}
});
});
But there is the result :
But when I see the logs :
I've an array with strings !
There the console message :
I can see an error appear at the first char typed but only the first time. All the time, I've "undefined" x 5 proposed.
What's the matter ? I guess the format, but I've tried mainly things from stacks, without results (only errors). My Php code return ("echo") an json_encode($array) ! It's my first time using Ajax and Typeahead..
Sorry for my english.
I think that suggestion must be this kind of array :
[{ "value": "CBOXXX" }, { "value": "CBAXXX" }]

If only single quote is passed as parameter in ajax post it throws error

The JQuery Code:
var name = jQuery("#name1").val();
jQuery.ajax({
url: siteUrl + 'search/ind',
type: 'POST',
data: { name: name, },
success: function(data) {
jQuery('#input').val('');
}
});
If only a "'" (single quote is given for search field) , the result is getting at response but due to a JS error it is preventing from appending to html container.
The ERROR:
SyntaxError: missing ; before statement
...imit":14,"keyword":{"name":"'"
Any help is appreciated as
SOLUTION:
The main reason behind this issue was due to json parsing.... after debugging through code i was able to find the issue and on removing an unwanted parsing the params are getting correctly.Anyway thanks to all who assisted in finding this issue...cheers!!!
Please Remove Extra Comma from data: { name: name, }, and try Again
var name = jQuery("#name1").val();
jQuery.ajax({
url: siteUrl + 'search/ind',
type: 'POST',
data: { name: name }, /*Extra Comma removed*/
success: function(data) {
jQuery('#input').val('');
}
});
I like to use short hands and put the key of the object in quotes "", it is just simple and easy to read.
var name = $( '#name1' ).val();
$.post( siteUrl + 'search/ind', { "name" : name }, function( response ) {
$( '#input' ).val('');
}
});

ExtJS grab JSON result

I'm generating JSON response from PHP witch looks like this:
{ done:'1', options: [{ message:'Example message'},{message:'This is the 2nd example message'}]}
I want to grab these results using ExtJS. This is what I have so far:
Ext.Ajax.request({
loadMask: true,
url: 'myfile.php',
params: {id: "1"}
});
What do I have to write next to get the json results like this:
var mymessages = jsonData.options;
And mymessages should contain Example message and This is the 2nd example message.
Thank you.
The straightforward approach:
Ext.Ajax.request({
loadMask: true,
url: 'myfile.php',
params: {id: "1"},
success: function(resp) {
// resp is the XmlHttpRequest object
var options = Ext.decode(resp.responseText).options;
Ext.each(options, function(op) {
alert(op.message);
}
}
});
Or you could do it in a more Ext-ish way using Store:
var messages = new Ext.data.JsonStore({
url: 'myfile.php',
root: 'options',
fields: [
{name: 'text', mapping: 'message'}
],
listeners: {
load: messagesLoaded
}
});
messages.load({params: {id: "1"}});
// and when loaded, you can take advantage of
// all the possibilities provided by Store
function messagesLoaded(messages) {
messages.each(function(msg){
alert(msg.get("text"));
});
}
One more example to address the last comment:
var messages = [{title: "1"},{title: "2"},{title: "3"}];
var titles = msg;
Ext.each(messages, function(msg){
titles.push(msg.title);
});
alert(titles.join(", "));
Although I would prefer doing it with a Array.map (which isn't provided by Ext):
var text = messages.map(function(msg){
return msg.title;
}).join(", ");
alert(text);
Use the success and failure properties:
Ext.Ajax.request({
loadMask: true,
url: 'myfile.php',
params: {id: "1"},
success: function(response, callOptions) {
// Use the response
},
failure: function(response, callOptions) {
// Use the response
}
});
See the Ext API docs for more details
check this sample fiddle which is for Ext JS 4. http://jsfiddle.net/mrigess/e3StR/
Ext 4 onward utilizes Ext.JSON.encode() and Ext.JSON.decode() ; while Ext 3 uses Ext.util.JSON.encode() and Ext.util.JSON.decode()
if you are sure that your input is correct (beware of xss attacks) you can use the eval() function to make your javascript object from your json result, which can then be accessed through your command:
var mymessages = jsonData.options;
But then again, Ext does that nicely for you, as Rene has pointed out through the Ext.decode function

Categories

Resources