I have this code as a cffunction that works fine:
<cfcomponent extends="core.core">
<cffunction name="loadService" access="remote" returnformat="JSON">
<cfscript>
objResponse = '{"CONFIG":[["internal"],[ "success"]],"DATA":[["Message1"]]}';
</cfscript>
<cfreturn objResponse>
</cffunction>
</cfcomponent>
I am trying to convert it to a full cfscript function like this:
component extends="core.core"{
remote JSON function loadService(){
objResponse = '{"CONFIG":[["internal"],[ "success"]],"DATA":[["Message1"]]}';
SerializeJSON(objResponse);
return objResponse;
}
}
The first way returns JSON fine and I can process it with jQuery. The second one throws and error "The value returned from the loadService function is not of type JSON."
I have tried it with and without SerializeJSON and both ways throw that error. I have also tried it without specifying JSON in the function syntax. That does not throw an error but it does wrap wddxpacket info around it. This is what it looks like when I don't specify JSON:
<wddxPacket version='1.0'><header/><data><string>{"CONFIG":[["internal"],[ "success"]],"DATA":[["Message1"]]}</string></data></wddxPacket>
I am stuck on this. Any help would be great. Thanks!
The correct CFScript syntax in CF9 is:
remote any function loadService() returnformat="JSON" {
Technically, "JSON" is not a valid returntype from a function (see here for all returntypes), but when you write:
remote JSON function
...you're basically saying that.
Notice in your tag-based cffunction call, you do not specify a returnType...so guess what it is by default? (hint: any).
It's easy to mix returnType and returnFormat up. A simple adjustment above and you should be good to go.
Complete Code
component extends="core.core" {
remote any function loadService() returnFormat="JSON" {
objResponse = '{"CONFIG":[["internal"],[ "success"]],"DATA":[["Message1"]]}';
SerializeJSON(objResponse);
return objResponse;
}
}
Also, I noticed that you have
SerializeJSON(objResponse);
in your function. This line has no effect on your function's return. So, it can easily be ommitted as your objResponse value is already in a JSON string. But, if the value of objResponse was something like
objResponse = {
"CONFIG" = [["internal"], ["success"]],
"DATA" = [["Message1"]]
};
then you could have done something like
return serializeJSON(objResponse);
which would have turn the complex data you had into a JSON string.
Here's the complete function
remote any function loadService()
returnFormat="JSON"
{
objResponse = {
"CONFIG" = [["internal"], ["success"]],
"DATA" = [["Message1"]]
};
return serializeJSON(objResponse);
}
Another way to specify the 'returnFormat' would be to use annotations:
component extends="core.core" {
/**
* #hint loads properties of an object and returns them in as JSON
* #output false
* #returnFormat JSON
*/
remote struct function loadService() {
objResponse = {
CONFIG = [["internal"],[ "success"]],
DATA = [["Message1"]]
};
return objResponse;
}
}
Related
In the CF 2016 Administrator page, by selecting the check box "Prefix serialized JSON with" //ABC (form example), it will break the function below, because it will add the string //ABC to the JSON
How can we remove the prefix //ABC before parsing the JSON, please?
<cffunction name="searchData" access="remote" returnformat="JSON">
<cfquery name="getData" datasource="#dataSource#">
SELECT *
FROM aTable
</cfquery>
<cfreturn serializeJSON(getData)>
</cffunction>
Thank you for your help
We have an option for this prefix Serialized JSON uncheck the Prefix serialized JSON with options in our admin comes under the options cfadmin - > Server Settings - > setting table you can see that options. FYR, Please refer my below images & sample codes,
Before uncheck the prefix option:
<cfset struct = {"name":"thiraviam", "age":24}>
<cfdump var="#serializeJSON(struct)#">
Output:
//abc{"name":"thiraviam","age":24}
After uncheck the prefix option:
<cfset struct = {"name":"thiraviam", "age":24}>
<cfdump var="#serializeJSON(struct)#">
Output:
{"name":"thiraviam","age":24}
[]
I hope it's help you more. Thank you !
You did not provide how you are calling this service. Regardless, all you need to do when calling a service which prefixes the JSON data is remove the prefixed data before processing the response. Below is an example using jQuery to make an AJAX call to such a service.
For jQuery AJAX the key for this is to use the dataFilter option. The dataFilter option gives you access to the raw response so it can be sanitized.
A function to be used to handle the raw response data of XMLHttpRequest. This is a pre-filtering function to sanitize the response. You should return the sanitized data. The function accepts two arguments: The raw data returned from the server and the 'dataType' parameter.
From the jQuery documentation
Here is an example. Notice how the dataFilter in this case is removing the first 2 characters from the response with this code; data.substr(2). For your example you would need to increase that to 5 in order to remove //ABC.
$.ajax({
type: 'POST',
cache: false,
data: {property1:'somevalue',property2:'someothervalue'},
dataFilter: function(data, type) {return data.substr(2)},
dataType: 'json',
url: 'https://www.somedomain.com/api/service/',
success: function(data, stat, resp) {
if(!data.error) {
// good return so do what you need to do
// this is assuming the service returns an 'error' field
// the JSON data is accessible by using data.fieldname format
} else {
// bad return so trap it
}
},
error: function(resp, stat, err) {
// service call failed so trap it
}
});
I am sending this json data by PostMan:
{
'id':10,
'fname':'abc',
'lname':'xyz'
}
On the server side I receive the data by using:
$request = $this->getRequest();
$rawBody = $request->getContent();
$rawBody variable is of type string.
So how can I get those parameters...?
json_decode($rawBody); should work but I'd rather suggest:
\Zend\Json\Json::decode($rawBody);
or
$data = $request->getPost()->toArray();
This is very basic stuff, you should be able to find this easily with Google.
thnx decoding solve the problem
I got it..
public function createAction()
{
$user=new User();
$request=$this->getRequest();
$rawBody=$request->getContent();
$u=\Zend\Json\Json::decode($rawBody);
$user->fname=$u->fname;
$user->lname=$u->lname;
$this->getUsersTable()->createUser($user);
return new JsonModel(array($user));
it was also a Json syntax error,double qoute resolve the error
{
"id":10,
"fname":"abc",
"lname":"xyz"
}
I'm using node, express, and mongoose.
I have a function that performs a search in a database and sends the response in a JSON format with:
res.jsonp(search_result);
This displays the correctly returned result in the browser as a JSON object. My question is, how do I get that JSON object?
I've tried returning search_result but that gives me null (possibly because asynchronous). I'd also like to not edit the current function (it was written by someone else). I'm calling the function and getting a screen full of JSON, which is what res.jsonp is supposed to do.
Thanks in advance.
Just make a new function that takes this JSON as parameter and place it inside the old one. Example:
// Old function
app.get('/', function(req,res){
// recieve json
json_object = .....
// Get json to your function
processJson(json_object);
// Old function stuff
.
.
.
});
function processJson(json_object) {
// Here you'll have the existing object and can process it
json_object...
}
I can successfully make a jQuery Ajax call into my C# Controller and receive back an XML string, but I need to in turn gather some Portfolio dates and package them up into a JSON object so I can send them back into another C# Controller.
If it's a C# issue, then I apologize if I'm in the wrong forum...however I'd like to pass my JSON object into the server side controller ..
Here's what I'm trying to do:
var nodeDatesJson = {"nodedates": // CREATE JSON OBJECT OF DATE STRINGS
{ "date": 01/20/2012,
"date": "01/21/2012" } };
getTradeContribs(thisPfId, nodeDatesJson.nodedates.date);
Now call the next js function:
function getTradeContribs(pfid, nodedates) {
//alert(nodedates);
$.ajax({ // GET TRADE CONTRIBS FROM SERVER !!
url: "/Portfolios/getTradeContribs?portfolioId=" + pfid + "&nodedates=" + nodedates,
type: "GET", // or "PUT"
dataType: "json",
async: true,
success: parseTradeContribs,
error: function (error) {
alert("failed in opening Trade Contribs file !!!");
}
});
}
function parseTradeContribs(data) {
alert("In parseTradeContribs..." );
$(data).find("Trade").each(function(){
$(".TradeContrib").append($(this).text());
})
}
and my C# controller is trying to read in the "nodedates" JSON object, but HOW do I read it in ?
public string getTradeContribs(string portfolioId, **string nodedates**)
{
// Build Portfolio Select request here !
RequestBuilder rzrRequest = new RequestBuilder();
// REQUEST FOR CONTRIBUTIONS !
// ... more code here..
xmlResponse.LoadXml(contribResponse);
string jsonTest = #" {""nodedates"": ""date"":""01/01/2012""}";
//return xmlResponse.OuterXml; // WORKS FINE
return "<Trade><TradeId>1234</TradeId></Trade>"; // RETURN TEST XML STR
}
thank you in advance...
Bob
The best way to receive a list of dates in a MVC action is to bind to a collection. What this means is that you should put your dates and other attributes in a form with the following naming convention:
<input type="hidden" name="dates" value="2012-1-20" />
<input type="hidden" name="dates" value="2012-1-21" />
Then you should serialize this form (look into jquery's docs for this) and post its data to your action, which will be something along the lines of:
public ActionResult getTradeContribs(string portfolioId, IList<DateTime> dates) {
// Do your work here
}
You should really take a look into MVC Model binding and collection binding as well:
Model binding to a list
Model binding objects
Also, if I may, your javascript object has two properties with the same name, which is probably not what you mean. If you want to have multiple dates stored somewhere in a object, you should use an array:
var nodeDatesJson = {"nodedates":
[ "01/20/2012", "01/21/2012" ] };
Sorry, but I didn't understand your doubt very well...but here it goes:
Maybe you should pass the json, well-formatted, as a string and use some C# parser.
This way you can get a object in server-side as same as the Json object in javascript.
=]
Whats wrong in below JSON Object definition
I am trying to create a new JSON Object like below.
So that my idea is to access COMPANYSETUP.HourSetup.initiate();
Not sure the error ?
COMPANYSETUP = {
initiated : false,
companyId : "",
initiate : function() {
if(!initiated){
// TO DO
initiated = true;
} },
HourSetup = {
initiated : false,
hourId : "",
initiate : function() {
if(!initiated){
// TO DO
initiated = true;
}
}
}
};
Assuming you want a javascript object and not JSON, which disallows functions,
HourSetup =
Should be changed to:
HourSetup :
Also, as JonoW points out, your single line comments are including some of your code as the code is formatted in the post.
There's a "=" that shouldn't be there. Change it to ":"
JSON is a form of JavaScript deliberately restricted for safety. It cannot include dangerous code elements like function expressions.
It should work OK in plain eval()ed JavaScript, but it's not JSON.