How to detect if a user leaves a page in PHP - javascript

There is this function which i want to execute in case the user leaves a particular page. This function will basically change all of the data within a certain column in my database. So in case the user leaves this page, i want this function to be performed by the system. Is there a way to detect if the user already left the page.
Thanks!

With 100% reliability, no, it's not possible. Since leaving a particular page is a client-side operation, you have 0 control over what the client does. You can register an onbeforeunload handler via Javascript and hope that the client browser supports it. But again, support for this isn't universal.

You can't do this in php but you could use the javascript function onbeforeunload, here an example
<script type="text/javascript">
window.onbeforeunload = confirmExit;
function confirmExit()
{
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
</script>

You can't do that using PHP since it's a server-side language.
You will need to use JavaScript.

Since server-side php only runs the server script and then sends the result to the browser you can't do this with php alone. You could send an ajax request to your php script with the onunload event using javascript, and then run the php script in response to that request.

To cover the cases where the user leaves a particular page to navigate to another one inside the same website, you can try to achieve this using page IDs, store the ID of the "page_to_be_left" in a session var, and check if the current page ID matches the one stored in the session var.
Your function could then be triggered if there is no match.

You need to use the javascript function
onbeforeunload

Related

With the Javascript event onbeforeunload, is it possible to do anything other than an alert dialog?

In all of the sample code I have seen, it appears that the only function of onbeforeunload is to serve up an alert dialog box prior to the person leaving the page. Is that the only thing that can be triggered by the event or is it possible to do something else, like an unobtrusive function that sends off partial form data?
I am trying to capture abandoned shopping carts in Yahoo! Small Business and unfortunately I do not have access to any server side scripting, so I'm forced to work client-side only.
I was also thinking of doing an ajax posting of data after the email field was changed, and then comparing the list of all forms partially submitted against completed carts to determine which were incomplete.
You can save the partial form data in localStorage. Then, when another page is loaded, you could check for the presence of that data and AJAX it to the server, deleting it from localStorage on success. Or you might be able to just use that data in JavaScript, without involving the server, but that depends on your setup.
<body onbeforeunload="return ('You will lose all your data')" onunload="alert('You have gone away!')">
</body>
Onbeforeunload uses for alert box. Onunload for anything else.
You can technically fire off an ajax event, but there is no guarantee that it will complete before the page is actually reloaded.

Can I Send an Email using ONLY Javascript Without Having to Click The Send Button on the Email Client?

I created a form in HTML and when the submit button is clicked the onclick event calls the following function:
function ProcessSubmition(){
var stringEmailBody=BuildEmailBody();
var stringTo=document.getElementById("SubmittersEmail").value;
var stringSubject = "My Subject Text";
window.location.href = "mailto:"+stringTo+"?subject="+stringSubject+"&body="+stringEmailBody;
}
There are two requirements to my project:
No PHP is allowed on our server.
The person filling out the form must not be able to edit the data which contains a calculate price.
The Problem:
When the function launches, the mail client window appears and displays the message constructed by the function and the user must click the "Send" button in the mail client window.
Unfortunately before the user clicks send, they can simply change the calculated price to a lower dollar amount which obviously is unacceptable.
Is there any way to hide the mail client window and auto-sent? Alternately is there any other method I could use to solve the problem?
Thank you for any help you can give me.
Short answer: No
The JavaScript code that runs in the context of a browser is client-side code that can be manipulated by the end-users. For that reason, you should never rely on client-side code to perform any sensitive operations.
Basically, you will need some server-side support to do what you are tyring to achieve or it will never be secure. Now, if it's dangerous for you that the users can tamper with your code, it would also be dangerous for them if your code could perform tasks such as sending e-mails on their behalf without any form of approval.
Even if you could talk directly to the mail client like you asked and make the email being sent automatically, there's nothing that would prevent users from editing the JavaScript source that generates the message and change the message content.
Alternative? If you will never be able to use any server-side technology, Maybe you could simply send the form details by e-mail and do the pricing calculations in another process afterwards.

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.

Javascript function execution on link click?

I have a link, that when a user clicks on it, it loads a different page as normal but also executes a JS function that autofills a specific text-box on that different page. Is it better practice to use Jquery or Javascript to do this? How can I do this using either one of them?
You can't do this from the source page.
It's a security feature. Imagine if you wrote a JS function that went to an online banking page and auto-filled a bank transfer using the user's current cookie. That's why you can't.
If you control the other page then the sequence you can use is:
Save data to the server;
Go to the new page with a JS redirect;
The new page is loaded from the server;
While loading th epage the data that was saved from the server is retrieved and used to populate the text box.
So it can be done from the server but only if you save it there. The only way of doing that is using Ajax.
An alternative approach is:
Instead of a JS redirect, submit the page back to the server;
The server saves whatever data it needs to;
The server sends back an HTTP redirect to the new page;
The new page uses the saved data to construct the new page with the populated text box.
At the end of the script add return false;. This will make the page run the script without redirecting the page.
Edit: (after saw your edition).
Is it better practice to use Jquery or Javascript to do this? How can I do this using either one of them?
jQuery is a javascript library, this it doesn't matter if you use plain javascript or use jquery as long as you happy with the result.
And about what you say that you successfully manipulated a page fro the redirecter page... I don't see how it possible.

Categories

Resources