Not able to access JSON data in ajax jquery - javascript

I have a Jquery AJAX POST method.Which call a web method of asp.net.
The ajax method get a json data.
The data format is :
[
{
"Title": "Test2",
"Name" : "AMIT",
"IsRoot": "True"
},
{
"Title": "Test3",
"Name" : "AMIT1",
"IsRoot": "False"
},
{
"Title": "Test4",
"Name" : "AMIT2",
"IsRoot": "True"
}
]
I validate the dataformat in "http://jsonlint.com/" site and it's telling that dataformat is correct.
I want to loop through the data and access each of the attribute.But I am not able to get that.
I try to find the total array length which should be 3.But it's giving me 9(means each attribute )
I try
alert(data.d.length); // giving 9 (should give 3)
var jsondata = data.d;
alert(jsondata[1].Title); //undefined (should give Test3)
alert(jsondata[2].Title); //undefined (should give Test4)
alert(jsondata[1].Name); //undreined (should give AMIT1)
var key, count = 0;
for (key in data.d) {
if (data.d.hasOwnProperty(key)) {
count++;
}
}
alert(count); // giving 9 (should give 3)
any help is highly accepted.
My ajax calling method is
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebForm1.aspx/GetRootData",
dataType: "json",
success: function (data, textStatus) {
var jsondata = data.d;
alert(jsondata[1].Title);
alert(jsondata[2].Title);
alert(jsondata[1].MimeType);
var key, count = 0;
for (key in data.d) {
if (data.d.hasOwnProperty(key)) {
count++;
}
}
alert(count);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}
});
and don't know why debugger also not working.. :(

Thanks everyone.Finally I solved the problem.
the solution is
var jsonObject = eval(data.d);
Now it's returning all the data fine..
alert(jsonObject.length); //Now it's returning 2
alert(jsonObject[1].Title); // it's returning Test3 now.
Thanks..

Related

How to limit a JS Object to be posted via ajax

I have an application that sends a message through JSON via ajax. This is the JS object:
var message = {
"message_by": colmn[0].innerHTML,
"message_date": new Date(),
"message_recipients": [
{
"phone_number": colmn[1].innerHTML,
"recipient_name": colmn[2].innerHTML
}
],
"message_text": colmn[3].innerHTML,
"subscriber_name": "John Doe"
};
Which is then posted like so:
var url = "http://url/api/sendMessage";
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(message),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
console.log(data);
console.log(status);
console.log(jqXHR);
//alert("success..." + data);
alert("Success. Message sent.");
},
error: function (xhr) {
//alert(xhr.responseText);
alert("Error. Try again.");
}
});
The stringified message could look like this for example:
var message = {
"message_by": "Brian",
"message_date": new Date(),
"message_recipients": [{
"phone_number": "0700111222",
"recipient_name": "Timothy"
}, {
"phone_number": "0800222111",
"recipient_name": "Winnie"
}],
"message_text": "Hello! You are invited for a cocktail at our auditorium. ",
"subscriber_name": "John Doe"
}
Now to the problem. The messages are posted to the api just fine but recently noticed some messages failing and discovered the failed messages had 100 message recipients or more. It works fine up to 99. I asked a colleague and he said there weren't any limit restrictions set on the api.
Is there a way I could limit the object size to 99 and push the remainder to a new object but still have it as part of the same ajax post? Is there any other creative way around this?
There is no such limit.
If you want to restrict your message recipients to 99 you can do as follows
validateMessege(message){
var length = message.length;
var messegeRep = message.message_recipients.slice()
for(var i = 0; i < length; i+=99){
message.message_recipients = messageRep.slice(i, i+99)
// Your post request here
}
}

How to read data from json format using jquery

How to read data from json format using jquery. below is what i have tried, but unfortualtly i couldn't able to read exact data which i want.
$.ajax({
url: '#Url.HttpRouteUrl("GetDistrictList", new { })',
type: 'GET',
datatype: "json",
success: function (data, txtStatus, xhr) {
console.log(data);
if (data != null) {
$.each(data, function (i, item) {
alert(data[0]);
alert(data[0].DistrictCode)
alert(item);
alert(item[0]);
alert(item.DistrictCode);
$('#tblDistricts > tbody').append('<tr><td>'+item.DistrictCode+'</td><td>test</td><td>test</td><td>test</td><td>test</td><td>test</td></tr>');
})
}
},
error: function (xhr, textStatus, errorThrown) {
console.log("error in GetDistrictList : " + errorThrown);
}
});'
In alert box , I'm getting 'undefined' or '[object] [Object] only, I could not able to read exact data. I got stuck here.
Edit:
Web api will return the data as List objects.
[HttpGet]
[Route("GetDistrict/", Name = "GetDistrictList")]
public List<DistrictModels> GetDistrictList()
{
BAL_District oBAL_District = new BAL_District();
return oBAL_District.GetDistrictList();
}
Use var Data = $.parseJSON(response);
Example
var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" );
JSON.stringify turns a Javascript object into JSON text and stores that JSON text in a string.
JSON.parse turns a string of JSON text into a Javascript object.
How to access JSON object
FYI, as of jQuery 3.0, $.parseJSON is deprecated. To parse JSON objects, use the native JSON.parse method instead.
var json = [
{ 'red': '#f00' },
{ 'green': '#0f0' },
{ 'blue': '#00f' }
];
$.each(json, function () {
$.each(this, function (name, value) {
console.log(name + '=' + value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I think you wish to call this function -
http://api.jquery.com/jquery.parsejson/
if you are getting [object,object] it means you have already fetched the Json Object. And if you need some clarifications, please share the expected Json you want.Thanks
Use JSON.stringify(object). It is super safe way to print out.
$.ajax({
url: '#Url.HttpRouteUrl("GetDistrictList", new { })',
type: 'GET',
datatype: "json",
success: function (data, txtStatus, xhr) {
console.log(data);
if (!!data) {
// '!data' means data variable is not available and '!!data' returns true:boolean if variable is valid
//idx is 'index', I made the code as a loop. It will not work if array is empty.
//It is good way to avoid error
for(var idx in data){
if(idx == 0) {
//JSON.stringify makes object type to string type. It is safe to use since it is a native javascript function
alert(JSON.stringify(data[idx]);
//You can access member by 'data[idx].memberName'
//DOM adding code can be here
}
}
}
},
error: function (xhr, textStatus, errorThrown) {
console.log("error in GetDistrictList : " + errorThrown);
}
});
Assuming your server side script doesn't set the proper Content-Type: application/json response header you will need to indicate to jQuery that this is JSON by using the dataType: 'json' parameter.
You should not use data variable in $.each(). Then you could use the $.each() function to loop through the data:
$.ajax({
url: '#Url.HttpRouteUrl("GetDistrictList", new { })',
type: 'GET',
datatype: "json",
success: function (data, txtStatus, xhr) {
console.log(data);
if (data != null) {
$.each(data, function (index, element) {
alert(element);
alert(element[0]);
alert(element.DistrictCode);
$('#tblDistricts > tbody').append('<tr><td>'+element.DistrictCode+'</td><td>test</td><td>test</td><td>test</td><td>test</td><td>test</td></tr>');
});
}
},
error: function (xhr, textStatus, errorThrown) {
console.log("error in GetDistrictList : " + errorThrown);
}
});'
or use the $.getJSON method:
For example:
$.getJSON('/functions.php', { get_param: 'value' }, function(data) {
$.each(data, function(index, element) {
$('body').append($('<div>', {
text: element.name
}));
});
});
Note: As of jQuery 3.0, $.parseJSON is deprecated. To parse JSON objects, use the native JSON.parse method instead.

javascript check if JSON key exists and display the value

I've been tinkering with Z-Wave lately and I'm trying to make a page to include/exclude their products. But it's not going too well. I'm trying to check if a JSON key exists then display it on the page. I get
TypeError: data.controller is undefined
Here is the code:
window.setInterval(function(){
getData();
}, 2000);
function getData()
{
var milliseconds = (new Date).getTime();
var time = milliseconds.toString().substr(0, milliseconds.toString().length - 3) ;
$.postJSON( "http://192.168.1.102:8083/ZWaveAPI/Data/" + time, function( data ) {
if(data.controller.lastExcludedDevice.value) alert("EXCLUDED SOMETHING");
if(data.controller.lastIncludedDevice.value) alert("INCLUDED SOMETHING");
});
}
$.postJSON = function(url, data, callback, sync) {
// shift arguments if data argument was omited
if ( jQuery.isFunction( data ) ) {
sync = sync || callback;
callback = data;
data = {};
};
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
success: callback,
error: callback,
async: (sync!=true)
});
};
Json:
{
"controller.data.controllerState": {
"value": 0,
"type": "int",
"invalidateTime": 1424781697,
"updateTime": 1425338938
},
"controller.data.lastIncludedDevice": {
"value": 42,
"type": "int",
"invalidateTime": 1424781697,
"updateTime": 1425338938
},
......
Any help is greatly appreciated.
if the dots are part of the key you need to use the [] notation.
for example
if (data['controller.data.controllerState'].value) ...
or
if (data['controller.data.lastIncludedDevice'].value) ...
Try this:
if(data.controller &&
data.controller.lastExcludedDevice.value)
alert("EXCLUDED SOMETHING");
Think of it this way: console.log({}.x) prints "undefined." console.log({}.x.y) throws an error. You're allowed to work with undefined but it throws an error if you try to access properties of it.
Use the short-circuiting property of && to expedite this check:
if(a && a.b && a.b.c && a.b.c.d) {
console.log("Not an error to print", a.b.c.d);
}{

Success or error call back in AJAX not working

$(document).ready(function () {
$("#loginForm").submit(function (e)
{
var Data = $(this).serializeArray();
var formURL = $(this).attr("action");
var PostData =
{
"CompanyName": $(this).serializeArray().CompanyName,
"Username": $(this).serializeArray().Username,
"Password": $(this).serializeArray().Password
}
$.ajax(
{
url: formURL,
data: PostData,
success: function (data, textStatus, jqXHR) {
alert("Data" + data);
alert("Jq" + jqXHR);
alert("textStatus" + textStatus);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Failed..ajax error response type " + textStatus);
}
});
e.preventDefault(); //STOP default action
})
});
$("#loginForm").submit(); //SUBMIT FORM
This is a simple Ajax request to the C# code,that i have.I know for sure that the C# is giving a correct value(according to the situation).
C# return true or false as per the situation.But in any case this Ajax script neither giving me a alert window which i have coded for.
Instead i get this response from
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<boolean xmlns="http://schemas.microsoft.com/2003/10/Serialization/">false</boolean>
When false and just the value in the tag changes when its true.
Can anyone tell me why neither success or error is not working.
Something that make work better is this:
$("#loginForm").submit(function (event) {
event.preventDefault();
$.post($(this).attr("action"), $(this).serialize())
.done(function (results) {
alert(results);
})
.fail(function (error) {
alert(error);
})
.always(function () {
alert("AJAX Complete");
});
});
As you can tell from it's name the .serializeArray() method returns an array -- not an object. The array is of the form:
[
{
name: "a",
value: "1"
},
{
name: "b",
value: "2"
},
{
name: "c",
value: "3"
}
]
array of objects
Ref: http://api.jquery.com/serializearray/
What you need: http://api.jquery.com/serialize/
Therefore to access the third value you would need to supply the index 2 -- ..[2].value ... name ...[2].name. Your code has errors that would prevent the ajax call from being made. Is it possible that error is coming from somewhere else?
Therefore change:
var PostData =
{
"CompanyName": $(this).serializeArray().CompanyName,
"Username": $(this).serializeArray().Username,
"Password": $(this).serializeArray().Password
}
To:
var PostDate = $(this).serialize();

Scraping JSON data from an AJAX request

I have a PHP function that echoes out JSON data and pagination links. The data looks exactly like this.
[{"name":"John Doe","favourite":"cupcakes"},{"name":"Jane Citizen","favourite":"Baked beans"}]
Previous
Next
To get these data, I would use jQuery.ajax() function. My code are as follow:-
function loadData(page){
$.ajax
({
type: "POST",
url: "http://sandbox.dev/favourite/test",
data: "page="+page,
success: function(msg)
{
$("#area").ajaxComplete(function(event, request, settings)
{
$("#area").html(msg);
});
}
});
}
Using jQuery, is there anyway I can scrape the data returned from the AJAX request and use the JSON data? Or is there a better way of doing this? I'm just experimenting and would like to paginate JSON data.
It's better to not invent your own formats (like adding HTML links after JSON) for such things. JSON is already capable of holding any structure you need. For example you may use the following form:
{
"data": [
{"name": "John Doe", "favourite": "cupcakes"},
{"name": "Jane Citizen", "favourite": "Baked beans"}
],
"pagination": {
"prev": "previous page URL",
"next": "next page URL"
}
}
On client-side it can be parsed very easily:
$.ajax({
url: "URL",
dataType:'json',
success: function(resp) {
// use resp.data and resp.pagination here
}
});
Instead of scraping the JSON data i'd suggest you to return pure JSON data. As per your use case I don't think its necessary to write the Previous and Next. I am guessing that the first object in your return url is for Previous and the next one is for Next. Simply return the below string...
[{"name":"John Doe","favourite":"cupcakes"},{"name":"Jane Citizen","favourite":"Baked beans"}]
and read it as under.
function loadData(page){
$.ajax
({
type: "POST",
url: "http://sandbox.dev/favourite/test",
dataType:'json',
success: function(msg)
{
var previous = msg[0]; //This will give u your previous object and
var next = msg[1]; //this will give you your next object
//You can use prev and next here.
//$("#area").ajaxComplete(function(event, request, settings)
//{
// $("#area").html(msg);
//});
}
});
}
This way return only that data that's going to change not the entire html.
put a dataType to your ajax request to receive a json object or you will receive a string.
if you put "previous" and "next" in your json..that will be invalid.
function loadData(page){
$.ajax({
type: "POST",
url: "http://sandbox.dev/favourite/test",
data: {'page':page},
dataType:'json',
success: function(msg){
if(typeof (msg) == 'object'){
// do something...
}else{
alert('invalid json');
}
},
complete:function(){
//do something
}
});
}
and .. in your php file, put a header
header("Content-type:application/json");
// print your json..
To see your json object... use console.log , like this:
// your ajax....
success:(msg){
if( window.console ) console.dir( typeof(msg), msg);
}
Change your json to something like this: (Use jsonlint to validate it - http://jsonlint.com/)
{
"paginate": {
"previous": "http...previsouslink",
"next": "http...nextlink"
},
"data": [
{
"name": "JohnDoe",
"favourite": "cupcakes"
},
{
"name": "JaneCitizen",
"favourite": "Bakedbeans"
}
]
}
You can try this :-
var jsObject = JSON.parse(your_data);
data = JSON.parse(gvalues);
var result = data.key;
var result1 = data.values[0];

Categories