Reading a JSON object - javascript

I have a Service which returns JSON using C#'s JavaScriptSerializer class.
jQuery
$.get('GlobalService/Index',
{ crudOperation: crudOperation,
globalType: globalType,
globalObject: globalObject
},
function (data) {
alert(data);
});
the callback function displays in the alert
[object XMLDocument]
How do I get to and parse the JSON object? The object has basic construction
{"field1":"data","field2":"more data",/*...~10 more of these*/}

$.get('GlobalService/Index',
{
crudOperation: crudOperation,
globalType: globalType,
globalObject: globalObject
},
function (data) {
// access it as you would normally access a JS object
alert(data.field1);
},
'json'); // do not forget to pass the json data type here, otherwise it
// will just guess it (probably wrong, as it shows in your case)

Easiest way.
#see getJSON
also,
parseJSON

Your code is working fine, just an alert cannot show the object data:
$.get('GlobalService/Index',
{ crudOperation: crudOperation,
globalType: globalType,
globalObject: globalObject
},
function (data) {
console.log(data); //view data in console
alert(data.field1);
});

You must specify a dataType of "json" in order to let the method know how parse the returned data:
$.get('GlobalService/Index',
{ crudOperation: crudOperation,
globalType: globalType,
globalObject: globalObject
},
function (data) {
alert(data);
}, 'json');
See $.get() documentation at jQuery: http://api.jquery.com/jQuery.get/.
Note that if you don't specify dataType, jQuery will do a smart guess of what the server is returning and it is very clear that it is misunderstanding the server response with an XML block of code.

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.

Unable to get value from json object

I am trying to get a value from a json object after making an ajax call. Not sure what I am doing wrong it seems straight forward but not able to get the data
The data that comes back looks like this
{"data":"[{\"Id\":3,\"Name\":\"D\\u0027Costa\"}]"}
The code, removed some of the code
.ajax({
type: 'POST',
url: "http://localhost:1448/RegisterDetails/",
dataType: 'json',
data: { "HomeID": self.Id, "Name": $("#txtFamilyName").val()},
success: function (result) {
console.log(result.data); //<== the data show here like above
alert(result.data.Id); //<==nothing show
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I tried in the Chrome console like this
obj2 = {}
Object {}
obj2 = {"data":"[{\"Id\":3,\"Name\":\"D\\u0027Costa\"}]"}
Object {data: "[{"Id":3,"Name":"D\u0027Costa"}]"}
obj2.data
"[{"Id":3,"Name":"D\u0027Costa"}]"
obj2.data.Id
undefined
obj2.Id
undefined
Update
The line that solved the issue as suggested here is
var retValue = JSON.parse(result.data)[0]
Now I can used
retValue.Name
to get the value
Actually, looking at this, my best guess is that you're missing JSON.parse()
.ajax({
type: 'POST',
url: "http://localhost:1448/RegisterDetails/",
dataType: 'json',
data: { "HomeID": self.Id, "Name": $("#txtFamilyName").val()},
success: function (result) {
var javascriptObject = JSON.parse(result);
console.log(javascriptObject ); //<== the data show here like above
alert(javascriptObject.Id); //<==nothing show
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I also find that doing ajax requests like this is better:
var result = $.ajax({
url: "someUrl",
data: { some: "data" },
method: "POST/GET"
});
result.done(function (data, result) {
if (result == "success") { // ajax success
var data = JSON.parse(data);
//do something here
}
});
For clarity it just looks better, also copying and pasting into different functions as well is better.
The id property is in the first element of the data-array. So, alert(result.data[0].Id) should give the desired result. Just for the record: there is no such thing as a 'JSON-object'. You can parse a JSON (JavaScript Object Notation) string to a Javascript Object, which [parsing] supposedly is handled by the .ajax method here.
The data field is just a string, you should parse it to a JSON object with JSON.parse(result.data), since data is now an array you will need to need to use an index [0] to have access to the object. Know you will be able to get the Id property.
JSON.parse(result.data)[0].Id

Using data returned from AjaxSubmit

I am trying to get access to the data returned from an ajaxSubmit request.
$("#searchbutton").on('click', function() {
$("#searchform").ajaxSubmit({
success: function(data) {
populate('#registrationform', data);
},
resetForm: true
});
});
The data that is returned is not being recognise by my populate function, If i do however with raw data,
$("#searchbutton").on('click', function() {
$("#searchform").ajaxSubmit({
success: function(data) {
populate('#registrationform', {studentId: 1, firstName: 'Kay'});
},
resetForm: true
});
});
my populate function works. Any ideas why the data returned is not recognised?
My guess is that the data is actually coming back as a String, NOT a JavaScript object. If you are inspecting with console.log(data), this distinction would be very easy to miss.
Looking at the documentation for the success method and the dataType option, it is quite possible that your server's response is being taken for a simple String. Try explicitly setting dataType: "json" and see what comes back. That, or deserialize to an object with JSON.parse().
Use it like,
$("#searchbutton").on('click', function() {
$("#searchform").ajaxSubmit({
success: function(data) {// data should be return as json
populate('#registrationform',{studentId: data.id, firstName: data.name});
},
resetForm: true
});
});

Get values from object using Backbonejs

i want to get value from this API http://demo82.com/lois/api/get_page/?id=6 using Backbone js. i tried but i don't know how can we get values from object in backbone.
here is my Backbone code
Page = Backbone.Model.extend({
initialize: function() {
this.on('all', function() { console.log(this.get('page')); });
},
url: "http://demo82.com/lois/api/get_page/?id=6",
defaults: {
"id":null,
"title":"",
"content":""
}
});
var page = new Page();
console.log(page.fetch({}));
i am new and try to learn backbonejs please explain what is the better way ? please give me ans using jsfiddle.net.
thanks
Is id always going to be 6? In your code, your model is always getting the 6th thing. If you want a custom url with a get parameter, override url as a function:
url: function() {
id = this.get("id");
return "loispage/api/get_page/?id=" + id
}
Better yet, if you have control over the server side and can do something a little more RESTful with a page entity -- simply set urlRoot
urlRoot: "loispage/api/page/"
and fetch will automatically do an HTTP get from
"http://.../loispage/api/page/<id>
It looks like a context problem (this doesn't refer to the model in on's callback). You can fix this by specifying the context:
this.on('all',
function() { console.log(this.get('pagel')); },
this
);
Edit
There's also a cross-domain issue. You'll need to use a JSONP request for this by overriding sync and parse. (I adapted the following code from this example.)
var Page= Backbone.Model.extend({
// override backbone synch to force a jsonp call
sync: function(method, model, options) {
// Default JSON-request options.
var params = _.extend({
type: 'GET',
dataType: 'jsonp',
url: model.url(),
processData: false
}, options);
// Make the request.
return $.ajax(params);
},
parse: function(response) {
// parse can be invoked for fetch and save, in case of save it can be undefined so check before using
if (response) {
console.log(JSON.stringify(response));
// here you write code to parse the model data returned and return it as a js object
// of attributeName: attributeValue
return { status: response.status }; // just an example
}
},
Here's a JSFiddle demo.

Send array with $.post

I'm trying to execute a $.post() function with an array variable that contains the data, but it seams that I'm doing something wrong because it won't go or it's not possible
var parameters = [menu_name, file_name, status, access, parent, classes];
console.log(parameters);
$.post('do.php', { OP: 'new_menu', data: parameters }, function(result) {
console.log(result);
}, 'json'); //Doesn't work
Firebug debug: NS_ERROR_XPC_BAD_CONVERT_JS: Could not convert JavaScript argument
So, which would be the propper way of doing it (if possible)?
i am using for such kind of issues always the $.ajax form like this:
$.ajax({
url: 'do.php',
data: {
myarray: yourarray
},
dataType: 'json',
traditional: true,
success: function(data) {
alert('Load was performed.');
}
});
the traditional is very important by transfering arrays as data.
Could be the variables in the parameters array
Having ran your code and supplemented the parameters for something like:
var parameters = ['foo','bar'];
It seems to work fine. I think the problem must be in the variables that you are passing as part of the array. i.e. are menu_name, file_name, status, access, parent and classes variables all as you expect them to be? e.g. console log them and see what they are coming out as. One might be an object which doesn't convert to json.
Use JSON.stringify()
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify
$.post('do.php', {
OP: 'new_menu',
data: JSON.stringify(parameters)
},
function(result) {
console.log(result);
},
'json'
);
And then, in the server-side use json_decode() to convert to a php array.
http://php.net/manual/es/function.json-decode.php
Ok, so with the help of these StackOverflow fellows I managed to make it work just the way I wanted:
var parameters = {
'name': menu_name.val(),
'file': file_name.val(),
'status': status.val(),
'group': group.val(),
'parent': parent.val(),
'classes': classes.val()
};
$.post('do.php', { OP: 'new_menu', data: parameters }, function(result) {
console.log(result);
}, 'json');

Categories

Resources