pageLoad in MVC - javascript

In ASP.NET I usually use pageLoad() JavaScript function, that gets executed every time the page sends a request even with Ajax (UpdatePanel).
Is there anything like that in Razor?
I mean a JavaScript function to get executed for every ajax request without using OnSuccess or something like that in AjaxOptions.

If you want a javascript function to run every time your page loads then you need to include the script you want at the top bottom of every page you want it to execute on
Then inside of that you'll have the js you want to run.
If you're using jquery then I suggest using $(document).ready()
Edit
Alternatively if you want some csharp/vb to run every time your page loads then you need to create a constructor in your controller and place the necessary code in there.

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.

Keep timer (setInterval) running while reloading page

Once I load a webpage, I insert some Javscript via the console. I was wondering if it's possible for me to, using either Javascript or jQuery, reload the page (not from cache) while keeping a setInterval that I have running. I'm familiar with location.reload(), but that terminates it.
When you reload a page, the entire page context including all running JS is completely destroyed. You cannot keep a setInterval() running while its host page is reloaded.
You can create a signal for the new page to start the interval going again itself using a cookie, query parameter or local storage value (query parameter is probably the most appropriate). If you go this way, then you need to code the page to look for a specific query parameter and if it finds it, then the page should start the designated setInterval() itself. You can even pass some data in the query parameter (such as how much more time until the next interval should fire, etc...).
Another option is to not actually reload the page, but instead to refresh the content manually by getting new content via an ajax call and then inserting it into the current page. This allowed the current page context and running interval timers to continue running.
Not possible unless you fetch the page using Ajax request, then replace the body while the setInterval Is working

How to run a javascript function when ANY page is loaded

I am doing some maintenance work to a fairly large existing site written in PHP & JavaScript. I am trying to set up a "time out" so that the user is automatically logged out after a specified period of time. I think I have the code that will "expire" the users session, but what I need is a way to run a specific javascript function whenever ANY of the pages in the existing system are loaded. I'd rather not manually add a call in each page as this would take forever and would require even more testing.
Is there a way to add a javascript function call to the window or some other part of the DOM to get called whenever a page is loaded?
Thanks for any help!
There are many ways to achieve this. BUT, you will have to first include a reference to the javascript file.
Then, you can, for instance, use jQuery to detect that the DOM is loaded and ready to call a function of yours.
On a side note, can I ask you why you need to call a javascript function? There are probably other ways to do that, like a listener on your server that redirects to a logout page when a session expires.
Write the javascript in a .js file, host it on your server, and link to the .js from all the pages. While this does not apply a global rule, it is the only way I can think of and it won't be a problem for testing as the code will be from one source.
No.
You have to have the javascript function load into every page. But you just have to write it once and then include like:
<script src="logout.js"></script>
and then you'll need to set the timer for the logout
<body onload="setLogoutTimer()">
But in order for every page to have it you either need to explicitly place it in every page.
That depends to your site script. If you're checking your session data on every request this could be done easily.
Add time data for a session's last move, append it to a js script which controls that If it's time to end the session or not. And take action(js redirect or an ajax request)

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.

Call javascript function when consuming event in codebehind

I have a aspx page that, when loading, will initialize a class called, Bill :)
When Bill is initialized, the aspx page will wire a function to a handler of Bills.
When that function in Bill is fired, I would like to call a javascript function in the aspx page, but that is where I am having difficulties...
I have tried ClientScript.Register and all of that, but nothing is seeming to work. As of now, I am simple trying to get the function to fire an alert.
I have a feeling that I am missing something critical in the understanding of this, so any information would be greatly appreciated.
Thanks.
Is all of this happening in javascript, or is some of this server-side code? Javascript is client-side only, so if you are running server-side code, you can't execute the javascript on the server. You can, however, register script to run when the page renders in the browser (be careful of this, if you are opening another window, actions like this will be blocked by the browser unless the user directly initiates the action by clicking a button or something similar).

Categories

Resources