Accessing elements in single Json Object - javascript

I have a book in the form of a single Json object returned from an ajax request:
{
"status": "success",
"bytes": 2598,
"book": {
"isbn": 9781449397227,
"title": "jQuery Pocket Reference",
"author": "David Flanagan",
"description": "As someone who uses jQuery on a regular basis, blah blah.",
"published": "2000-05-02",
"cover": "http://bks9.books.google.co.uk/books?id=rK6YPwAACAAJ&printsec=frontcover&img=1&zoom=1&source=gbs_api",
"pages": 402,
}
}
And I wish to access the isbn, title, author elements etc to append to my output . My question is how to access these in my
success: function(data) {
};
I have used console.log(data); in success and Firebug shows me that the data is there. My other ajax calls return a books array and I can just use something like:
$.each(data.books, function(i,book)
and it works fine. But with the example above its just a single object 'book'.
Thanks

success: function(data) {
console.log(data.book.isbn);
console.log(data.book.title);
console.log(data.book.author);
};

I'm not sure I understand the problem (because of my little english). But if your ajax call has dataType:'json', you can access the data with
success: function(data) {
console.info(data)
otherwise you have to parse the data with
success: function(data) {
data = $.parseJSON(data);
or in case use are using Crockford JSON lib
success: function(data) {
data = JSON.parse(data);

Related

How to use ajax response JSON data?

I have made my ajax request, which works great and returns JSON.
But how do i use it?
My response is something like this
[{
"id": "5",
"reviewID": "2389",
"serviceID": "50707",
"title": "well done"
}]
Now in my success function I am trying to use the data like such:
success: function(data) {
alert('Success Alert');
$('#myModalLabel').text('Review:' + data.title);
},
This just shows
[object Object]
How can I use this data?
As data is array of objects, use data[0].title:
$('#myModalLabel').text('Review:' + data[0].title);
// ^^^

Parsing response text as key value pairs in an elegant way

Can't seem to find what I'm looking for in searches so this might be a duplicate but I haven't found an original yet sooo....
I have a an ajax call:
$.ajax({
url: "/events/instructor/",
type: 'POST',
data: {
instructorID: $(this).attr("id")
},
complete: function (data) {
$("#name").html(data["responseText"]["name"]);
$("#email").html(data["responseText"]["email"]);
$("#photo").html(data["responseText"]["photo"]);
$("#summary").html(data["responseText"]["summary"]);
$("#url").html(data["responseText"]["url"]);
}
});
The data being returned is encoded in JSON by the server (C#).
Obviously, data["responseText"]["fieldName"] isn't doing the trick. I could do splits and whatnot but that would mean that if the format changes, I'd need to make sure that the code above keeps up with the changed shape of the data.
How can I say something as simple as data["responseText']["fieldName"] to get the value out of that key?
i think you need to parse json first. look at the api.jquery.com/jquery.parsejson
// data = '{ "name": "John" }'
var obj = jQuery.parseJSON( data );
console.log( obj.name);
// result will be "John"
P.S. also better use 'succes' instead 'complete', you can read about this here Difference between .success() and .complete()?
success: function(data) {
console.log("response is good", data);
},
error: function (){
console.log("something is went wrong");
}
try using like this:
complete: function (data) {
var data=JSON.parse(data);
$("#name").html(data.responseText.name);
$("#email").html(data.responseText.email);
$("#photo").html(data.responseText.photo);
$("#summary").html(data.responseText.summary);
$("#url").html(data.responseText.url);
}
to get only correct response use success.

How to parse json response in jQuery mobile?

I am new to jquery mobile. I am trying to get contact name from contacts. JSON by sending AJAX request. But I am not getting any alert when I click on submit button.
My jQuery ajax request
$(document).ready(function() {
//after button is clicked we download the data
$("#submit").click(function(){
//start ajax request
$.ajax({
url: "myURL/contacts.json",
dataType: "json",
success: function(data) {
var json = $.parseJSON(data);
alert(json.name);
});
});
});
contacts.json
{
"contacts": [
{
"id": "c200",
"name": "Ravi Tamada",
"email": "ravi#gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
{
"id": "c201",
"name": "Johnny Depp",
"email": "johnny_depp#gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
.
.
.
.
]
}
How to generate dynamic clickable list for above ajax response?
dataType: "json"
already specifies the returned data to be a json object. so to read the values, you can simply use the object syntax:
success: function(data) {
//cycle trough returned "contacts":
for(var i=0;i<data.contacts.length;i++){
console.log(data.contacts[i].name);
}
}
from the looks of it, your json will be an array of object. Try doing json[0].Name to test it
your json data present inside contacts,so you should take name in this format.
var json = $.parseJSON(data);
alert(json.contacts[0].name);
Firstly our code is badly formated (smart quotes, wrong placement of parentheses). Secondly since your contacts are in an array, you can't access them using json.name, you should try something like this instead:
$(document).ready(function () {
//after button is clicked we download the data
$("#submit").click(function () {
//start ajax request
$.ajax({
url: "myURL/contacts.json",
dataType: "json",
success: function (data) {
var json = $.parseJSON(data);
json.contacts.forEach(function(val, ind, arr){
alert(val.name);
});
}
});
});
});
In stead of parsing JSON you can do like followng:
$.ajax({
..
dataType: 'json' // using json, jquery will make parse for you
});
To access a property of your JSON do as shown in below:
data[0].name;
data[0].email;
Why you need data[0] because data is an array, so to its content retrieve you need data[0] (first element), which gives you an object {"name":"myName" ,"address": "myAddress" }.
And to access property of an object rule is:
Object.property
or sometimes
Object["property"] // in some case
So you need
data[0].name and so on to get what you want.
If you not
set dataType: json then you need to parse them using $.parseJSON() and to retrieve data like above.

JSONP ajax callback failing

I have following script running on my local test drive. It imports a JSON file and builds a webpage, but for some reason, there is an error in handling the data. No data is shown...
But whenever I use (the same) data hard-coded, I get the result I want. So this made me think it has something to do with the way I handle the JSON import...
This is my AJAX callback:
getGames: function(fn) {
$.ajax({
type: "GET",
url: App.Config('webserviceurl')+'games-payed.js',
dataType: "jsonp",
success: function (data) {
console.log('streets', data);
if(fn){
fn(data);
}
},
error: function (msg) {
if(fn){
fn({status:400});
}
}
});
}
And this code isn't working, nor am I getting any errors in my console...
When I load the data hard coded, it works perfectly:
getGames: function(fn) {
var games = App.Config('dummyGames');
if(fn){
fn(games);
}
}
Is there something wrong with my AJAX callback?
EDIT:
The JSON file looks like this:
jsonp1({
"status": "200",
"data": [
{
"id": "1",
"title": "Title 1",
"publishDate": "2013-03-27T15:25:53.430Z",
"thumbnail": "images/thumbs/image_game1.png",
"html5": "http://mysite.com/index.html"
},
{
"id": "2",
"title": "Title 2",
"publishDate": "2013-03-20T15:25:53.430Z",
"thumbnail": "images/thumbs/image_game2.png",
"html5": "http://mysite.com/index.html"
},
{
"id": "3",
"title": "Title 3",
"publishDate": "2013-03-18T15:25:53.430Z",
"thumbnail": "images/thumbs/image_game3.png",
"html5": "http://mysite.com/index.html"
}
]
});
In your example, I see that you wrap your json data inside jsonp1. I suppose that is a fixed name. If that's the case, try this:
getGames: function(fn) {
$.ajax({
type: "GET",
url: App.Config('webserviceurl')+'games-payed.js',
jsonp: false,
jsonpCallback:"jsonp1",
dataType: "jsonp",
success: function (data) {
console.log('streets', data);
if(fn){
fn(data);
}
},
error: function (msg) {
if(fn){
fn({status:400});
}
}
});
}
Notice the jsonpCallback:"jsonp1" and jsonp: false. The reason for this is: by default, jquery will generate the callback function name automatically and randomly and append ?callback=generatedFunctionName to the end of your url. Thanks to the callback parameter, the code on server side could use the same function name to call the callback on browser.
In your case, you're using fixed function name (jsonp1), so you have to:
Specify your function name explicitly using jsonpCallback="jsonp1"
Set jsonp = false to prevent jQuery from adding the "?callback" string to the URL or attempting to use "=?" for transformation.

Sending a multi-level javascript object to the server with AJAX fails

I have a javascript object that looks somthing like this:
var obj = {
"name": "username",
"userid": "9999",
"object1": {
"subObject1": {
"subArray1": [],
"subArray2": []
},
"subObject2": {
"subArray3": [],
"subArray4": []
}
},
"object2": {
"subObject3": {
"subArray5": [],
"subArray6": []
}
},
"array1": [],
"array2": []
};
I have tried to use a jQuery ajax call like this:
$.ajax({
url: "test.php",
type: "POST",
dataType: "text",
processData: false,
data: obj,
success: function(data, status) {
alert("Sucsess");
}
});
The problem is that PHP doesn't receive anything. The $_POST variable is empty. I'm not sure what I'm doing wrong.
Thanks
First, include JSON2.js (Link at bottom of that page) on the page, then change your call to this:
$.post(
"test.php",
data: JSON.stringify( obj ),
function(data, status) {
alert("Sucsess");
});
Try out jQuery 1.4.1 the $.param function was completely rewritten to support things like this.
Why not send it by using something like the json2 library to serialize the whole object as JSON, then send that via a single parameter? I don't know PHP but I would be stunned if there weren't dozens of alternative JSON parsers available.
I don't believe it is possible to send a data object like that.
If you wanted to do something like that you would have to serialize it before you send the data and then unserialize at the server. HTTP has it's limits.

Categories

Resources