How to use ajax response JSON data? - javascript

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

Related

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.

Trouble retrieving data from Pocket API using jquery.post()

I'm attempting to retrieve data from my Pocket account using the Pocket API by accessing it with a jQuery post function. I have obtained the consumer key and access token and when I execute the following code I get a parseerror ...but the data shows up in JSON format in Firebug.
var myPost = $.post("https://getpocket.com/v3/get",
{ "consumer_key": "<<consumer key here>>",
"access_token": "<<access token here>>",
"count": "3",
"detailType": "simple"
},function(data) {
return data
},
"jsonp");
myPost.done(function( msg ) {
console.log(myPost)
alert(msg);
});
myPost.fail(function( jqXHR, textStatus ) {
console.log(jqXHR)
alert( "Request failed: " + textStatus );
});
If I change the dataType on the post call from "jsonp" to "json" I don't get the parse error but instead get a generic error (literally just "error") with nothing returned in teh response tab in Firebug.
Attempts to do this call using jQuery.ajax() have also failed, yielding an error 400.
var something = $.ajax({
"accepts": 'application/json',
"type": 'POST',
"url": "https://getpocket.com/v3/get",
"contentType": 'application/json; charset=UTF8',
"data": {"consumer_key": "<<insert consumer key here>>",
"access_token": "<<insert access token here>>",
"count": "3",
"detailType": "simple"},
"dataType": 'json',
"success": ""
});
Seems like I am close using $.post() but how to I clear that error so I can get the actual response data returned?

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.

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

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