I am currently utilizing CF session management and have been investigating transitioning to utilizing J2EE session management. In my attempts to do so, ajax requests made ( when CFsession management is set to use J2EE sessions ) to CF cfc remote methods fail the verifyclient authorization. The code below works when session management uses CF session management.
My assumption is that the _cf_clientid is no longer the correct value to pass to the remote method - as it is generated using cfid and cftoken.
How do I successfully implement J2EE session management and utilize remote cfc methods with verifyclient? Or can it not be done? Using CF tag cfajaxproxy is not an option.
The example code below demonstrates how to use jQuery ajax to call a remote cfc method with verifyclient='true', even though CF documentation indicates that the use of cfajaxproxy is required. This is not the case. (Thanks to Ray Camden and DWMommy. ) This leads me to believe that there may also be a work-around to implement a similar method for verifying a client when using J2EE sessions.
Thanks in advance!
<script src="/plugins/jquery-1.7.2.min.js" type="text/javascript" language="Javascript"></script>
<cfajaximport />
<script>
$(function() {
$.ajax({
url: 'test.cfc',
type: 'get',
dataType: 'json',
data: {
method: 'sayHello',
yourname: 'Foo'
,_cf_clientid: _cf_clientid
},
success: displaySearchResults
});
});
</script>
<script>
function displaySearchResults(res){
$('#searchResults').html( res );
}
</script>
<div id="searchResults"></div>
test.cfc
component{
remote any function sayHello ( string yourname = 'anonymous')
returnformat='JSON' verifyclient='true'{
return 'Hello ' & arguments.yourname;
}
}
Related
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...
I'm creating a webproject in pyramid where I'd like to update a table every few secondes. I already decided to use ajax, but I'm stuck on something.
On the client side I'm using the following code:
function update()
{
var variable = 'variable ';
$.ajax({
type: "POST",
url: "/diagnose_voorstel_get_data/${DosierID}",
dataType: "text",
data: variable ,
success: function (msg) {
alert(JSON.stringify(msg));
},
error: function(){
alert(msg + 'error');
}
});
}
Pyramid side:
#view_config(route_name='diagnose_voorstel_get_data', xhr=True, renderer='string')
def diagnose_voorstel_get_data(request):
dosierid = request.matchdict['dosierid']
dosieridsplit = dosierid.split
Diagnoses = DBSession.query(Diagnose).filter(and_(Diagnose.code_arg == str(dosieridsplit[0]), Diagnose.year_registr == str(dosieridsplit[1]), Diagnose.period_registr == str(dosieridsplit[2]), Diagnose.staynum == str(dosieridsplit[3]), Diagnose.order_spec == str(dosieridsplit[4])))
return {'Diagnoses ' : Diagnoses }
Now I want to put this data inside a table with zpt using the tal:repeat statement.
I know how to use put this data in the table when the page loads, but I don't know how to combine this with ajax.
Can anny1 help me with this problem ? thanks in adance.
You can do just about anything with AJAX, what do you mean "there's no possibility"? Things become much cleaner once you clearly see what runs where and in what order - as Martijn Pieters points out, there's no ZPT in the browser and there's no AJAX on the server, so the title of the question does not make much sense.
Some of the options are:
clent sends an AJAX request, server does its server-side stuff, in the AJAX call success handler the client reloads the whole page using something like window.location.search='ts=' + some_timestamp_to_invalidate_cache. The whole page will reload with the new data - although it works almost exactly like a normal form submit, not much sense using AJAX like this at all.
client sends an AJAX request, server returns an HTML fragment rendered with ZPT which client then appends to some element on your page in the AJAX success handler:
function update()
{
var variable = 'variable ';
$.post("/diagnose_voorstel_get_data/${DosierID}")
.done(function (data) {'
$('#mytable tbody').append(data);
});
}
client sends an AJAX request, server returns a JSON object which you then render on the client using one of the client-side templating engines. This probably only make sense if you render your whole application on the client and the server provides all data as JSON.
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>
I have an Ajax post call written in a separate ".js" file which I call in multiple pages.
My code looks like this:
$.ajax({
url: '/MyVirtualDirectory/Controller/Action',
type: 'POST',
dataType: 'json',
....
....
})
Each time I change my virtual directory in my server, I'm required to change the code in "URL" to make my Ajax call working.
Is there any method that can make my code independent of my "Virtual Directory" name in IIS ..?
My application is MVC3.
Description
You should use the Url.Action method. But in your case, a seperate js file, you cant access this method. So i would create a javascript variable for each url in your view. Then you can use this variable in your js file.
UrlHelper.Action Method - Generates a fully qualified URL to an action method.
Sample
Your View
<script type="text/javascript">
var myUrl = '#Url.Action("actionName", "controllerName")';
</script>
<script type="text/javascript" src="yourJsFile.js"/>
Your js file
$.ajax({
url: myUrl,
....
})
Update
Another way is to store your url in a hidden field inside your view and get the hidden fields value inside your js file.
More Information
MSDN - UrlHelper.Action Method
I finally found a partial work around.
In my .js file i did some dirty coding like this:
var Path = location.host;
var VirtualDirectory;
if (Path.indexOf("localhost") >= 0 && Path.indexOf(":") >= 0) {
VirtualDirectory = "";
}
else {
var pathname = window.location.pathname;
var VirtualDir = pathname.split('/');
VirtualDirectory = VirtualDir[1];
VirtualDirectory = '/' + VirtualDirectory;
}
$.ajax({
url: VirtualDirectory/Controller/Action,
....})
The basic idea is I check the URL for localhost and port number. If both are there, it means that then I'm debugging in my local machine and so I don't need virtualdirectory in URL. If I'm running a hosted version then there won't be localhost and port number in my URL(provided I'm hosting on port 80).
And by this way when I run on my local machine while debugging the url will be only Controller/Action and while I host the URL will be VirtualDirectory/Action/Controller. It works fine for me now.
But please post if there is any other simple method.
I think it would be safer to declare a global Javascript variable and then set the variable for the first time, maybe when Home/Index fires. and then reuse it in every ajax calls like so:
$.ajax({... url: GlobalVariablePath + "Controller/Action/RouteValues" ...})
if you already designed your WebApp and every thing works fine and stuck when site is deployed, then you can manipulate the all ajax URLs like so:
$.ajaxSetup({
beforeSend: function (jqXHR, settings) {
settings.url = GlobalVariablePath + settings.url;
}
});
Using this way, you can safely use the existing js codes and leave the rest without change.
I am in a bit of a pickle right now. I am building a web page that will get data from a CGI backend. I have no control over the CGI backend, nor the server (so no mod_headers or mod_expires). Also, because of the parameters to the script, I cannot append a unique value (like '&089u0af0d98) to each request. The requests are AJAX using the XmlHttpRequest object. I have tried to set the 'If-Modified-Since' and 'Cache-Control' request headers unsuccessfully. Does anybody have any other ideas for how I can prevent the AJAX response from being cached by the browser?
You can send random parameters using POST, while sending the important vars using GET if you need to.
If you have problems with IE, I know that sending something with POST makes it to stop caching server responses
I use this javascript function ( which in turn uses jquery.ajax function )
the cache: false would do the trick.
This works perfectly for me , may be you can give it a try
function ajax_call(urlString)
{
ret_val="";
$.ajax
(
{
type: "GET",
url: urlString,
async:false,
cache:false,
dataType: 'html',
success: function(msg)
{
ret_val=msg;
},
error:function (xhr, textStatus, thrownError)
{
ret_val=xhr.readyState;
alert("status=" +xhr.status);
}
}
);
return ret_val;
}
I used $.ajaxSetup({ cache: false }); somewhere in my base html-page (default.aspx) in a non-frequent web-system and it worked fine. No pain-in-the-neck caching problems anymore.
I ran into this today, and found that if you want to keep to using get, you can add a hidden form element to the page and have JS set it's value to the current timestamp before submitting the query to ajax.
I add a form element something like this:
<input type="hidden" name="ie_sucks" id="ie_sucks", value="1" />
Then, in the function to submit the form via AJAX I set this hidden input to the current timestamp with something like this:
$('#ie_sucks').val(new Date().getTime());
The above code uses JQuery, so in pure JS it would be something like:
document.getElementById('ie_sucks').value = new Date().getTime();
This is not a pretty solution, but it does work.
I know jQuery's .ajax() call has a parameter called 'cache' which, if set to false, will force requested pages not to be cached by the browser. It's probably worth checking the jQuery source to see how they do it.
(I'm checking it now and will update if I find anything, but posting this answer early in case you or anybody else has better luck finding it.)