ASP.NET MVC + Javascript (calling c# code with javascript variables) - javascript

is it possible to call c# functions with javascript parameters (from javascript)?
i.e.
<script>
function someFunction()
{
var data = "123";
var test ="<% AppHelper.GetSomething("+data+"); %>";
}
</script>
Thank You !

No, because ASP.NET code is run and compiled before you get to the javascript. If you want to communicate with the server using javascript, you need to use something like AJAX.
Or you might have a look at server side javascript, to see if that's something you can use.

You could do it but you would have to use an ajax call to hit a URL endpoint which will execute an action. Once the action has been triggered you can do what ever you want in c#.

What you want to do exactly because with jQuery it's very easy to do a call to a controller that return some HTML or data that you can use in javascript. I could give you an exemple if you give more details of what you are trying to do.

Related

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.

Accessing Javascript variables from JSF [duplicate]

This question already has an answer here:
How to invoke a JSF managed bean on a HTML DOM event using native JavaScript?
(1 answer)
Closed 1 year ago.
I have a JSF file that needs to get populated from the data I get from the JS function that I get from Ajax call to a web-service. The latter part works like a charm. I am able to retrieve the JSON data from the ajax call. I need to parse this json data and take data and use that to populate the JSF. I am unsure as to how I would access the JS variables from the JSF/xhtml.
Is is possible to do it in someway? I was going through some DWR stuff that would send ajax post from JS to the Java bean and I could use the bean variable from the JSF. But, I want to know if there is any other way of doing this.
I would greatly appreciate any help. I am using JSF 2.x btw.
Thanks,
S.
You can use the following 'hack' to get JS to submit information to JSF.
Create an invisible JSF form with <f:ajax> hook:
<h:form prependId="false" style="display:none;">
<h:inputText id="input" value="#{bean.input}">
<f:ajax event="change" execute="#form" listener="#{bean.process}" render=":something" />
</h:inputText>
</h:form>
Let JS update the input field and trigger the change event:
<script>
function somefunction() {
var input = document.getElementById('input');
input.value = 'your JSON string';
input.onchange();
}
</script>
Do the Java/JSF job in the listener method:
private String input; // +getter +setter
public void process(AjaxBehaviourEvent event) {
doSomethingWith(input);
}
Put the desired JSF markup in a <h:someComponent id="something"> which will be re-rendered by <f:ajax render=":something"> when the listener has done its job:
<h:panelGroup id="something">
The JSON string was: <h:outputText value="${bean.input}" />
</h:panelGroup>
That said, I'd prefer to do the webservice call in the constructor or action method of the managed bean instead of in JS. Your approach is literally a roundabout.
I think this is not possible.
JSF runs on server.
JavaScript runs on client (browser).
So, JSF runs BEFORE action in JS.
Of course, you can make a servlet that will be called from JavaScript, receiving information stored in JavaScript variables. But, this will be in next step:
JSF assembles the page
JavaScript call WebService, getting JSON data
JavaScript send JSON data to server (servlet)
You could revisit the design a bit and probably accomplish what you're looking for. Rather than accessing the webservice via ajax on the client you could access it server side by communicating with it directly in an action method or a method that occurs before the view is created (prettyfaces actions handle this kind of work nicely). Then you can construct your view dynamically based on the results of the response from the web service.
I'm not 100% sure that will accomplish what you are looking for but that general idea might work for what is sounds like you're going for.
If you've already rendered a view and you want to do it with ajax you could use f:ajax with the same principle -- hit action method, communicate with webservice server side in that action method, change state of variables that determine the view layout and render the response.

How to call a .cs method from a JavaScript function?

I need to call a .cs method from JavaScript function; how can I do that?
Thanks
You need to do post back to the server then catch this post back on Pageload event then execute the cs function.
check the following article:
Understanding the JavaScript __doPostBack Function
You need to postback to the server by either submitting an HTML form or using JavaScript. If you're not in a browser, it might be more of a challenge because I don't think the Windows Scripting Host includes anything that can call the web by default. In which case you could use something like cURL instead.

Call from JavaScript to server-side code in JSF

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).

PageMethods with ASP.Net MVC

I have found ASP.Net PageMethods very handy and easy to use, but I have just started developing using MVC and am not sure how to use them?
What is the equivalent of PageMethods.MyFunction() in MVC where MyFunction is a Controller action?
I know I can use the Json function to return a value, but how do I call the action from the client?
I know I can use the Json function to
return a value, but how do I call the
action from the client?
I think you're looking for either getJSON
$.getJSON("/controller/action", function(json)
{
alert("JSON Data: " + json.users[3].name);
});
or the ajax jQuery method.
Either can call an action and get JSON data back from ASP.NET MVC very easily.
I don't think you need page methods. Page methods in asp.net are a way to expose methods in the page class to your client-side code.
In MVC, you don't have a page class, so you can just issue an XHR to a url (../controller/action/params, or whatever), and return JSON from the action.
Update:
After re-reading your question, it sounds like you want to know how to issue an XHR from the client. In raw javascript, you can just use the XMLHttpRequest object, but whatever JS library you are using probably has a nicer wrapper. jQuery's, for instance, is here

Categories

Resources