can't fetch data from json with jquery ajax - javascript

I just started learning json using jquery and I'm having some difficulties, I've spent two days, I've followed lots of tutorial both on youtube and blogs but what they show isn't what I have in my case. Their json is different from mine. They got multiple keys I've only one "news"
the JSON response from the server I get is like this:
{
"news":[
{
"id":48927,
"name": "The title goes right here",
"url": "www.example.com",
"date":"16 August 2013",
"image":"img.example.com\/image.jpg"
},
{
"id": 48908,
"name":"The title goes right here — photography",
"url":"www.example.net",
"date":"17 August 2013",
"image":"img.example.net\/image2.jpg"
}
]
}
in reality what I get from the server is more like this:
{"news":[{"id":48927,"name": "The title goes right here","url": "www.example.com","date":"16 August 2013","image":"img.example.com\/image.jpg"},{"id": 48908,"name":"The title goes right here — photography","url":"www.example.net","date":"17 August 2013","image":"img.example.net\/image2.jpg"}]}
but they both valid! I've already check with JSON LINT.
so what I'm not able to do is to get all the info from JSON and append them in my #posts
I've tried both $.getJSON & $.ajax but I get undefined as response
$(document).ready(function() {
$.ajax({
url: 'http://s.example.com/myjson.php',
data: 'GET',
dataType: 'json',
success: function(data){
$('#posts').append('name: ' + data.news.id + '<br/>');
},
});
});
in code above I've tried in append also with data, data.id, data.news, data.url etc. but alway getting undefined or null.
$(document).ready(function() {
$.getJSON("http://s.example.com/myjson.php", function(data) {
$.each(data, function(key, value) {
$("#posts").append("<li>"+data.news+"</li>");
});
});
});
same as $.ajax tried different things in append but nothing.
what I want to do is to have all the data id, name, url, date, image appended for everyone of the "things" I've in my json file. But unfortunately I'm stuck at the beginning. It's really frustrating, because it seems so simply but I can't figure out a way to do it. Please help me!!

Inside your success function, loop over all of the elements in the news array:
for (var i=0; i < data.news.length; i++) {
$('#posts').append('name: ' + data.news[i].id + '<br/>');
}

data.news is an array so you have to loop through it to get all the values
$(document).ready(function() {
$.getJSON("http://s.example.com/myjson.php", function(data) {
$.each(data.news, function(key, value) {
$("#posts").append("<li>"+value.id+"</li>");
});
});
});

In your JSON, news is an array.
You need to get the property from an element in the array:
data.news[42].id
You will need to figure out which element to get.

Related

I am trying to display a paragraph of text in HTML but I need to create it as a JSON object and read it with AJAX to do so. My code is not working

I have tried to iterate through the JSON object but it is not working. Is there a more efficient way to even structure the object? Also, I am not sure that the AJAX request is being made because I keep seeing an error message which is "There was a problem: 0".
This is my JS file:
$(document).ready(function() {
$.ajax({
type: "GET",
url: "lab4.json",
dataType: "json",
success: function(response){
var message = "";
$.each(responseData.text, function(i, item) {
$.each(item.tutoring-text, function(x, s) {
message += s;
});
});
$("#tutoring-text").html(message);
},
error: function(msg) {
// there was a problem
alert("There was a problem: " + msg.status + " " + msg.statusText);
}
});
});
This is my JSON file:
{
"text":{
"tutoring-text": [
"Gamma Nu Eta holds weekly tutoring sessions every Wednesday.",
"At these tutoring sessions, GNH can help you with any course in your ITWS degree program.",
"This includes ITWS core classes, such as Intro to ITWS and Web Systems, or classes outside of ITWS, such as Computer Science 1 and Data Structures.",
"We can also help with any questions that you might have about career development, resumes, as well as just general questions about RPI."
]
}
}
You're trying to iterate when your JSON structure is reasonably flat.
All you really need is
$("#tutoring-text").html(response.text["tutoring-text"].join(""))

Pull different data strings from JSON via Ajax

My client has a jobs board whose API data I'm pulling via Ajax. I can parse the "jobs" data but cannot seem to pull any thing else. For instance, this works to pull the names of job listings to a select box:
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/jobs/',
type:'GET',
data: 'q=' + "",
dataType: 'json',
success: function( json ) {
$.each(json.jobs, function(i, value) {
$('#myselect').append($('<option>').text(value.title).attr('value', value.title));
});
}
});
But when I change "json.jobs" to anything else like "json.offices" or "json.locations" nothing is pulled. How do I go about accurately targeting these data strings to cull together for a complete careers page? Appreciate any guidance whatsoever thanks.
This is the JSON if you need to take a look:
https://api.greenhouse.io/v1/boards/roivantsciences/jobs/
try pull location.name for all jobs $.each(json.jobs, function(i, value) { $('#myselect').append($('<option>').text(value.location.name).att‌​r('value', value.location.name)); });
Ive done a small test:
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/jobs/',
type:'GET',
data: 'q=' + "",
dataType: 'json',
success: function( json ) {
console.log(json)
}
});
What I got back from console is that your json object only has 'jobs' as the top attribute in it.
You have to go through it like this to get locations:
$.each(json.jobs, function(i, value) {
console.log(value.location);
});
then you have the location object inside this you got the attribute 'name'
so u can get the names with value.location.name

display ajax called data in an UI

i have been able to fetch data with an ajax call from active directory .
the php file used to make the ajax call to active directory :http://pastebin.com/tSRxwQL8
The browser console shows that an ajax call returns this :
<p> sn: xxxxxx<br/>givenname: xxxxx<br/>
employeeID: 0050<br/
>distinguishedName: CN=xxxx xxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxxxxx,DC=com<br/>
displayName: Mark Hewettk<br/>sAMAccountName: xxxxxxx<br/>
department: xxxxx<br/>manager: CN=xxxxxx xxxxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxx,DC=com
<br/>
mail: mhewettk#abc.com<br/>
title: xyz<br/>
I want to take only some attributes above like mail,displayname etc and display in my HTML :
<h2 class="profile__name" id="emailOfUser">Email : </h2>
Now the problem is the jquery that I have used here :
$('.leaderboard li').on('click', function() {
$.ajax({
url: "../popupData/activedirectory.php", // your script above a little adjusted
type: "POST",
data: {
id: $(this).find('.parent-div').data('name')
},
success: function(data) {
console.log(data);
$('#popup').fadeIn();
$('#emailOfUser').html(data); //this line displays all data whereas I want to select only email,displayname from the above console data
//whatever you want to fetch ......
// etc ..
},
error: function() {
alert('failed, possible script does not exist');
}
});
});
problem is this :
$('#emailOfUser').html(data);
this line displays all data whereas I want to select only email,displayname from the above console data
kindly help me how to select only desired attribute data from the above browser console data.
Ideally you should return JSON from PHP file, however if it is not possible for you to make changes to PHP file then you can use split("mail:") and split("title:") to extract data
success: function(data) {
console.log(data);
$('#popup').fadeIn();
var email=(data.split("mail:")[1]).split("title:")[0];
$('#emailOfUser').html(email); //this line displays all data whereas I want to select only email,displayname from the above console data
//whatever you want to fetch ......
// etc ..
},
You are getting response in HTML which makes difficult for you to extract mail, displayname, etc.
You should get the response in JSON which will make it easy for you to extract the required info.
Ask your back-end team to send response in JSON format.
Working Fiddle
Try :
var lines = 'sn: xxxxxx<br/>givenname: xxxxx<br/>employeeID: 0050<br/>distinguishedName: CN=xxxxxxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxxxxx,DC=com<br/>displayName: Mark Hewettk<br/>sAMAccountName: xxxxxxx<br/>department: xxxxx<br/>manager: CN=xxxxxx xxxxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxx,DC=com<br/>mail:mhewettk#abc.com<br/>title:xyz<br/>'.split('<br/>');
jQuery.each(lines, function() {
var val = this;
if (val.indexOf('mail') > -1)
// alert(val.split(':')[1]); //Only for test
$('#emailOfUser').html(val.split(':')[1]);
});

Issue getting first item from JSON array

$('#data').change(function () {
$.ajax({
url: 'richiesta.php',
type: 'POST',
dataType: 'json',
data: {
value: this.value
},
}).done(function (data) {
$('#textfield').val(JSON.stringify(data));
$('#results').val('Descrizione codice: ' + data[0].descrizione_codice);
});
});
richiesta.php is just a file that triggers some functions to get the JSON.
#textfield is correctly populated with the raw JSON, so everything is working properly.
I can't figure out how to output the first item of the JSON identified by the name descrizione_codice in #results.
The JSON is valid, here's an example selecting one option (truncated):
{
"data":[
{
"codice_comparto":"PRO",
"descrizione_codice":"Competenze fisse per il personale a tempo indeterminato",
"codice_siope":"1101",
"descrizione_ente":"",
"ricerca":false,
"idtable":"000717409-1101",
"cod_ente":"000717409",
"anno":"2014",
"periodo":"12",
"codice_gestionale":"1101",
"imp_uscite_att":"756",
"importo_2013":"37718576",
"importo_2014":"32810124",
"importo_2015":null
}
],
"cosa":false
}
I'm doing something wrong is that data(0).descrizione_codice as Firebug tells me "data is not a function"..
I'm not using $.parseJSON because jQuery already parses data correctly thanks to the datatype.
I put up a test page here. You can request the JSON response selecting an option from the dropdown menu.
According to your JSON structure you should be able to access array as data.data
.done(function (data) {
console.log(data.data[0].descrizione_codice);
});
$('#results').val('Descrizione codice: ' + data.data[0].descrizione_codice);
First data is your actual js variable
Second data is your array inside JSON named "data" where we access first element's property named "descrizione_codice"
Hope it clarifies

Displaying my json result but it only returns 1 result from database

Hi I have a working script on my javascript for my chat application but I noticed on my console that my json result returned as 1 single result only when i used .append() so I switched to .text() it also returned my json result but this time only 1 conversation was retrieved from my database.. What I want is to retrieve everything just like on .append but each are displayed individually
here is what I have so far :
$("#user-list").find("a").on("click", function(e){
$(".wtf").fadeIn(300);
e.preventDefault();
var uid = $(this).data('uid');
$('.wtf #rid').val(uid);
var rid = $('#rid').val(),
user = $('#usernas').val(),
suid = $('#uid').val(),
data = {chat: suid, rid: rid, name: user};
$.ajax({
url: "includes/uid-chats.php",
type: "GET",
data: data,
dataType: 'json',
}).done( function(result){
$.each(result, function(rowKey, row) {
$(".media-heading").text( row.username );
$("p").text( row.message_content );
});
});
});
The reason why I didn't want to continue using .append() is because the chat is loaded on a styled <li>... Any suggestion on how can I solve my problem?
0
Object { msgid="2014041412", message_content="asdsaf", username="ab.cd", more...}
1
Object { msgid="2014041412", message_content="asdfff", username="ab.cd", more...}
2
Object { msgid="2014041412", message_content="a", username="ab.cd", more...}
This is what the firebug gave me under JSON tab there atleast nine result I just pasted few to cut it short
And on my main page it only displays
ab.cd
ccc
only
Try this fiddle..
http://jsfiddle.net/madhust/Aa65D/
In that i have created the li as per the json length and appended to the ul dynamically.
you are iterating through the object and overwriting the text value of the same element on every iteration. try something like:
$.each(result, function(rowKey, row) {
var newEl = $('<div><h2 class="media-heading"></h2><p></p></div>');
$(newEl.find('.media-heading')[0]).text(row.username);
$(newEl.find("p")[0]).text( row.message_content );
$('body').append($(newEl));
});

Categories