Liferay 7.2 - Resource URL is calling same instance - ajax

I have two or more equal portlets on the same page. And the portlet itself has a Resource URL request.
So let's suppose that I have on the same page my portlet_pages_INSTANCE_1 and portlet_pages_INSTANCE_2, and the relevant code for the portlet is:
JSP:
<liferay-portlet:resourceURL var="loadDocuments" />
<i class="fa fa-angle-double-left" onclick="paginate()"></i>
<script>
function paginate() {
$.ajax({
type: 'POST',
url: '${ loadDocuments }',
data: {
'<portlet:namespace />someData': someData
},
success: function(data) {
// handle the success
}
});
}
</script>
This works wonders if only one instance of the same portlet is in the page. But it has a strange behaviour if more than one of the same portlet is added to the page.
After some debugging I tried to:
#Override
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws IOException, PortletException {
System.out.println(themeDisplay.getPortletDisplay().getInstanceId());
}
And noticed that dispiting clicking on the paginate button on different portlet instances, the serveResource prints only the latest portlet that I added instance.
Is there any way to make the ajax call to the a specific portlet instance?

You have multiple definitions of your paginate method per resulting HTML page. You'll need to namespace it, or parameterize a common implementation.
For javascript, one of those method overloads the previous

Related

Create rest service Umbraco 7 backOffice

I read a lot on this issue.
I read that I can use at web api asp.net to create rest service in Umbraco.
Can I create this api in Umbraco back office?
If not, how do I connect the service to my local Umbraco site?
I can't find a simple tutorial that shows this.
EDIT:
I want to get Umbraco content data in client side.I read that I can create in server side(Umbraco) rest service that I can get data when I call to specific url to my Umbraco server.
Take a look at https://our.umbraco.org/DOCUMENTATION/Reference/WebApi/ - the article explains how to create controllers inheriting from UmbracoApiController.
EDIT - I added this example:
I made a controller like this:
public class PartnersController : UmbracoApiController
{
public IEnumerable GetPartners(string zip = "") { ... }
}
Then I used jQuery and AngularJS like this:
function getPartnersForZip($scope, $http) {
$http({ method: 'GET', url: '/umbraco/api/partners/getpartners/?zip=' + getQueryVariable("zip") }).success(function (data) {
$scope.partners = data;
});
}
<div ng-controller="getPartnersForZip" ng-cloak>
<ul class="dealer-list" ng-cloak>
<li ng-repeat="partner in partners"></li>
</ul>
</div>
This works for me. What have you tried?

liferay, jsf. How to javascript json object save to database

Need some help in the following case:
I have set an application as Liferay portlet and i am using JSF/Primefaces for builing my views. For data modelling i am using Hibernate.
In a certain view i load a so called "image annotator" which is using Javascript tools for gathering user input (annotation on an image canvas). This information i would like to be able to save in a file/database and then re-use when the user edits again a specific image.
Here is my view:
<h:head>
<script src="#{facesContext.externalContext.requestContextPath}/js/OpenLayers.js" />
<script src="#{facesContext.externalContext.requestContextPath}/js/image-viewer.js" />
<script src="#{facesContext.externalContext.requestContextPath}/js/xml2js/xml2json.js" />
<script src="#{facesContext.externalContext.requestContextPath}/js/xml2js/xml2json.min.js" />
...
</head>
...
<p:fieldset legend="Viewer">
<p:outputPanel layout="block" styleClass="imageEditorImagePanel" />
</p:fieldset>
....
So the image and the relevant jscript tools (OpenLayers) are loaded in imageEditorPanel placeholder.
The javascript code (image-viewer.js) gathers user input in a json (GEOJson) object, and this object i would like to pass to a back bean controller when Save button (jscript) is selected:
...
//define save button
var save = new OpenLayers.Control.Button({
title: 'Save', text: 'Save',
trigger: function(){
var GEOJSON_PARSER = new OpenLayers.Format.GeoJSON();
var vectorLayerAsJson = GEOJSON_PARSER.write(vlayer.features);
...
So i want to pass 'vectorLayerAsJson' object to a java controller (backbean) ...
I am trying to implement an ajax call like:
jQuery.ajax({
type: 'POST',
url: 'imageannotations',
contentType: 'application/json',
data: vectorLayerAsJson,
success : function(data) { alert("success")}
});
can anybody help on how am i going to make this ajax request as also how am i going to implement my controller class?
You can initiate a call to a java managed bean via Javascript using primefaces p:remoteCommand. Answers how to send the String as an argument can be found here.
In the managed bean/java controller, just have a String variable with getter/setter and an action method to start the unserialization (following is untested code):
#ManagedBean(name="testBean")
public class Test {
public String actionOnString() {
String value = FacesContext.getCurrentInstance()
.getExternalContext().getRequestParameterMap().get("param");
// do your unserialize and actions here
return "";
}
}
Within JSF have something like
<p:remoteCommand name="sendJSONToServer" action="#{testBean.actionOnString}" />
and as javascript on the desired position
sendJSONToServer({param: vectorLayerAsJson});
should do the job.
Direct ajax-push is also possible via PrimePush, using the athmosphere framework. Possibly, that might be overkill for what you try to achieve.
Update 1
Of course, when you get a JSON-Object serialized (so to say "n String format), you have to JSONize it in Javascript - this answer "How to parse JSON in JavaScript" might help you further regarding that.
Hope it helps...

Ajax with custom Form Authentication in MVC3 project

I have an MVC3 project with custom form authentication.
I got the authentication to work fine (I used the "HttpContext.Current.User.Identity.IsAuthenticated" property in order to make sure it worked)
I use on my of my forms an Ajax:
$(document).ready(function () {
$.ajax({
url: '/MyPages/MyControllerFunction',
type: 'POST',
success: function (result) { $('#MyJavaTemplate').tmpl(result).appendTo('#MyHtmlTable'); },
error: function (result) {
$('#errorDisplay').html(result.responseText);
}
})
});
When I get to this page (and the ajax should call this controller's function) I get this error:
HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
My controller function:
[HttpPost]
public ActionResult MyControllerFunction()
{
var MyEntity = MyBusinessLogic.GetByID(1);
return Json(MyEntity);
}
(I also tried to add the [Authorized] attribute and it didn't help)
It only happens to me with mhen I call the controller's function through ajax. Before I changed my program to work with form authentication, It all worked. It's as if the user is not authenticated (even though it is)
What should solve this problem?
I'm thinking you have a GET specified on that controller action, where is should be a POST
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult MyControllerFunction()
I FOUND THE SOLUTION !
It was here:
Getting 404s when calling Actions in MVC3 with jQuery
All I had to do is change the:
url: '/MyPages/MyControllerFunction'
to
url: '#Url.Action("MyControllerFunction","MyPages")'

Django API Requests

I'm trying to access another service's API, using my model's fields as the keywords in the API request. The URL would be like like so:
http://api.example.com/json/?first_name=FNAME&last_name=LNAME&key={key}
Here's my code from views.py:
class ExamplePersonView(ListView):
context_object_name = "example_person"
template_name = "templates/example_person.html"
def get_queryset(self):
lname = get_object_or_404(ExamplePeople, lname__iexact=self.args[0])
return ExamplePeople.objects.filter(lname=lname)
From what I understand, I'll need to use AJAX to communicate between my page template and my views.py to send the request and then present the information on the page.
I've found several Django apps that make it easy to turn your models into a public API, but none that help you access API's from another service. Does anyone know of an app like that?
If not, does anyone have a good understanding of using AJAX with Django to make the request and present it in the template?
There's several ways to communicate with a "foreign" API. There's no necessity for ajax. Ajax is just for making background calls in a template, triggering whatever event you have in mind.
But let's say you want to communicate with the facebook GraphAPI to retrieve a profile
http://graph.facebook.com/bill.clinton
The standard result is serialized as JSON, which implements easily into AJAX or any JavaScript library, hence the name JavaScript Object Notation.
So an example with AJAX might be:
function callFacebook() {
$.ajax({
type: "GET",
data: ({}),
dataType: 'json',
url: "http://graph.facebook.com/bill.clinton",
success: function(data){
alert("Hi I am former "+data.name);
}
});
}
callFacebook();
Include this in your javascript file or within your template between script tags and you should get a nice alert message:
Hi I am former President Bill Clinton
Now you could turn this alert into something more meaningful, and put it within a h1 tag (not sure why this is meaningful)
$("body").html("<h1>"+data.name+"</h1>");
But sometimes you would want to retrieve data and do something with it server side in your application.
So create a django urlpattern and view, e.g.:
from urllib2 import urlopen
from django.http import HttpResponse
from django.utils import simplejson
def call_bill(request):
url = "http://graph.facebook.com/bill.clinton"
json = urlopen(url).read()
# do whatever you want
return HttpResponse(simplejson.dumps(json), mimetype="application/json")
# add this to your url patterns
url("^call_bill_clinton/$", call_bill)
Now visit your url
As a logic result, it's also perfectly possible to trigger async events by some user action. Eg the URL parameter in the previously mentioned ajax example, could also be a django url like "/call_bill_clinton/".
<!-- add a button to call the function -->
<button onclick="callFacebook();">Call Bill</button>
function callFacebook() {
$.ajax({
type: "GET",
data: ({}),
dataType: 'json',
url: "/call_bill_clinton/",
success: function(data){
alert("Hi I am former "+data.name+" and I came from Django");
}
});
)
// remove the auto call
Furthermore ajax calls let you do the same trickery as http requests, you can use a variety of request methods combined with cool javascript events, like a beforeSend event
beforeSend: function() {
$('#loading').show();
},
Where the #loading could be something like:
<div id="loading" style="display:none;">
<img src="{% static "images/loading.gif" %}" />
</div>

How to Call an Action from a View and return its result?

I have defined an action on my controller which accepts an integer and returns a string value:
public string SqlQuery(int listItemId)
{
return _sqlListSharePointList.GetSqlQueryFromCache(listItemId);
}
How could I call this action from my view? also what other options do I have apart from AJAX?
I tried the below but didn't work:
$.get('/SqlReportList/SqlQuery', 1, function (data) {
alert(data);
});
the "SqlReportList" is the name of my controller.
I also tried the below code:
$.get('/SqlReportList/SqlQuery/1', function (data) {
alert(data);
});
But it threw an exception on production that the listItemId is null.
Should I decorate my Action differently?
I also tried accessing it via fully qualified name but same error:
http://localhost:4574/SqlReportList/SqlQuery/1
Thanks,
If you do not want to use ajax (which is recommended) then only way to call the method is thru page refresh, only that way you are hitting your server side (controller) again from the view.
$.get('/SqlReportList/SqlQuery', { "listItemId": listItemId }, function (data) {
$('#tbSqlQuery').text(data); }
);
Is the parameter known at the time of rendering the surrounding page?
If so (and I've understood your question correctly) then you can use Html.RenderAction. See http://haacked.com/archive/2009/11/17/aspnetmvc2-render-action.aspx
If not, then you can only really use AJAX or a full page reload. For getting the URL right for AJAX, you should be able to use Url.Action with some placeholder value.
The T4MVC project offers strongly-typed support for various things including action URLs, even supporting explicit placeholders for Javascript code. See section 2.2.2 of http://t4mvc.codeplex.com/documentation

Resources