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.
Related
I am unable to get a json response from my controller action. The network shows as a post which is correct as I am posting a file to the server, however, needs a JSON response sent back to my view.
public JsonResult Upload(HttpPostedFileBase file, int id)
{
Homes thishomes= _db.Homes.FirstOrDefault(t => t.Id == id);
FileUploader fileupload = new FileUploader();
fileupload.PostIt(file.InputStream);
return Json(new { success = true, response = "File uploaded.", JsonRequestBehavior.AllowGet });
}
JQUERY using Dropzonejs:
Dropzone.options.DropzoneForm = {
paramName: "file",
maxFilesize: 2000,
maxFiles: 28,
dictMaxFilesExceeded: "Custom max files msg",
init: function () {
this.on("success", function () {
alert("Added file");
})
}
};
Can anyone see an this issue?
Try to write [HttpPost] attribute over your action. Also "The network shows as a post which is correct" if its post then you don't need JsonRequestBehavior.AllowGet
when you are returning Json to your request
I would like to return the result of an HTTP request in my AWS Lambda function:
var http = require('http');
exports.someFunction = function(event, context) {
var url = "http://router.project-osrm.org/trip?loc=47.95,12.95&loc=47.94,12.94";
http.get(url, function(res) {
context.succeed(res);
}).on('error', function(e) {
context.fail("Got error: " + e.message);
});
}
It should return exactly what I get when I open the url directly in my browser (try it to see the expected json).
AWS Lambda return the following error message when I call context.succeed(res):
{
"errorMessage": "Unable to stringify body as json: Converting circular structure to JSON",
"errorType": "TypeError"
}
I assume that I need to use some property of res instead of res itself, but I couldn't figure out which one contains the actual data I want.
If you are using the raw http module you need to listen for data and end events.
exports.someFunction = function(event, context) {
var url = "http://router.project-osrm.org/trip?loc=47.95,12.95&loc=47.94,12.94";
http.get(url, function(res) {
// Continuously update stream with data
var body = '';
res.on('data', function(d) {
body += d;
});
res.on('end', function() {
context.succeed(body);
});
res.on('error', function(e) {
context.fail("Got error: " + e.message);
});
});
}
Using another module such as request https://www.npmjs.com/package/request would make it so you don't have to manage those events and your code could go back to almost what you had before.
I have a middleware function using Node's Express4 to log each request & response for debugging. I use the res.json call in the request handler to send back JSON to the client for all but static files. So I do not want to log the response for static files, but only the JSON responses. I have the following code:
function logRequests(req, res, next) {
// do logging (will show user name before authentication)
logger.reqLog('IN '+req.method+' '+req.url, req);
var oldEnd = res.end,
oldWrite = res.write,
chunks = [];
res.write = function(chunk) {
chunks.push(chunk);
oldWrite.apply(res, arguments);
};
res.end = function(chunk, encoding) {
if(chunk) {
chunks.push(chunk);
}
oldEnd.apply(res, arguments);
// the content-type prints "undefined" in some cases
// even though the browser shows it returned as "application/json"
console.log('type='+res.get('content-type'));
if(res.get('content-type') === 'application/json') {
var body = Buffer.concat(chunks).toString('utf8');
logger.info(body, req);
}
logger.reqLog('OUT '+req.method+' '+req.path, req);
};
next(); // make sure we go to the next routes and don't stop here
}
So why do some requests show the correct content type in the middleware meaning they also print the response fine and others do not? All of them look good in the REST client when inspecting the returned headers.
EDIT: Some more info discovered tonight while trying to figure this out - if I append any character as a dummy request parameter, it logs the response type correctly:
http://localhost:8081/node/ionmed/api/logout?0 WORKS
where
http://localhost:8081/node/ionmed/api/logout DOES NOT
Also, I can always get a response type logging in the middleware function if I replace the .json() call with .end() so this:
res.json({ item: 'logout', success: true });
becomes:
res.set('content-type', 'application/json');
res.end({ item: 'logout', success: true });
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.
The contents of my dataHelper.js file:
define(["dojo/_base/declare", "dojo/dom", "dojo/_base/xhr", "dojo/json"],
function(declare, dom, xhr, json){
return {
getJSON: function(){
xhr.get({
url: "../../cpuusage.json",
handleAs: "json",
load: function(jsonData){
return jsonData;
},
error: function() {
}
});
}
};
});
I'm trying to run this from my index.html as follows:
var chartData = dataHelper.getJSON();
I think I have several issues. First of all, I'm not sure my module and the getJSON function is defined correctly. Secondly I get errors on my console:
TypeError: this.source is undefined
[Break On This Error]
= [],
dojo.js (line 362)
SyntaxError: missing : after property id
},
dojo.js (line 330)
SyntaxError: missing : after property id
},
dojo.js (line 330)
SyntaxError: missing : after property id
},
All I want to achieve first is load the json data into the chartData variable. Many thanks.
The first issue I'm seeing is you are treating an asynchronous process as if it was a synchronous one. The xhr.get returns immediately after the request to the server is sent, it does not block until a response is received.
First, I would add a console.log to your module definition to ensure that your dataHelper module is being loaded correctly.
define(["dojo/_base/xhr"],
function(xhr){
console.log('dataHelper.js loaded');
return {
//
};
});
Also note that above you aren't using any of the base dojo modules except dojo/_base/xhr, so it is unnecessary to include them (unless they are used outside this snippet).
You need to update your code to handle this call asynchronously. To do this, you could take advantage of the fact that the xhr.get method returns a Deferred object. This class makes dealing with asynchronous in a consistent manner quite easy.
To do this, update the dataHelper module to return the result of the xhr call:
define(["dojo/_base/xhr"], function(xhr){
return {
getJSON: function(){
//this returns a Deferred object, what to do on load and error is then handled by the invoker
return xhr.get({
url: "../../cpuusage.json",
handleAs: "json"
});
}
};
});
Then, when utilizing this module:
//replace dataHelper with whatever it's path is
require(['dataHelper'],function(dataHelper){
var deferred = dataHelper.getJSON();
deferred.then(function(data){
//this function is invoked once the data has been fully loaded
}, function(error){
//this function is invoked if an error occurs while loading the data (in case of a server error response or if the response isn't in the format you specified)
});
});
This is my proposal:
Your dataHelper.js file:
define("dataHelper", ["dojo/_base/declare", "dojo/dom", "dojo/_base/xhr"],
function(declare, dom, xhr){
return declare("dataHelper", [], {
getJSON: function(){
return xhr.get({
url: "../../cpuusage.json",
handleAs: "json"
});
});
};
});
your invocation:
require(["dataHelper"], function(dataHelper) {
var chartData;
dataHelper.getJSON().then(function(jsonData) {
chartData = jsonData;
//Continue doing stuff with chartData in here, not outside
});
});