According to my previous post I am trying to get back some information from a RESTful interface using JSON. I am working on JQuery 1.5.
The problem I face is that I get back as a result undefined values. I am not able to use firebug because my application is developed using PhoneGap and the app is running on the iPhone's simulator.
If I visit the RESTful interface (I type the "example.json" url in a browser - where example is a valid url created by another developer) returns me results with the following format:
[{"person":{"created_at":"2011-07-18T17:51:33Z","id":1,"name":"John","age":60,"surname":"Smith","car_id":1,"updated_at":"2011-07-18T17:51:33Z"}},{"person":{"created_at":"2011-07-18T17:51:35Z","id":1,"name":"Johnny","age":50,"surname":"Deep","car_id":2,"updated_at":"2011-07-18T17:51:35Z"}}]
I need to get the information id, name, age and store them in an array (not an html table). Just to see if the connection returns any values I use the code:
var jqxhr = $.getJSON("example.json", function(person) {
$.each(person, function(i, person) {
alert(person.name);
alert(person.age);
});
})
.success(function() { alert("second success"); })
.error(function() { alert("Cannot connect to the SWT's maps. Please try again later!"); })
.complete(function() { alert("complete"); });
So, why do I get by the alert undefined as values?
This code should work:
var jqxhr = $.getJSON("example.json", function(person) {
$.each(person, function(i, item) {
alert(item.person.name);
alert(item.person.age);
});
})
.success(function() { alert("second success"); })
.error(function() { alert("Cannot connect to the SWT's maps. Please try again later!"); })
.complete(function() { alert("complete"); });
are you sure of your code ? try:
var jqxhr = $.getJSON("example.json", function(data) {
$.each(data, function(i, item) {
alert(item.name);
alert(item.age);
});
}
Hope this helps
Related
I know this question in naive, but i stuck and new to angular. I search enough but not able to comeup with solution.
var app=angular.module('myApp',['ngResource']);
app.controller('myCtrl',['$scope','$resource',function ($scope,$resource) {
// body...
var data= $resource('http://ip/category/something',{"p1":76,"p3":9}, { charge: { method: 'POST' } });
console.log(data);
}]);
I am not able to fetch the data from the server and it return a function.
I need explanation if it is possible.
the problem you have is that the $resource service isnt a function that returns data from a request, it returns a $resource object, that has predefined methods to make those requests.
heres how you should do it to get what your looking for
var app=angular.module('myApp',['ngResource']);
app.controller('myCtrl',['$scope','$resource','$q',function($scope,$resource,$q) {
// body...
var data,
dataResource = $resource('http://ip/category/something',{"p1":76,"p3":9}, { charge: { method: 'POST' } });
data = dataResource.get();
$q.when(data.$promise).then(function(){
console.log(data);
});
}])
```
or something like that.
I am using Ajax to create comments and its not working , and i am not sure where the problem is. I am thinking it might be in the way i am reading UserID and VideoID
I have UserID saved in a session, and the videoID is saved in Query String.
am i reading them wrong?! if yes how can i read them?
here is my js code:
<script type="text/javascript">
$(document).ready(function () {
$('#btnPost').click(function (e) {
$.ajax({
url: "Ajax/ProcessAddComment.aspx",
data: {
commenttext: $('.txtcomment').val(),
videoid: Request.QueryString["d"],
userid: $.session.get('UserID')
},
success: function (data) {
alert(data);
},
error: function () {
}
});
});
$.ajax({
url: "Ajax/ProcessFindComment.aspx",
data: { videoid: Request.QueryString["id"] },
success: function (data) {
// Append to the bottom
// of list while prepend
// to the top of list
$('.postlist').html(data);
},
error: function () {
alert('Error');
}
});
});
I assume you're using this plugin to get and set your session.
I think your problem is: Request.QueryString
Try using the following JS function to get a value from the querystring rather than that:
function (key) {
if (!key) return '';
key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars
var match = location.search.match(new RegExp("[?&]" + key + "=([^&]+)(&|$)"));
return (match && decodeURIComponent(match[1].replace(/\+/g, " "))) || '';
};
Note: you can use the network tab in your developer window (F12 in most browsers) to see the Ajax data. The error console in there should tell you if there's a JavaScript error, and the network tab should tell you what was in the Ajax request and response.
I am using the following get getJSON
$.getJSON("js/production-data.json").done(function(response) {
console.log(response);
console.log('hello');
});
I can see in Firebug that the data is being retrieved, but there is no console.log for the response which would be the entire data. I can't even see hello either.
Try specifying the callback inline, like:
var jqxhr = $.getJSON( "example.json", function() {
console.log( "success" );
});
As another step, add an always handler, rather than only done.
$.getJSON("data.json", function(d) {
}).done(function(d) {
console.log("success");
}).fail(function(d) {
console.log("error");
}).always(function(d) {
console.log("complete");
});
Also get the JSON verified at JSONLint
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
I have a nested data structure / JSON, how can I access a specific value?
Basically I have a returned json object like this:
"products":[
{
"id": "21102165",
"name": "Eliza J (3/4 sleeve ruched waist dress)",
}]
My method to display it:
function getCart(){
var json = $.getJSON('https://'+storedomain+'/cart?'+fcc.session_get()+'&output=json&callback=?');
alert(json['name']);
}
However the alert displays "undefined". Where I'm I doing wrong here?
Thanks
$.getJSON return $.Deferred object and not a result
function getCart(){
$.getJSON('https://'+storedomain+'/cart?'+fcc.session_get()+'&output=json&callback=?', function(data) {
console.log(data.products[0].name);
});
}
you can do:
function getCart(){
return $.getJSON('https://'+storedomain+'/cart?'+fcc.session_get()+'&output=json&callback=?');
}
$.when(getCart()).then(function(data) {
console.log(data.products[0].name);
});
Use the success callback.
var jqxhr = $.getJSON("example.json", function(data, textStatus, jqXHR) {
alert("success");
})
.success(function(data, textStatus, jqXHR) { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
See the API documentation for getJSON.
Your method should be:
function getCart(callback) {
var url = 'https://'+storedomain + '/cart?'+fcc.session_get()+'&output=json&callback=?';
$.getJSON(url, callback);
}
// Usage
getCart(function(data) {
console.log(data.products); // array of car objects
});
Or you can use deffered object as explained in salexch answer.
You should become familiar with asynchronous nature of AJAX requests and with callback functions.
I'm using jQuery's getJSON function to return a JsonResult from my controller.
jQuery
$.getJSON("/Test/GetJsonWFA", null, function (data) {
$(data).each(function () {
alert("call succeeded");
//alert(data);
});
});
controller
public JsonResult GetJsonWFA()
{
List<WorkFlowAssignment> listWFAs = new List<WorkFlowAssignment>();
listWFAs.Add(new WorkFlowAssignment()
{
ID = 1,
WorkFlowName = "WorkFlowName1"
});
listWFAs.Add(new WorkFlowAssignment()
{
ID = 2,
WorkFlowName = "WorkFlowName2"
});
return Json(listWFAs, JsonRequestBehavior.AllowGet);
}
I'm getting the following error: 500 Internal Server Error.
If I replace the WorkFlowAssignment in GetJsonWFA with a trivial class everything works.
It seems to be related to the type of object in the list.
The WorkFlowAssignment class has many properties and methods.
Can anyone point me in the right direction?
I suspect that your WorkFlowAssignment model has some circular references which cannot be JSON serialized. I would recommend you to use a view model and break any possible circular references. Another advantage of using a view model is that you will send to the client only the properties it actually needs in order to do the processing. You don't need to transfer over the wire some complex stuff that the client will never need. So for example if everything that your client needs is the ID and the WorkFlowName do this:
public ActionResult GetJsonWFA() {
List<WorkFlowAssignment> listWFAs = ...
var viewModel = listWFAs.Select(x => new {
ID = x.ID,
WorkFlowName = x.WorkFlowName
});
return Json(viewModel, JsonRequestBehavior.AllowGet);
}
and on the client:
$.getJSON("/Test/GetJsonWFA", null, function (data) {
$.each(data, function (index, item) {
alert('ID = ' + item.ID + ', WorkFlowName = ' + item.WorkFlowName);
});
});
Also you should use debugging tools such as FireBug or Developer Toolbar to inspect the AJAX request that your browser sends and analyze the server response for eventual errors. When an AJAX request fails your first reaction as a developer should be to launch your debugging tool and see exactly what request/response is being sent.