Weird JSON, how to access needed value - json

This is the JSON response:
I need to access data[1], which is 0.2. How do I get it?
Here's the actual code:
function getTheValue(){
var result = $.ajax({ url: "https://www.blahblah.com/json" });
return result;
}
console.log(getTheValue());
Here's another way I tried, no luck:
var val = getTheValue();
console.log(val.responseJSON.dataset.data[0][1]);

Your getTheValue function is not returning the JSON response from the AJAX call. It is returning a promise object, since it is actually a doing an asynchronous call. I suggest you read documentation for jQuery.ajax() for more information.
Anyway, you can fix your problem by doing this:
var val;
getTheValue().done(function(response) {
val = response.dataset.data[0][1];
});

The response you're seeing is the ajax object, not the return from the function. $.ajax is asynchronous, so the value isn't available until immediately.
Adapted from the jQuery docs:
$.ajax({
url: your_url,
})
.done(function( result ) {
console.log( result );
});
will give you result. Your subsequent code will need to be triggered inside that done() function.

This finally helped me:
var tBill = getTheBill();
function getTheBill(){
var result;
$.ajax
({
url: "https://www.blahblah.com/json",
context: document.body,
async: false
}).done(function(val) {
result = val;
});
return result.dataset.data[0][1];
}
Guys, thanks for your help! jimm101, you rock.

That object isn't json in its common sense but an Javascript object, if you want the ajax result you have to use a callback:
$.ajax({
url: "https://www.blahblah.com/json" ,
dataType: "json",
})
.done(function(data) {
console.log(data);
});

Related

Printing JSON data member into console with angular.js

I want to access JSON object member using angularjs. I can print the whole json object array but can't access the member of the object uniquely.
$scope.rows = []; // init empty array
$scope.datainput =[];
$http({
method: 'GET',
url: 'Data/input.json'
}).then(function (data){
$scope.datainput=data;
//console.log($scope.datainput);
console.log($scope.datainput);
},function (error){
console.log("big error");
});
var json=JSON.parse($scope.datainput);
console.log(json[0].status);
I have tried this code also but still geting the same error .
$scope.temp = "";
$scope.rows = []; // init empty array
$scope.datainput =[];
$http({
method: 'GET',
url: 'Data/input.json'
}).then(function (data){
$scope.datainput=data;
//console.log($scope.datainput);
console.log($scope.datainput);
var json=JSON.parse($scope.datainput);
console.log(json[0].status);
},function (error){
console.log("big error");
});
json file input.json:
[
{"status":"payfail","value":"310"},
{"status":"payinit","value":"100"},
{"status":"paysuccess","value":"200"},
{"status":"payreturn","value":"50"}
]
I get this error :
SyntaxError: Unexpected end of JSON input
at JSON.parse ()
The solution will be this....
$scope.rows = []; // init empty array
$scope.datainput =[];
$http({
method: 'GET',
url: 'Data/input.json'
}).then(function (data){
$scope.datainput=data.data;
//console.log(data);
console.log($scope.datainput);
var json=JSON.parse(JSON.stringify($scope.datainput));
console.log(json[0].status);
},function (error){
console.log("big error");
});
My guess would be that you are trying to parse the JSON string before it has been returned by the promise.
Try putting your parsing code inside the then block so that it executes in the correct order.
Upon further investigation, here is an updated Answer:
In addition to fixing the promise execution order, it turns out there is an issue with the way that you are accessing the data on the response variable.
Check the documentation for $http here: W3Schools.com $http doco
You will see that the callback response value actually contains a member called data for the response payload. To get this working try accessing the data member on the response object.
$scope.datainput=data.data;
It would probably be a good idea to also rename the data response object from data to response for readability.
You can use this code to solve that:
$scope.rows = []; // init empty array
$scope.datainput =[];
$http({
method: 'GET',
url: 'Data/input.json'
}).then(function (data){
$scope.datainput=data.data;
console.log($scope.datainput);
var json= angular.fromJson($scope.datainput);
console.log(json[0].status);
},function (error){
console.log("big error");
});
You should'n write Json.Parse out function Get you should write this code inside the then block and use data.data to get the data from json file.

Wrong data format for store loadData method ExtJS

I want to call JSON data as much as the amount of data in the store. Here is the code:
storeASF.each(function(stores) {
var trano = stores.data['arf_no'];
Ext.Ajax.request({
results: 0,
url: '/default/home/getdataforeditasf/data2/'+trano+'/id/'+id,
method:'POST',
success: function(result, request){
var returnData = Ext.util.JSON.decode(result.responseText);
arraydata.push(returnData);
Ext.getCmp('save-list').enable();
Ext.getCmp('cancel-list').enable();
},
failure:function( action){
if(action.failureType == 'server'){
obj = Ext.util.JSON.decode(action.response.responseText);
Ext.Msg.alert('Error!', obj.errors.reason);
}else{
Ext.Msg.alert('Warning!', 'Server is unreachable : ' + action.response.responseText);
}
}
});
id++;
});
storeARF.loadData(arraydata);
StoreASF contains data[arf_no] which will be used as a parameter in Ajax request url. StoreASF could contain more than one set of the object store, so looping is possible. For every called JSON data from request would be put to array data, and after the looping is complete, I save it to storeARF with the loadData method.
The problem is, my data format is wrong since loadData can only read JSON type data. I already try JSON stringify and parse, but couldn't replicate the data format. Any suggestion how to do this? Thank you.
Rather than using Ext.util.Json.decode(), normalize the data in success() method using your own logic. For example:
success: function (response) {
console.log(response);
var myData = [];
Ext.Array.forEach(response.data, function (item) {
myData.push({
name: item.name,
email: item.email,
phone: item.phone
});
});
store.load();
}

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.

How to convert JSON array to JavaScript Array?

I am using KnockoutJS for data binding.
Following code is controller's action method
public JsonResult GetPeople()
{
var people = new List<Person>
{
new Person {Name = "aaaa", Address = "aaaaaaaaa"},
new Person {Name = "bbbb", Address = "bbbbbbbbb"},
new Person {Name = "cccc", Address = "ccccccccc"}
};
return Json(people, JsonRequestBehavior.AllowGet);
}
And bellow is the snippet of client side code
<ul data-bind="foreach: people">
<li>NAME:<span data-bind="text: Name"></span></li>
<li>ADDRESS:<span data-bind="text: Address"></span></li>
</ul>
<script>
function getPeopleFromServer() {
var people= [];
$.ajax({
url: "GetPeople",
cache: false,
type: "GET",
success: function (result) {
console.log("result= " + result);
people = $.parseJSON(result);
console.log("people= " + people);
}
});
return people;
}
function ViewModel() {
var self = this;
// data
self.people = ko.observableArray(getPeopleFromServer());
}
ko.applyBindings(new ViewModel());
</script>
The problem is that people variable in the getPeopleFromServer method is always null while result has proper value from the server.
Am I missing something?
Your $.ajax function is taking longer to complete than it's containing function, and so the containing function never popuplates people by the end of execution
One thing you can do is to add the following to your $.ajax:
$.ajax({
async: false,
url: "GetPeople",
.....
});
async: false will make the containing function 'wait' until ajax is finished. Your people var should be populated by the end of function execution. While this is a quick win, I agree with Tom that you should re-think how your ViewModel is handled.
#tom's comment is correct.
'success' is an inline async function. Basically, 'return people' happens before the 'success' function is called, because the ajax call is non-blocking. You need to redesign your ViewModel to work asynchronously (or turn off async), hopefully others will chime in with code fixes
Here's the fully commented fiddle he prophesied.
http://jsfiddle.net/bczengel/8Wqum/
people should be referred to either in the same view model. Or as self.people. I suggest you put the call to ajax inside the view model and then it will be clear.
So getPeopleFromServer() should be inside the viewmodel.
Out of interest you can also add
timeout: 600000 so that the call doesnt timeout.
Try to use ko.mapping plugin.
function ViewModelWrapper(jsonResult)
{
var self = this;
self.model = ko.mapping.fromJS(jsonResult);
}
http://knockoutjs.com/documentation/plugins-mapping.html

how to return ajax suceess from user defined function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I am having the bellow function .
Here i want to return ajax success from user defined function . How to do this
alert(Ajaxcall(id_array,"del"));
function Ajaxcall(id_array,type){
$.ajax({
type: "POST",
url: "serverpage.php",
cache:false,
data: ({id:id_array,type:type}),
success: function(msg){
return msg; //this returns nothing
}
});
alert(msg); // this one undefined
}
thanks
The "a" in "ajax" stands for "asynchronous" ("Asynchronous JavaScript And XML", although these days most people use it with JSON rather than XML).
So your Ajaxcall function returns before the ajax call completes, which is why you can't return the message as a return value.
The usual thing to do is to pass in a callback instead:
Ajaxcall(id_array,"del", functon(msg) {
alert(msg);
});
function Ajaxcall(id_array,type, callback){
$.ajax({
type: "POST",
url: "serverpage.php",
cache:false,
data: ({id:id_array,type:type}),
success: function(msg){
callback(msg);
}
});
}
It's surprisingly easy with JavaScript, because JavaScript's functions are closures and can be defined inline. So for instance, suppose you wanted to do this:
function foo() {
var ajaxStuff, localData;
localData = doSomething();
ajaxStuff = getAjaxStuff();
doSomethingElse(ajaxStuff);
doAnotherThing(localData);
}
you can literally rewrite that asynchronously like this:
function foo() {
var localData;
localData = doSomething();
getAjaxStuff(function(ajaxStuff) {
doSomethingElse(ajaxStuff);
doAnotherThing(localData);
});
}
I should note that it's possible to make an ajax call synchronous. In jQuery, you do that by passing the async option in (setting it false). But it's a very bad idea. Synchronous ajax calls lock up the UI of most browsers in a very user-unfriendly fashion. Instead, restructure your code slightly as above.
But just for completeness:
alert(Ajaxcall(id_array,"del"));
function Ajaxcall(id_array,type){
var returnValue;
$.ajax({
type: "POST",
url: "serverpage.php",
cache:false,
async: false, // <== Synchronous request, very bad idea
data: ({id:id_array,type:type}),
success: function(msg){
returnValue = msg;
}
});
return returnValue;
}
JQuery has a number of global Ajax event handlers, including $.ajaxComplete() and $.ajaxSuccess() (ref: http://api.jquery.com/ajaxSuccess/).
The code can be attached to any DOM element and looks like this:
/* Gets called when all request completes successfully */
$("#myElement").ajaxSuccess(function(event,request,settings){
$(this).html("<h4>Successful ajax request</h4>");
});
This code will execute whenever any successful Ajax call is completed.