Grails GET method for JSON - json

I am trying to use the http GET method to retrieve JSON object I have created, then in Titanium I have created a method to retrieve, however it is only retrieving "undefined"
def listJSON() {
def converter = User.list() as JSON
System.out.println(converter)
render(converter)
//response(converter)
}
The output from grails is correct and the page rendered (from system out) :
[{"class":"testingmobile.User","id":1,"age":22,"email":"test#hotmail.com","name":"Ryan","occupation":"Whatever "}]
The code from the mobile app in Titanium is as follows:
var url = "http://localhost:8080/TestingMobile/user/listJSON";
var client = Ti.Network.createHTTPClient ({
onload : function(e) {
Ti.API.info("Recieved text: "+ this.responceText);
var jsonObj = JSON.parse(this.responseText);
getShow(jsonObj);
alert('success');
},
onerror : function(e) {
Ti.API.debug(e.error);
alert('error');
},
timeout : 5000
});
client.open("GET", url);
client.send();
The console outputs "Received text: undefined"

responceText
should be
responseText
with an s, not a c.

Related

POST-request with multipart/form-data from ExtJS form to .Net5 controller gets responseText empty

I have a form in ExtJS:
{
xtype: 'form',
items: [{
xtype: 'filefield',
name: 'azezFile'
}],
buttons: [{
text: 'Load',
handler: function() {
var form = this.up('form').getForm();
if(form.isValid()) {
form.submit({
url: uploadApiPath,
success: function(fp, o) {
// Never goes here
}
});
...
It sends file to a controller (.Net5):
namespace KROSS_Core.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Produces("application/json")]
public class UploadController : ControllerBase
{
// POST: api/Upload
[HttpPost]
public IActionResult Post([FromForm] IFormFile file)
{
//AzezUploadFile(this.HttpContext);
return Ok(new { success = true });
//return Ok(LoadFileToBase(this.HttpContext));
//return BadRequest(new { success = false, message = "Wrong answer" });
}
Controller getting request and responses normally, but I got an exception in ext-all-debug.js:
Unhandled exception at line 6092, column 17 in
https : // localhost:44364/Website/Scripts/ext.js/ext-all-debug.js
0x800a139e - Error JavaScript: Ext.JSON.decode(): You're trying to
decode an invalid JSON String:
And response.responseText is empty in debugger. After I close that exception, the browser (IE11) asks me to save or open that json file.
Firefox shows another error in console:
"You're trying to decode an invalid JSON String: <pre>{\"success\":true}</pre>"
, but it was set [Produces("application/json")] in controller...
Google Chrome log: "You're trying to decode an invalid JSON String: <pre style="word-wrap: break-word; white-space: pre-wrap;">{"success":true}</pre>"
What is the problem and how to make it working? The same controller method loaded without sending multipart form-data goes normally and ExtJS works with response JSON.
I have no idea how to fix it in ExtJS, but I used another method of uploading a file to a server (same controller), and it works perfect:
function uploadFile(file, url, success, failure) {
var formData = new FormData();
var request = new XMLHttpRequest();
formData.append('file', file);
request.onload = function (response) {
var jsonResult = JSON.parse(response.target.responseText);
if (jsonResult.exception || jsonResult.error) {
failure(jsonResult);
}
else {
success(jsonResult);
}
};
request.open("POST", url);
request.send(formData);
}
And use it like
uploadFile(form.down('[name=fileInnputName]').extractFileInput().files[0], uploadApiPath, function() { }, function() { });

SAPUI5 oData V4 Read Object

How to read the object in UI5 with oData V4?
Basically I want to get the JSON object from the URL service:
Ths is my onInit function in the controller.
onInit: function() {
var this_ = this;
this.getView().addEventDelegate({
onBeforeShow: function(evt) {
var oModel = new sap.ui.model.json.JSONModel();
oModel = sap.ui.getCore().getModel("appid");
var app_id = oModel.getData().app_id;
this_.getView().bindElement({
path: "zearnModel>/zearn_summary(" + app_id + ")"
});
}
});
}
From the documentation:
The OData V4 model only supports data access using bindings. It does not provide any direct access to the data.
To get the raw JSON object, all you can do is use jQuery's ajax features to request the data:
$.get({
url: "<your_service_url>/zearn_summary(" + app_id + ")",
success: function(data) {
// your success logic
},
error: function(error) {
// your error logic
}
});

Parsing JSON object sent through AJAX in Django

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'

AngularJS with Jersey JSON resource in undefined in javascript

This is weird issue I have so far.
I am using jaxon backbone to do this Angularjs project.
java resource file
#GET #Path("{query}")
#Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Signature findByName(#PathParam("query") String query) {
return dao.findById(query);
}
control.js file
function SearchCtrl($rootScope,$scope,Signature) {
// console.log('SearchCtrl is invoked!!!!!!');
$scope.signature;
$scope.searcherrormsg='';
$scope.searchaction = function(barcodenum,signature) {
signature = Signature.query({rewardcardId:barcodenum});
$scope.signature = signature;
alert("data is " + $scope.signature.name); <=== This is UNDEFINED
};
}
apps.js file
angular.module('demo', ['demo.filters', 'demo.directives','demo.services.signature']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/search', {templateUrl: 'partials/search.html', controller: SearchCtrl});
$routeProvider.otherwise({redirectTo: '/search'});
service.js file
angular.module('demo.services.signature', ['ngResource']).
factory('Signature', function($resource){
return $resource('api/signature/:rewardcardId', {}, {
query: {method:'GET', params:{rewardcardId:'signature'}, isArray:false}
});
});
This is invoking database and server console is showing the following message ;
com.sun.jersey.api.container.filter.LoggingFilter$Adapter finish
INFO: 1 * Server out-bound response
1 < 200
1 < Content-Type: application/json
1 <
{"name":"xxx xxxx","customerid":187,"email":"xxxx#hotmail.com","sign":null,"barcode":"xxxx"}
And it displays return data at the HTML page properly. For example, the html page has
<p>{{signature.barcode}}
{{signature.name}}
which are displaying name and barcode properly as the above data set .
It only has an issue to get the data from the javascript that is saying undefined.
Whenever the javascript is trying to get the data from return resources from database, it is saying undefined.
You are trying to print the resource before it is available. The request to the server is asynchronous. Put alert("data is " + $scope.signature.name); in the success callback instead.
$scope.searchaction = function (barcodenum, signature) {
Signature.query({ rewardcardId: barcodenum },
function(data) {
$scope.signature = data;
alert("data is " + $scope.signature.name);
},
function(err) { // error handling can go here
});
};
I am not sure why you pass signature to $scope.searchaction and then perform an assignment operation on it.

HTML5 localStorage and Dojo

I am working in DOJO and my task is i have one JSON file and the datas are coming from JSON url. So now i have to read JSON url and save the datas to browser using HTML5 localStorage, after saving i have to read datas from browser and i have to display in DOJO. Guys any one know about this kindly help me..
Function for getting json data
function accessDomain(dom_sclapi, handle) {
var apiResponse;
//accessSameDomain
if(!handle) {
handle = "json";
}
dojo.xhrGet({
url : dom_sclapi,
handleAs: handle,
sync: true,
headers: { "Accept": "application/json" },
//Success
load: function(Response) {
apiResponse = Response;
},
// Ooops! Error!
error: function(Error, ioArgs) {
//apiResponse = Error;
//console.log(ioArgs.xhr.status);
}
});
//apiResponse
return apiResponse;
}
where dom_sclapi = <json url>
Call
var data = accessDomain(<jsonurl>,'json');
then
console.log(data);
You can see the json o/p in console window. Now you can dispaly to html page using,
dojo.forEach(data, function(eachData){
//script for each json element eg: eachData.displayName;
});