How can I fetch json values and display in html - json

I have been killing myself over this for some time. I am looking to use the causes API to fetch some data from some of our causes we have active and display that via html.
I have created a facebook app and i'm trying to use jquery ajax. This is what I have:
<script type="text/javascript">
$(document).ready(function()
{
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%3D'http%3A%2F%2Fapi.causes.com%2Fbeneficiaries%2F1239.xml'&format=json&callback=cbfunc",
dataType: "json",
success: function(cbfunc) {
$(cbfunc).find('count').each(function(){
var total = $(this).find('total-raised').text();
$(this).html('<p>'+total+'</p>').appendTo('#listTotalDollor');
});
}
});
});
Problem is that I am not getting anything to display. Is this a crossdomain issue or is there something I missed.
Thanks!
Updated code:
<script type="text/javascript">
$(document).ready(function()
{
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22http%3A%2F%2Fapi.causes.com%2Fbeneficiaries%2F1239.json%22&format=json",
dataType: "json",
success: function(data) {
$.each(data.query.results, function(i, key) {
var total = key['total_raised'];
$("#listTotalDollar").html('<span>' + total + '</span>');
});
}
});
});
One last question to ask:
If I wanted to format one of the returning values as currency.
In my updated code I get a return of 5000 I would like it to read $5,000. Is there a good tut you can point me to?

You are mixing DOM and JSON access in you cbfunc. Assuming, that you want that total-raised number for each of the elements returned by that query, you can simple request JSON (as you do) and iterate over it accordingly.
$.ajax({
// !wrapped only for readability!
url: "http://query.yahooapis.com/v1/public/yql?
q=select%20*%20from%20xml%20where%20url%3D'\
http%3A%2F%2Fapi.causes.com%2Fbeneficiaries%2F1239.xml'\
&format=json",
dataType: "json",
success: function(data) {
// `data` is actually a json structure (as requested)
// if you want to see it as a whole, just use
// console.log(data);
// now iterate over the json structure
// (see also: http://stackoverflow.com/q/1078118/89391)
// and set your target dom element as you like
// (this is just a dummy ...)
$.each(data.query.results, function(i, key) {
var total = key['total-raised'].content;
$("target").html('<p>' + total + '</p>');
});
}
});
Here's the code I used for debugging: https://gist.github.com/850148.
For reference, here's a sketch of the response:
Object
query: Object
count: 1
created: "2011-03-01T23:24:18Z"
lang: "en-US"
results: Object
beneficiary: Object
id: Object
name: "INTERNATIONAL FELLOWSHIP OF CHRISTIANS & JEWS"
recent-facebook-donors: "time1297716630facebook_id0nameRobert \
Alan Schoonoveramount200time1297372019facebook_id0nameCurtis En…"
total-causes: Object
total-donors: Object
total-members: Object
total-raised: Object
__proto__: Object
__proto__: Object
__proto__: Object
__proto__: Object

Related

Trying to pass list of ids to the M-V-C Action through Ajax Function

I am trying to get and store the Ids of all the selected check-boxes in the JavaScript object. And then passing this object as a data to my JSON Action. I am able to successfully get the Ids of all the selected check-boxes, but when I am passing this object to my action I am getting null. Following is my code:
$("#btnSave").on('click', function () {
var selected = [];
$('input:checked').each(function () {
selected.push($(this).attr('id'));
});
$.ajax({
url: '#Url.Action("SaveRecords", "Users")',
data: { ids: selected },
cache: false,
type: "GET",
success: function (data) {}
});
});
My Action:
public JsonResult SaveRecords(List<int> ids) //Here I'm getting Null.
{
return Json(true, JsonRequestBehavior.AllowGet);
}
As suggested in the comments, since you are saving data POST is more appropriate than GET. Also, I think you will save yourself some trouble by using JSON as input - you're already using it as output format from the action. This means your AJAX call will look like this:
$.ajax({
type: 'POST',
url: '#Url.Action("SaveRecords", "Users")',
contentType: 'application/json',
data: JSON.stringify(selected),
success: function (data) { /* ... */ }
});
When I say "save yourself trouble by using JSON as input" I mean that model binding collections and complex types in MVC can be a bit tricky when sending data as a form post - google it and you'll see that there are several implementation characteristics to be aware of. In my experience, using JSON for structured data posted with AJAX just works much more like what you would expect.

AJAX/JSON MVC method not being called

The MVC controller method is not being called with the following code and the issue isn't clear. $("#screeners").val() returns a list of strings:
<script>
$(document).ready(function () {
$("#submitScreeners").click(function () {
var selected = $("#screeners").val();
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Applicant/PassScreeners',
data: "selected=" + JSON.stringify(selected),
success: function () {
$('#result').html('"PassScreeners()" successfully called.');
},
failure: function (response) {
$('#result').html(response);
}
});
});
});
</script>
Method in controller:
public void PassScreeners(List<string> selected)
{
Session["SelectedApplicants"] = selected.Select(e => Int32.Parse(e.ToString())).ToList();
}
If I understand you correctly, the "selected" parameter is being passed in as a null value. I believe this is because you are using an incorrect data format. You tell the server to expect JSON formatted data, but then pass it something more akin to a form value with '='.
Try removing the "selected=" bit from your data line and just pass the stringified list.
If that doesn't work, check the trace and post it. If the string you are posting is just comma separated or something it needs to be an array in order for the POST to work correctly.
Apologies if I've misunderstood.

Populate textbox with ajax call to server

I have first and last name text boxes, last name on blur triggers an ajax call to get additional data to fill in other textboxes. The call is made and I can see in the Chrome dev tool (network tab) that a json string is coming back with all the data, but I can't figure out how to populate the text fields.
ajax function:
$(function() {
$("#LastName").on('blur', function () {
var first = $("#FirstName").val();
var last = $("#LastName").val();
$.ajax({
url: '#Url.Action("SearchEmployee", "Employee")',
type: "GET",
datatype: 'json',
data: { 'firstName': first, 'lastName': last },
success: function (data) {
alert(data.ManagerFirst);
$("#ManagerFirst").val(data.ManagerFirst);
$("#ManagerLast").val(data.ManagerLast);
},
error: function () { alert("Huh? What? What did you need?.") }
});
})
})
returns something like this:
{"EmployeeId":0,"FirstName":"Bob","LastName":"Smith","EmailAddress":null,"ManagerEmail":"Boss.Man#work.org","ManagerId":null,"ManagerFirst":"Boss","ManagerLast":"Man"}
The 'alert' shows "undefined".
You may just have a typo. Try changing "datatype" to "dataType"
You are trying to alert a data member of the response string, which does not exist. Instead, you should try to convert the string to object, like this:
$(function() {
$("#LastName").on('blur', function () {
var first = $("#FirstName").val();
var last = $("#LastName").val();
$.ajax({
url: '#Url.Action("SearchEmployee", "Employee")',
type: "GET",
datatype: 'json',
data: { 'firstName': first, 'lastName': last },
success: function (data) {
//converting it to object, since further rows expect this
data = $.parseJSON(data);
alert(data.ManagerFirst);
$("#ManagerFirst").val(data.ManagerFirst);
$("#ManagerLast").val(data.ManagerLast);
},
error: function () { alert("Huh? What? What did you need?.") }
});
})
})
EDIT:
As Bryan Lewis pointed out, it was a typo. This has led to the behavior about which I have written my answer.
Turns out the problem was the server was returning an array of employee objects, so had to access it like:
data[0].ManagerFirst ... etc.
There was no way to tell that from the data I posted, so my apologies.
fyi, once I added that fix, I changed the the dataType param back to 'datatype' and it still worked fine.

json returns [object Object] instead of actual data

I have refered many questions on stack overflow and on other sites for the solution. But everywhere I got incomplete answer. some answer says log the json data to console. So I tried it and there I get the json object correctly. But when I add it to HTML or alert it says [object Object].
There are many duplicates of this question but still I dont understand what the problem is?
Here is my code so far
$(document).click(function () {
$.ajax({
type: "POST",
url: "/members/ListOfAllOppositeTypeUsersWithTheirRespectiveData?LoggedInUserOppositeType=2",
dataType: 'json',
success: function (json) {
console.log(json);
//var strJson = JSON.stringify(json);
$.each(json, function (key, value) {
$('#AllowedFriends').append($('<option value="'+ key + '">' + value + '</option>'));
});
},
error: function () {
alert("F");
}
});
});
edit :
The values that I get in the console :
0: Object
MemberID: 1
Name: "Cipla"
1: Object
MemberID: 2
Name: "Himalaya"
You should try something like:
$.each(json, function (index, obj) {
$('#AllowedFriends').append($('<option value="'+ obj.MemberId + '">' + obj.Name + '</option>'));
});
An object can contain actual data, what is the problem? I suggest you take a look at the network calls from your browser using the developer console or Firebug to see what object is received. Then jQuery parses the string into an object so you can use the data.
Try console.log(eval('('+json+')'));

load data from json into extjs

i want to load one value from a json into a var in an extjs app. The json output looks like this
{"rechten":[{"name":"baas"}]}
If i want to use it in a store i know what to do but i use that only for grids before. I want a var like this
var rechten = "baas";
so i can check this into something else:
if(rechten == "baas") { alert('je bent de baas') }
else { alert('helaas je bent arbeider')};
so my question is how can i check the name value from that json in this if else statement?
You can load your data into a store (eg. store.load()) and then check for the value via standard store methods (eg. store.getAt()).
Or you can use Ext.Ajax and Ext.JSON it will look like this
Ext.Ajax.request({
url: 'someurl',
success: function(response){
var decoded = Ext.JSON.decode(response.responseText);
console.log(decoded.rechten.name);
}
});
Second method will skip required model/store declaration and will be out of EXTJS MVC data concept, but for quick and easy data processing should be fine to use.
Ext.Ajax.request({
url: 'your_url_here',
success: function(response, opts) {
var o = Ext.decode(response.responseText);
alert(o.rechten[0].name); // alerts "baas"
},
failure: function(response, opts) {
console.log('server-side failure with status code ' + response.status);
}
});
If your json string were to come from a file named page-with-rechten.xyz this snippet could call that file and then decode the text creating a JavaScript object you could then use properties of.
You can inspect the rechten object in the console and then add the additional logic you
Ext.Ajax.request({
url: './page-with-rechten.xyz',
success: function(response){
var text,
rechten;
text = response.responseText;
console.log('response text: ', text);
rechten = Ext.decode(text);
console.log('rechten object: ', rechten);
}
});