Lets start , firstly I get parameters for specific report for exmaple
var config = {
url : "http://exmaple.com/jasperserver/rest_v2/reports/reportFolder/exampleReport/inputControls",
method: "GET",
headers: {
Accept: "application/json;"
},
}
Everything is ok, I get a response with an array of inputs,
The array contains, 2 objects with :
First:
{
description: "Date_from",
id: "Date_from",
label: "Date from",
type: "singleValueDate"
}
Second:
{
description: "Date_to",
id: "Date_to",
label: "Date_to",
type: "singleValueDate"
}
Both inputs have a property:
validationRules[0].dateTimeFormatValidationRule.format = "yyyy-MM-dd"
So now I want to run a async report (I will pass async parameter false for now, se there is less code here)
var params ={
reportUnitUri: "/reportFolder/exampleReport",
outputFormat: "html",
freshData : true,
saveDataSnapshot : false,
ignorePagination: true,
async : false,
interactive: false,
allowInlineScripts: true,
parameters: {
"Date_from":["2014-08-01"],
"Date_to":["2015-10-08"]
}
}
So now I try to generate async report:
var config = {
url : "http://exmaple.com/jasperserver/rest_v2/reportExecutions",
headers: {
Accept: "application/json"
},
data: params,
method: "POST"
}
I get a success response, but
totalPages: 0,
requestId: "0200cf28-300f-4e76-b99e-e479be4980ba",
reportURI: "/reportFolder/exampleReport/",
status: "ready",
exports[0].id: "c9a5578a-6bc8-4c3e-8a78-9056ef19f456",
exports[0].status: "ready",
exports[0].outputResource :{
contentType: "text/html",
outputFinal: true
}
When I try to get the output of the report by calling :
http://exmaple.com/jasperserver/rest_v2/reportExecutions/0200cf28-300f-4e76-b99e-e479be4980ba/exports/c9a5578a-6bc8-4c3e-8a78-9056ef19f456/outputResource
The report is empty.
Runing the same via :
http://exmaple.com/jasperserver/rest_v2/reports/reportFolder/exampleReport.html?Date_from=2014-08-01&Date_to=2015-09-08
Gives me a filled report,
Can anyone point me what I'm doing wrong ? :/
I'm pretty sure that it may be something wrong with the parameters but I tried in various ways and I can't find a solution by myself :/
The thing was that the parameters passed to the async report were badly formatted, it should be like this:
parameters: {
reportParameter: [
{name : "Date_from",value : ["2014-08-01"]},
{name : "Date_to",value : ["2015-10-08"]}
]
}
Related
I have a function button that carry user info fullname, after clicking the button, it will send fullname and level to an API to be process and the result should be display in dataTable. Unfortunately, I got this error.
This is console.log for console.log(params). {"task_level":3,"fullname":"Administrator"}
Below is console.log for console.log(params).
Both console log is similar to API's result.
I don't know which is proper.
JS 1st Try (1st Ajax to send the parameter to API and after return success hopefully working but not.
"<button type='button' class='btn btn-dark btn-round' onclick='viewTablePerson(""+value.fullname+"")'>View Project</button>"+
function viewTablePerson(fullname){
var level = 3;
var fullname2 = fullname;
var obj = {
task_level : level,
fullname : fullname2
};
var params = JSON.stringify(obj);
console.log(params)
$.ajax({
url : url_api + '/api/user_task',
crossDomain: true,
type : 'POST',
dataType : 'json',
data: params,
success: function(response){
if (response.status == "Success"){
console.log(response)
$('#viewProgress').DataTable({
ajax: {
url: url_api + '/api/user_task',
crossDomain : true,
type : "POST",
cache : false,
dataType : "json",
contentType: false,
processData: true,
data : params,
timeout: 10000,
},
destroy: true,
columns: [
{ data : "task_name"},
{ data : "task_owner"},
{ data : "task_status"}
],
});
}
},
error: function(e){}
});
}
JS 2nd Try
<button type='button' class='btn btn-dark btn-round' onclick='viewTablePerson(""+value.fullname+"")'>View Project</button>"+
function viewTablePerson(fullname){
var level = 3;
var fullname2 = fullname;
var obj = {
task_level : level,
fullname : fullname2
};
var params = JSON.stringify(obj);
console.log(params)
$('#viewProgress').DataTable({
ajax: {
url: url_api + '/api/user_task',
crossDomain : true,
type : "POST",
cache : false,
dataType : "json",
contentType: false,
processData: true,
data : params,
timeout: 10000,
},
destroy: true,
columns: [
{ data : "task_name"},
{ data : "task_owner"},
{ data : "task_status"}
],
});
}
Documentation says:
When using the ajax option to load data for DataTables, a general error can be triggered if the server responds with anything other than a valid HTTP 2xx response.
So, you have to check server-side response instead of search for problems on the front-end.
Also, in your case make sure
the plugin sends request to the same domain from which the current page is loaded;
browser security system doesn't prevent loading of external scripts - for example on http://localhost you cannot Ajax load a script from http://google.com without special measures;
you are specifying a relative path without a domain name (if you are using a single domain);
JSON data in response is a valid.
If you cannot alter the backend system to fix the error, but don't want your end users to see the alert message, you can change DataTables' error reporting mechanism to throw a Javascript error to the browser's console, rather than alerting it:
$.fn.dataTable.ext.errMode = 'throw';
I have been trying to create an application which needs multiple photos to be attached to one post. These are the following attempts i tried,
First i used facebook-node-sdk which JS SDK to achieve different functionality, but Official Js Sdk does't have option for file to upload, when then i moved to attaching/inserting photo itself to HTTP POST with the help of form-data, with the following code-
var form = new FormData();
form.append('file', fs.createReadStream(picPaths[0]));
form.append('message', "Hello"); //Put message
var ACCESS_TOKEN = "ACCESS_TOKEN";
var options = {
method: 'post',
host: 'graph.facebook.com',
path: '{Object-ID}/photos' + '?access_token=' + ACCESS_TOKEN,
headers: form.getHeaders(),
}
var request = https.request(options, function(res) {
console.log(res, false, null);
});
form.pipe(request);
request.on('error', function(error) {
console.log(error);
});
This works with one photo.
But as you can see in this github.com/Thuzi/facebook-node-sdk/issues/113 which i started, it is not possible to attach more than one photo.
So as mentioned by dantman i stated looking in batch process, which can be found developers.facebook.com/docs/graph-api/making-multiple-requests titled under Uploading binary data. The one thing that hits and give me hope is this one statement.
The attached_files property can take a comma separated list of attachment names in its value.
Note That (batching with photos) also is not possible with this library or JS SDK (Please correct me if i am wrong)
You can do post images with curl like this,
curl -F 'access_token=ACCESS_TOKEN' -F 'batch=[{"method":"POST","relative_url":"{Object-Id}/photos","body":"message=Test Post","attached_files":"file1"}]' -F 'file1=#image1' -F 'file2=#image2' https://graph.facebook.com
The above code posts with one image
So my question is this, it possible to attach multiple images/binary_files to the post with the help of curl, something like ..."attached_files":"file1,file2"... as suggested by docs, please help me with this problem and if you have already done this can you please post the snapshot of your code.
Thanks, Ravi
I finally figured out how.
So first, read the section here titled "Publishing a multi-photo post with uploaded photos": https://developers.facebook.com/docs/graph-api/reference/page/photos/#Creating
What it says is basically correct, however, it is not in JavaScript. Also, they don't emphasize enough an important step: You have to set "published" to "false" for the image you upload, for it to then be attachable to the post that gets created.
So anyway, here is the working code -- in JavaScript, and with "published" correctly set to false:
async function PostImageToFacebook(token, filename, mimeType, imageDataBlob, message) {
var fd = new FormData();
fd.append("access_token", token);
fd.append("source", imageDataBlob);
//fd.append("message", "photo message for " + filename);
fd.append("no_story", "true");
//fd.append("privacy", "SELF");
fd.append("published", "false");
// Upload image to facebook without story(post to feed)
let uploadPhotoResponse = await $.ajax({
url: "https://graph.facebook.com/me/photos?access_token=" + token,
type: "POST",
data: fd,
processData: false,
contentType: false,
cache: false
});
console.log(`Uploaded photo "${filename}": `, uploadPhotoResponse);
let uploadPhotoResponse2 = await $.ajax({
url: "https://graph.facebook.com/me/photos?access_token=" + token,
type: "POST",
data: fd,
processData: false,
contentType: false,
cache: false
});
console.log(`Uploaded photo "${filename}": `, uploadPhotoResponse2);
let makePostResponse = await $.ajax({
"async": true,
"crossDomain": true,
"url": "https://graph.facebook.com/v2.11/me/feed",
"method": "POST",
"headers": {
"cache-control": "no-cache",
"content-type": "application/x-www-form-urlencoded"
},
"data": {
"message": "Testing multi-photo post2!",
"attached_media[0]": `{"media_fbid":${uploadPhotoResponse.id}}`,
"attached_media[1]": `{"media_fbid":${uploadPhotoResponse2.id}}`,
"access_token": token
}
});
console.log(`Made post: `, makePostResponse);
}
The code above currently just uploads the same image twice, then attaches both to the new post. Obviously, in real world usage you would replace the data in the second photo-upload with a different image.
Anyway, to use the function, just call it like so:
function dataURItoBlob(dataURI) {
var byteString = atob(dataURI.split(",")[1]);
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ab], {type: "image/png"});
}
let imageDataURI = GetImageDataURIFromSomewhere();
let imageBlob = dataURItoBlob(imageDataURI);
PostImageToFacebook(fbToken, "some_filename", "image/png", imageBlob, window.location.href);
this is possible.
Note: This one is not an efficient way to do this but just for explaining purpose i am doing here,
The first hint that i got that it may be possible is from this post
Steps that i used:
Follow the doc to create custom open graph stories
Let's suppose you four image to attach (pic[1, 2, 3, 4])
First i staged them with the help of new facebook-node-sdk v1.1.0-alpha1 with the code something like this (with batch process).
FB.api( "", "post", {
batch: [
{
method: "POST",
relative_url: "me/staging_resources",
attached_files: "file1",
type:"image/png"
}, {
method: "POST",
relative_url: "me/staging_resources",
attached_files: "file2",
type:"image/png"
}, {
method: "POST",
relative_url: "me/staging_resources",
attached_files: "file3",
type:"image/png"
}, {
method: "POST",
relative_url: "me/staging_resources",
attached_files: "file4",
type:"image/png"
}],
file1: fs.createReadStream(picPaths[0]),
file2: fs.createReadStream(picPaths[1]),
file3: fs.createReadStream(picPaths[2]),
file4: fs.createReadStream(picPaths[3])
},
function(response) {
console.log(response);
});
Now from the response part get the url and dis the post with the same library. With the code something like this.
FB.api(
"me/objects/{app-namespace}:{custom-object}",
"post", {
"object": {
"og:title": "Sample Post",
"og:image[0]": {
"url": "fbstaging:{...}",
"user_generated": true
},
"og:image[1]": {
"url": "fbstaging:{...}",
"user_generated": true
},
"og:image[2]": {
"url": "fbstaging:{...}",
"user_generated": true
},
"og:image[3]": {
"url": "fbstaging:{...}",
"user_generated": true
}
}
},
function(response) {
console.log(response);
}
);
Now, with these two piece of code you will be able to push multiple images/photo to the single post.
Note: this can make more sense or can be done with the help of named batch process which is being described here.
Thanks,
Ravi
Yet again another MVC issue. One day I'll look at my "MVC learning days" and smile.
So to the point and exactly as the title indicates; A constant 400 response, I've read numerous posts on SO and still cannot seem to get my logic working. If I may show you the logic, someone maybe able to help me.
Controller:
public JsonResult CreateExtendedProperty(ExtendedPropertyDefinitionViewModel extendedPropertyDefinitionViewModel)
{
//I originally had JsonResult as ActionResult, still no change.
var p = extendedPropertyDefinitionViewModel;
//Temp
//return Json(new { Success = false, ErrorMessage = "Error creating property" });
}
The Ajax/Javascript:
var extendedPropertyDefinition = JSON.stringify({
DefinitionId: '0',
Title: propertyInfo["Title"],
OrganisationId: '0',
Organisation: '',
TypeId: propertyInfo["TypeId"],
SortOrder: 0,
IsEnumerated: propertyInfo["IsEnumerated"],
AllowMultiSelect: propertyInfo["AllowMultiSelect"],
IsDate: propertyInfo["IsDate"],
LastUpdatedBy: "",
LastUpdatedDateTime: new Date().toISOString(),
CreatedBy: "",
CreatedByDateTime: new Date().toISOString(),
Options: {
OptionId: '0',
Option: '',
OptionValue: '',
SortOrder: 0,
LastUpdatedBy: '',
LastUpdatedDateTime: new Date().toISOString(),
CreatedBy: '',
CreatedByDateTime: new Date().toISOString(),
}
});
$.ajax({
url: "<%= Url.Action('CreateExtendedProperty', 'Organisation') %>",
contentType: "application/json; charset=utf-8",
dataType: "json",
//traditional: true,
type: 'POST',
data: extendedPropertyDefinition,
success: function(e) {
alert('success');
//Rebuild Grid?
},
error: function(e) {
alert('request failed (500)');
}
});
The payload:
Hopefully someone can put on the right path, all will be much appreciated.
Regards,
So to just get the answer from comments - you have to ensure that <%= Url.Action('CreateExtendedProperty', 'Organisation') %> gets compiled. If it is in a separate JS file you have to pass it from your view. Otherwise it could be some other problem(if you are using Razor syntax, it should something like #Url.Action("CreateExtendedProperty", "Organisation"))
I'm using FlexiGid for my project.But the problem is WebMethod not firing.(Json/Ajax call)
I have put a Debug point to the Webmethod but it's not firing and also Firebug shows the web method Url is correct.
Here i have put the code
Ajax Call
function flexgrid() {
debugger;
$("#flex1").flexigrid({
url: '/WebMethods.aspx/GetIssueSummaryById',
dataType: 'json',
contentType: "application/json; charset=utf-8",
colModel : [
{display: 'ID', name : 'id', width : 40, sortable : true, align: 'center'},
],
data: JSON.stringify({ ProjectId: "1", UserId: "1" }), //Hard code this values at this time
buttons : [
{ name: 'Add', bclass: 'add', onpress: test },
{ name: 'Delete', bclass: 'delete', onpress: test },
{separator: true},
{name: 'A', onpress: sortAlpha},
{name: 'B', onpress: sortAlpha}
],
searchitems : [
{ display: 'Project', name: 'project' },
{display: 'Name', name : 'name', isdefault: true}
],
sortname: "id",
sortorder: "asc",
usepager: true,
title: 'Issue Summary',
useRp: true,
rp: 10,
showTableToggleBtn: true,
width: 1000,
height: 500
});
};
Web Method( thats in WebMethods.aspx file )
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<IssuesVM> GetIssueSummaryById(string UserId, string ProjectId)
{
//Guid LoggedInUserId = new Guid(UserId);
//int ProjectId = Convert.ToInt32(ProjectId);
List<IssuesVM> lst = new List<IssuesVM>();
try
{
SqlCommand comIssueSummary = new SqlCommand("SP_GetIssuesByProjectIDAndOwnerId", conn);
comIssueSummary.CommandType = CommandType.StoredProcedure;
//comIssueSummary.Parameters.Add("#ProjectId", SqlDbType.Int).Value = ProjectId;
// comIssueSummary.Parameters.Add("#UserId", SqlDbType.UniqueIdentifier).Value = LoggedInUserId;
if (conn.State == ConnectionState.Closed)
conn.Open();
SqlDataReader rdr = comIssueSummary.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rdr);
foreach (DataRow r in dt.Rows)
{
//Some code goes here
}
}
catch (Exception)
{
throw;
}
return lst;
}
After that Firebug shows this
Image Here
Can anyone know the Error for this ? Not firing webmethod ?
P.S - I saw some solution in below post[Click Here], I did thatone to the flexigrid.js file but it also not working.
Here is the Change
FlexiGrid.js file (before change )
$.ajax({
type: p.method,
url: p.url,
data: param,
dataType: p.dataType,
success: function (data) {
g.addData(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
try {
if (p.onError) p.onError(XMLHttpRequest, textStatus, errorThrown);
} catch (e) {}
}
});
},
FlexiGrid.js (After Change )
$.ajax({
contentType: "application/json; charset=utf-8",
data: "{}", // to pass the parameters to WebMethod see below
success: function (data) {
g.addData(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
try {
if (p.onError) p.onError(XMLHttpRequest, textStatus, errorThrown);
} catch (e) {}
}
});
},
So first off, it might be a good idea to move this to a WebService.asmx file. It is just best and common practice to do so. .ASPX pages respond with HTML/CSS/Javascript normally and .asmx responds with JSON or XML.
Either way, whether the Ajax calls for flexigrid are to a WebService or a Web Forms page, when you add the attribute [WebMethod] to expose a method doing the first Ajax call can be a bit challenging. There is something a bit finicky about Ajax calls to public WebMethods. The finicky arises around the content-type of the request and if the request is JSON or XML and if the response is JSON or XML.
So I am going to show you what I know works for a project I used Flexigrid:
$('#gridTablegSearchProperty').flexigrid({
url: 'Services/WSgSearch.asmx/gridTablegSearchProperty',
colModel: [...
You will notice in the first code snippet I do not set the contentType or the dataType properties of Flexigrid.
And now my WebMethod signature
[WebMethod]
public XmlDocument gridTablegSearchProperty()
{
System.Collections.Specialized.NameValueCollection nvc = HttpContext.Current.Request.Form;
int pgNum = nvc.GetValueAsInteger("page").GetValueOrDefault(1);
int pgSize = nvc.GetValueAsInteger("rp").GetValueOrDefault(20);
string sortName = nvc.GetValueOrDefaultAsString("sortname", "key");
string sortOrder = nvc.GetValueOrDefaultAsString("sortorder", "desc");
string query = nvc.GetValueOrDefaultAsString("query", string.Empty);
string qtype = nvc.GetValueOrDefaultAsString("qtype", string.Empty);
My WebMethod is in a .asmx file, it will not matter if you keep yours in a code behind file but I would move to a WebService and drop the WebMethods.aspx this is poor naming convention and file use convention.
I have a Facebook SDK Batch, and one of the requests is returning the following error:
"error": {
"message": "Unsupported get request. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api",
"type": "GraphMethodException",
"code": 100
}
Here's the Batch:
FB.api('/', 'POST', {
batch: [
{
method : 'GET',
name : 'user',
relative_url : '/me'
},
{
method: 'GET',
name : 'post-ids',
relative_url: '/group-id/feed?fields=id',
omit_response_on_success : false
},
{
method : 'GET',
name : 'post-data',
relative_url : '?ids={result=post-ids:$.data.*.id}&fields=id,actions,application,from,to,message,message_tags,with_tags,picture,place,properties,source,status_type,link,description,caption,attachments,object_id,type,created_time,updated_time,likes.summary(1),comments.summary(1)',
omit_response_on_success : false
},
{
method : 'GET',
name : 'post-user-info',
relative_url : '/{result=post-data:$.data.*.from.id}/',
omit_response_on_success : false
},
{
method : 'GET',
name : 'post-likes',
relative_url : '?ids={result=post-ids:$.data.*.id}/likes?limit=5000',
omit_response_on_success : false
},
{
method : 'GET',
name : 'post-comments',
relative_url : '?ids={result=post-ids:$.data.*.id}/comments?fields=id,actions,application,from,to,message,message_tags,with_tags,picture,place,properties,source,status_type,link,description,caption,attachments,object_id,type,created_time,updated_time,likes.summary(1)&limit=5000',
omit_response_on_success : false
}
]
}, function (response) {
The fourth request, name post-user-info is the errant request. Basically, for each post, I want to get the information (profile picture in particular) about the user that created the post. What's the best way to do this?