Call from JavaScript to server-side code in JSF - javascript

I'm looking for an easy way to call a bean's method that will take no parameters and return a string in JSF. The thing that I don't really need is that the method returns an action result and then uses the whole JSF life-cycle to do get me to another view. I need to do that from JavaScript so that I can put together some client-side parts of the application and going over the A4J part of RichFaces has brought me nothing so far.
So here's the scenario again in a step-by-step form:
from JS issue a GET on some address
on the server process that GET and return JSON or HTML (basically a string)
once the request is sent back to the client I want to be able to process it further with JS.
Thanks!

Use a4j:jsFunction and the data attribute.
So roughly you want something like:
<button onclick="callBackend();">Go</button>
<a4j:jsFunction name="callBackend" action="#{myBean.someMethod}" data="#{myBean.someString}" oncomplete="handleResponse(data);"/>
<script>
function handleResponse(response) {
alert(response);
}
</script>

Damo: can you explain why it might only work for the first time the method callBackend is executed? I'm experiencing a strange behavior that the first call succeeds and the next calls are just blocked. I see the server-side code being executed but some strange result is being sent back to the browser (something like the _viewstate and those kind of things).

Related

loading javascript functions returned from an ajax request (named functions)

I am attempting to load javascript functions from a view generated from an ajax request. Thus far I have looked all over the internet and found this eval() function, however, I need to load named functions to memory to be called on events made by the newly added html. Does anyone know what method to use or how to accomplish this?
Note: The only way I can think of is to include the returned javascript functions in the page itself (and not return them along with the html), however, I would like to avoid this if possible.
Note Update: I can't include it on the app.blade.php because the ajax request needs to add in a few variables set at the time of the ajax request before the client receives the ajax response. Thus, the only method to accomplishing my objective is to somehow load my newly added scripts to the client buffer.
When the ajax request runs, it returns something like this:
<script>
function somefunction(){
//some stuff
}
</script>
<div>
sometext
</div>
Thanks.

Is it possible to use a javascript variable inside of a javascript variable that contains php?

I'm trying to use a JS variable inside of php code that executes a function. Based on the selected radio button, Javascript gets a string of code from a data attribute of the radio button (trimcode) and I need to set this as the key in my PHP function where one of the variables requires an array key.
The result will be, whenever a radio button is selected, the PHP function inside this function will execute using the 'code' variable and thus return it's return value as the inside content of the "byo" class div via javascript innerhtml. However, I can't figure out how to use a javascript variable inside of PHP code that is inside another javascript variable. Can someone point me in the right direction?
<script type='text/javascript'>
$(document).ready(function(){
var code;
var colorsavailable;
$("input:radio[name=trimlevel]").click(function() {
code = $(this).data("trimcode");
colorsavailable = ("<?=byoTrimImageColors($modelMap["+code+"],$hexcolors)?>");
$('#byo').html(colorsavailable);
});
});
});
</script>
I think you're confusing the notions of server-side code and client-side code.
The PHP code runs once, in its entirety, when the page is requested. Then, after it's executed, the resulting page is sent to the browser where the JavaScript code runs. And that line of PHP code isn't going to execute for each click event. It's going to execute once, and only once, and emit only one result to the page.
Given what it looks like you're trying to do, you probably have two options:
Include the functionality you're invoking in JavaScript code and just invoke it there instead of in PHP code. Whatever that array is, whatever that function is, implement those in JavaScript. Then there's no need to involve PHP at all.
If the functionality needs to be in server-side code, then you're going to need to use AJAX to invoke it. Essentially you'd create a separate PHP "page" (which emits JSON data, not an actual page) to accept the value, invoke the functionality, and emit the result. The JavaScript code would make an AJAX request to that resource and use the result.
Client-side, that AJAX call might look something like this:
code = $(this).data("trimcode");
$.post('someNewPage.php', { code : code }, function (result) {
$('#byo').html(result);
});
Server-side (and I'm mostly guessing here), someNewPage.php might have something like:
$code = $_POST['code'];
// you'll want to sanitize the $code value here, since it's user input
$result = byoTrimImageColors($modelMap[$code],$hexcolors);
echo json_encode($result);
Your idea is not possible since for PHP code to execute it requires a page refresh. The best solution would be using Ajax to send the data to PHP asynchronously and changing your HTML, using JS, with the data that comes back from PHP.
To learn how Ajax/PHP works visit this site: http://www.w3schools.com/php/php_ajax_php.asp.
It is not possible to call a PHP function from Javascript. PHP is a pre-processor and ALL PHP code will finish executing before the page loads. Once the page loads, the browser will load your Javascript files and JS will take it from there.
In order to "call a PHP function" again after the page has loaded, you will need to make a new request to the page. This is typically handled in Javascript via AJAX. Using ajax, Javascript can send a new request to the server, PHP will read it and send a response back to Javascript.
If you really need that PHP function to execute on the Javascript level synchronously, then consider porting that function to Javascript.
Right now what you are doing is constructing a string that resembles some PHP code. It looks like you are doing that part just fine.
However, you cannot execute PHP code on the client side. There is no interpreter available on the client (the browser) that knows what to do with your PHP code.
What I would recommend doing is if you need to run some PHP code, create a controller method or some script that you can execute on the server, make an AJAX request to that (passing the JS code variable), have the PHP method return the value of your byoTrimImageColors method, and then handle that data however you please.

sending data to another website and receive result

If i have a website1.com and website2.com, can I send data ( ex: value from input ) from website2.com to website1.com and receive result? with no page refresh or redirect. I'd like to use only javascript & ajax, no PHP or jQuery. If it is possible give me an example how to do it.
I thought about creating an script element ( with javascript) on website2.com with src like : website1.com?data=<value from input>, and when script element loads the src, it will show me an result, but maybe there is a better option to do this.
PS: I will have more separated datas to send.
Note: this is not XSS, just a public project for websites, which will need to update datas every x minutes and to send some data to website1.
Thanks.
Your question is not completely clear, but in general when you have to do cross-site AJAX you have to use JSONP
Since XmlHttpRequest does not work cross-domain, you have to use JSONP. Basically, this is adding a script tag dynamically as you're suggesting to do. Then, the server uses your GET datas, does whatever it wants, and usually "prints" a callback function.
When you call a file using the script tag, it will evaluate everything displayed. This is why, if, on the server side, you're doing :
<?php
echo 'alert(1);';
?>
This will be evaluated as javascript. You can then easily understand how to use a callback function (another GET parameter).
Also, in jQuery, there is an option called 'jsonp' when you call $.ajax (using "callback" as default GET parameter, but can be changed).
You could have some XSS issues but it is possible you could use ajaxgold. It is an pretty easy manner to send pretty much everything over.
Call send to website2
postDataReturnText( 'http://website2.com', 'data=bla', getResult );
Return the result
function getResult( text ) {}

How to make sure that a Javascript function is called after EVERY postback in Liferay/ICEFaces?

I have very little experience with Liferay and ICEFaces. I need to build a portlet that calls a specific Javascript function every time a postback occurs.
In fact, when the form is submitted through AJAX, a loading screen appears and blocks the screen. When the postback completes, I need to take it out and give control to user again.
I have tried to put the <script> snippet in the portlet's body and it succeeds in executing when the page is first loaded (it's ok) and also when a postback changes the page's HTML content.
The problem is, when the server doesn't change the HTML (ie. a search returned with no result, you search again and you still get no results) the function is not executed again.
Even if I could post some code, I have very little idea of the architecture the web application is built on. What I gave here is all the information I have. By editing the javascript function to emit alerts when it's called I found the behaviour of the page.
Can you help me with that?
Have you tried the following:
<script>
Ice.onSendReceive('document:body',
function(){/*Before send ajax request*/},
function(){/*After receive the response*/}
);
</script>
But this solution applied for every ajax request you made, hope this can help you.
I made it using a weird trick with random numbers I want to share.
First, in the backing bean property I created a method
public String getLoadFunction()
{
return "functionName("+ new Random().nextDouble() +");";
}
and then
<script>
#{MyViewBean.loadFunction}
</script>
"Simply", ICEFaces is so smart it checks if the HTML has been modified or not when processing AJAX requests. This trick is very similar to appending a random number to HTTP URLs to avoid caches.

When is a postback not a postback? (according to ASP.net)

Is there a difference between me using Javascript to redirect to URL + "?Querystring=value" versus using whatever mechanism ASP.NET uses?
If there is a difference, how can I make the rendered ASP.NET page be submitted to the same URL with a different query string by javascript?
If you want to do a post back just like a asp control like a asp:Button you can use the javascript functions included by the framework to do so:
__doPostBack('ControlIDOfEventYouWantToRaise','');
You can read more about the __doPostBack in this article:
Doing or Raising Postback using __doPostBack() function from Javascript in Asp.Net
Just doing a form.submit() will not be exactly the same as using __doPostBack.
To answer the first part of your question there is no difference doing a redirect if you are just doing a Response.Redirect as the will both do a GET. The difference is if you use a asp:Button control for instance, it will access your page first to handle the button (a post back) and then do a GET on the redirected page.
If you want to submit to the same URL (eg post your data) then you should use the __doPostBack method. If you don't require the data to be posted, then just do a redirect in javascript to the same URL with a modified query string (which will just do a basic GET) but your data will not be posted.
The only potential difference is that a querystring parameter is sent via GET, a form is (usually) sent by POST.
GET has a much smaller data limit as browsers have a max URL length (it varies)
You could use javascript to do a form.submit() which shoul emulate what ASP.Net does
I somewhat disagree with Basiclife's answer; if you have any code inside something like
if (IsPostBack) {
it's not going to be equivalent, ie the code is going to be executed if you're just setting the URL. Also, controls keep their state across postbacks but are freshly initialized if you're calling the URL again. This is due to ASP.NET trying to emulate a "normal" application, so the way to make sure a normal call and a postback have the same effect might result in "de-ASP.NET-ing" the entire page.
I'm not sure if what you want works. There probably is a way. But I heavily suspect there's a better way of doing this. If you get a postback for free, and can transmit data, why is it crucial that the data shows up in the URL, instead of being comfortably posted? I can see how you want a page to respond to a URL parameter, and how you might want to change the same parameter later on based on what's happening on that page, but since you always know you're posting back, you can eg override that URL parameter in that case, by something you're posting back. This doesn't sound so nice, but it might actually be less messy. Particularly since you seem to have a reason to not abandon the postback at all (otherwise you could just use a link, right?).

Categories

Resources