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();
}
Related
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.
I have trouble storing a JSON file in my DynamoDB table with the help of my Lambda function and my API Gateway on AWS. I have the following piece of code which gets executed once I press a button on my HTML site:
$('#submit').on('click', function(){
var example = {"number":"121212"};
$.ajax({
type: 'POST',
url: API_URL,
data: JSON.stringify(example),
contentType: "application/json",
success: function(data){
location.reload();
}
});
return false;
});
When pressed the website reloads, hence I assume function has successfully executed. However my problem is that the data does not arrive in the correct format in the lambda function and hence does not execute properly. When checking in CloudWatch it is shown as { number: '121212' } instead of {"number":"121212"}. Any idea how I can make sure that the value 'arrives' has a valid JSON format in my Lambda function?
Here's my Lambda function:
exports.handler = function index(e, ctx, callback) {
var params = {
Item: { number: e.number },
TableName: 'collectionOfNumbers'
};
docCLient.put(params, function(err, data) {
if (err) {
callback(err, null);
} else {
callback(null, data);
}
});
}
If I'm reading this right, e.number is the value of the JSON parameter 'number' that you are passing in, e.g. '121212'. I'm making the assumption from the usage that docClient is putItem under the hood.
I think your Item param should look like:
Item: {"number": {N: e.number}}
See AWS Docs for info regarding PutItem https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_PutItem.html
I want to make a HTTP-POST-Request with AJAX to call a JSON API. So, the API should return a response in JSON. I can see on the console of the API, that the request is successful. But the problem is, that no data or status is returned, or that I can't use it with JQuery. Here is my function:
$.post("http://api-adress/controller",
{
email: input_mail,
password: input_pw
},
function(data, status){
alert(data);
alert(status);
}, 'json');
I guess the problem is that the response from the Server does not get saved in the variables data and status correctly.
I would suggest to change a little bit your code like below:
var dataString = {
email: input_mail,
password: input_pw
}
$.post("http://api-adress/controller", dataString, function (result) {
})
.done(function (result) {
//Here is your result. You must parseJSON if it is json format
var data = jQuery.parseJSON(result);
})
.fail(function () {
//use this if you need it
})
Also make sure that you get the response through firebug in console tab. You can check there what you post, what you get etc.
This is my code creating a json file:
$( ".save" ).on("click", function(){
var items=[];
$("tr.data").each(function() {
var item = {
itemCode : $(this).find('td:nth-child(1) span').html(),
itemQuantity : $(this).find('td:nth-child(4) span').html()
};
items.push(item);
});
});
Now the json object looks like:
[{"itemcode":"code1","itemquantity":"quantity1"},{"itemcode":"code2","itemquantity":"quantity2"},...]
My question is how do I parse this data in Django view?
Following is my AJAX function for reference:
(function() {
$.ajax({
url : "",
type: "POST",
data:{ bill_details: JSON.stringify(items),
calltype:'save'},
dataType: "application/json", // datatype being sent
success : function(jsondata) {
//do something
},
error : function() {
//do something
}
});
}());
Since I'm sending multiple AJAX request to the same view, I need the 'calltype' data as well.
Thanks you on your answer!! BTW, I badly need to know this simple stuff, which I'm missing
This is my code snippet for parsing:
if (calltype == 'save'):
response_data = {}
bill_data = json.loads(request.POST.get('bill_details'))
itemcode1=bill_details[0]['itemCode']
#this part is just for checking
response_data['name'] = itemcode1
jsondata = json.dumps(response_data)
return HttpResponse(jsondata)
The error being raised is
string indices must be integers
Request your help
For your reference, this is my POST response (taken from traceback):
bill_details = '[{"itemCode":"sav","itemQuantity":"4"}]'
calltype = 'save'
csrfmiddlewaretoken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
EDITED Django View
This is my edited view:
if (calltype == 'save'):
bill_detail = request.POST.get('bill_details')
response_data = {}
bill_data = json.loads(bill_detail)
itemcode1=bill_data[0]['itemCode']
#this part is just for checking
response_data['name'] = itemcode1
jsondata = json.dumps(response_data)
return HttpResponse(jsondata)
I fail to understand the problem. SO, to solve it, my question: what is the datatype of the return for get call and what should be the input datatype for json.loads. Bcoz the error being shown is json.loads file has to be string type!! (Seriously in limbo)
Error:
the JSON object must be str, not 'NoneType'
I want to POST an Object via JSON to node.js server.
The Object structure is nested, and never succeeded to receive and parse correctly on node.js server site.
EDIT2
I found a solution: see the answer section...
EDIT
I found
console.log(body);
itself output
val1=hello&val2%5Bval3%5D=world
//= {"val1":"hello","val2[val3]":"world"}
weired JSON way
client.js
var data ={val1:"hello",val2:{val3:"world"}};
console.log(data); // -> *1
$.ajax({
url:"/",
type:"POST",
dataType: 'json',
data:data,
success:function (res)
{
resHandler(res);
}
});
*1 ChromeDevelopersTool
Object
val1: "hello"
val2: Object
val3: "world"
server.js
var onreq = function (req, res)
{
if(req.method == 'POST')
{
var body = '';
req.on('data', function (data)
{
body += data;
});
req.on('end', function ()
{
var json = qs.parse(body);
console.log(json.val1); //hello
console.log(json.val2); //undefined
console.log(json.val3); //undefined
console.log(JSON.stringify(json));
//{"val1":"hello","val2[val3]":"world"}
});
}
I understand
val2[val3]
is
val2.val3
However,
Problem 1
JSON.stringify prints out
{"val1":"hello","val2[val3]":"world"}
not
{val1:"hello",val2:{val3:"world"}}
It's ugly, and I don't know why it's like that.
Problem 2
I can never get {val3:"world"}
console.log(json.val3); //undefined
Anyone can explain, and how can I POST a nested JSON to node.js server?
Thanks.
Do NOT use JSON typed data on jQuery Ajax, instead use Stringified JSON
I created a WIKI
http://code.google.com/p/kenokabe/wiki/nestedJSONproblem