How to parse json response in jQuery mobile? - javascript

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.

Related

extract an URL from a JSON response of wikipedia api

I need to extract the URL of an image from a JSON response (maybe I could put it in a variable).
I read this page on the MediaWiki API help
I follow this example to get the information about images on a page:
https://commons.wikimedia.org/w/api.php?action=query&prop=pageimages&titles=Albert%20Einstein&pithumbsize=100
that return this JSON:
{
"batchcomplete": "",
"query": {
"pages": {
"2061": {
"pageid": 2061,
"ns": 0,
"title": "Albert Einstein",
"thumbnail": {
"source": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Albert_Einstein_Head.jpg/75px-Albert_Einstein_Head.jpg",
"width": 75,
"height": 100
},
"pageimage": "Albert_Einstein_Head.jpg"
}
}
}
In which way can I extract the URL of the image?
I tried this:
$.ajax({
type:"get",
url:"https://commons.wikimedia.org/w/api.php?action=query&prop=pageimages&titles=Albert%20Einstein&pithumbsize=100&format=json",
dataType:"jsonp",
contentType:"application/json; charset=utf-8",
success: function(data) {
var urlImage = data.query.pages.2061.thumbnail.source;
var stgurl = JSON.stringify(urlImage);
alert(stg);
}
})
but doesn't work.
Yes, it doesn't work because this url: https://commons.wikimedia.org/w/api.php?action=query&prop=pageimages&titles=Albert%20Einstein&pithumbsize=100 doesn't return JSON but HTML. If you want the JSON representation, you need to append &format=json to your url.
Change data.query.pages.2061.thumbnail.source to data.query.pages["2061"].thumbnail.source as you can't use numbers in a dot notation.
And also the alert; change stg to stgurl
$.ajax({
type:"get",
url:"https://commons.wikimedia.org/w/api.php?action=query&prop=pageimages&titles=Albert%20Einstein&pithumbsize=100&format=json",
dataType:"jsonp",
contentType:"application/json; charset=utf-8",
success: function(data) {
var urlImage = data.query.pages["2061"].thumbnail.source;
//var stgurl = JSON.stringify(urlImage); - unnecessary JSON.stringify
var stgurl = urlImage;
alert(stgurl);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I tried to use the solution in this post:
iterating through json object javascript
Use the recursion in this way:
function walk(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
console.log(val);
walk(val);
}
}
}
walk(obj);
it seems to work.

Accessing elements in single Json Object

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);

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.

Fetching JSON data from a URL in javascript?

I am trying to retrieve data from a URL of the form http://www.xyz.com/abc.json.
I have been trying to achieve this using the $.ajax method in the following manner.
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "http://www.xyz.com/abc.json.",
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})();
However I am being unable to get this to run. I need to loop through the retrieved data and check for some specific conditions. This could have been achieved easily with the $.getJSon if the json data had a name to it, however the file is of the form:
[{
"name": "abc",
"ID": 46
}]
because of which I have to effectively convert and store it in a Javascript object variable before I can use it. Any suggestions on where I might be going wrong?
It looks like you will want to convert that data response to a json object by wrapping it with { } and then passing that to the json parser.
function (data) {
json = JSON.parse("{\"arr\":"+data+"}").arr;
}
Then to get your data, it would be
json[0].name //"abc"
So your question is how to convert a string to Json object?
If you are using Jquery you can do:
jQuery.parseJSON( jsonString );
So your return should be:
return jQuery.parseJSON( json );
You can read documentation here

Javascript alert if JSON response has designated row

I'm trying to build an app that gets JSON from server and then shows a javascript alert if the JSON response has designated row. The JSON I get from server looks like this:
{
"key": [
{
"IND": "406",
"NUMBER": "9",
"MESSAGE": "this is a test",
"status": "ok"
}
]
}
And this is the code I use to show the alert:
function UpdateRecord(update_id) {
var id = getUrlVars()["id"];
jQuery.ajax({
type: "POST",
url: serviceURL + "test.php",
data: 'id=' + id,
cache: false,
success: function(data) {
if (data.status == 'ok') {
alert(data.message);
} else {
alert("no");
}
}
});
}​
But this code alerts "no" even though the JSON has a row "status": "ok"
Try with if (data.key[0].status), and replace alert(data.message) with alert(data.key[0].MESSAGE). You have to be careful with capitalization!
you have "key" defined in your jSON, sohould it not be
if(data.key[0].status == "ok")
Do a console.log(data) in the success handler to see what the data is. You will see that there is no data.status, but instead it would be data.key[0].status.

Categories

Resources