View Full Version : Can javscript run a php file?

09-07-2010, 01:19 AM
On the home page i have this code

function goodbye(e) {
if(!e) e = window.event;
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = 'Are you sure you want to logout?'; //This is displayed on the dialog

//e.stopPropagation works in Firefox.
if (e.stopPropagation) {

If it's possible i'd like to have the function run a php file..POSSIBLE?

09-07-2010, 06:16 AM
That depends upon what you mean by 'run'. But, generally yes.

I often use AJAX to run PHP files.

There are at least two issues though for something like this:

What if the user doesn't have javascript?

Your goodbye function might not fire in some browsers.

Getting back to your question though, What do you want to happen when logout.php is run?

I mean, does it need to be passed any information, or is everything it needs already available in the SESSION and/or elsewhere?

Just as an example, I recently was working on displaying PDF on an HTML page. It became desirable to know how many pages there were in any given PDF file on demand. PHP can find this information out fairly easily. But I don't want to load a separate page each time this information is wanted. So I used jQuery and AJAX to get it:

$.get('pages.php?pdf=' + page + '.pdf', function(data){

This passed the name of the PDF to a PHP page which calculates how many pages are in the PDF. By using AJAX, this is done in the background. Once the server fetches the page, the information is returned to my sizeIt() function. All this without having to leave the current page.

For what you are talking about you might want the logout page to be loaded for the user. In which case you could just do something like (using only ordinary javascript):

location.href = 'logout.php';

In any case, your function doesn't appear to actually do anything. How are you using it and what does it do? If it's used as onbeforeunload, there is no way I know of to determine the user's choice, and therefore no way to decide whether or not to launch the logout page.

09-11-2010, 02:47 PM
you can have a ajax call, a php file into a div. Then inside the php file you can have code which would "run"

09-11-2010, 03:45 PM
you can have a ajax call, a php file into a div. Then inside the php file you can have code which would "run"

Yes, but if all you want to do is run the PHP code, you don't have to put it into a div.

But the real trouble here is that the onbeforeunload isn't a normal event. Because of this we cannot get a boolean value that tells us whether or not the user really wants to log out.