An equivalent of javascript unload for PHP - php

For javascript there is an unload function, when a page closes, do something. Is there the same for php?
Thanks
Jean

PHP is server side, so by the time your user sees the page, the PHP thread is already done. You could of course put an ajax call in your javascript unload though that calls a PHP script.

PHP is a server-side technology. It has no idea that the page is closing unless you use JavaScript to send a message to a PHP script. Then it's just as any other php page.

If you want to execute something at the end of your request, you can use register_shutdown_function:
function my_func() {
// perform some cleanup
}
// my_func will be called after the rest of your script has executed
register_shutdown_function('my_func');

Since PHP is a server side language it's not possible to do something like this without using some sort of browser based scripting language.

short answer NO!
the reason for this is that PHP just creates a page, ones it has built up the page it sends the html to Apache to serve, when this is done, the PHP script is already finished.
A possible hack is using javascript.
so heres and example, Requires jQuery¬
$.fn.unloadping = function(url,params,callback)
{
this.onbeforeunload = function()
{
$.ajax({
type : 'GET',
data : params,
success : function(response)
{
callback(this) //Send window context back
}
});
return false;
}
return $(this); //keep the chain
}
and can use like so
$(window).unloadping('/ping/closewindow.php',{page:window.location.href},function(context){
this.close(); //Needs to be checked
});
can i ask why you would like to do this? what's your motives etc. ?

PHP is not event-oriented, the best way to know if a page finished is in the last line.
If you need to know when a class is "unloaded" you can use the function __destroy

Related

php run before ajax is completed

I know PHP runs first but is there a way to get PHP to wait on an ajax request and then run its script? I have a php script here that I want to run but I NEED a variable from my JS file in order for it to run successfully. So was wondering if it's possible?
What I have is a normal request in my JS:
var myvar = data;
$.get('phpscript.php', {myvar: myvar} );
And in PHP:
$myphp = $_GET['myvar'];
But if i echo $myphp it returns "undefined", if I alert it however It displays the value; which means the php script is running before it even gets the request from ajax. Any way I could make the PHP wait?
Thanks.
Put the PHP that requires a variable in its own script and call it from the ajax call, once the ajax call gets a response update the DOM as needed.
PHP runs on server, then javascript runs on client to make the ajax call, then PHP runs on server returning data, then the javascript gets the data and does something with it.
$.get('phpscript.php', {myvar: myvar}, function(data) {
$('.result').html(data);
});
Inside the php file have something like:
$myphp = $_GET['myvar'];
echo $myphp;
The short answer is, no, you can't make PHP wait. PHP only runs on the server-side, by the time the AJAX request is sent, by definition, the page is already been sent to the client.
You'll probably have to do some refactoring. If the variable absolutely needs to be used for a PHP function, then you may need to move that logic into 'phpscript.php' or (less optimally) you may need to issue another AJAX request when you get the response from the first.
But my guess is that more commonly, you'll probably just have to figure out how to do what you want with javascript. If all you want is something equivalent to a PHP echo, you'll want to use Javascript (or JQuery) DOM manipulation for that.
EDIT: I forgot to mention, the other option is simply to do all the PHP stuff on the server-side before you send the page at all, instead of AJAX you'd want to do something in PHP like including your other php script and calling methods from it. But, everything you do on the server-side, the user is sitting there looking at a blank screen waiting for the page to load. So this isn't an option for anything that's not very quick.

Execute php from javascript

I'm having some trouble getting some php code working in my app.
The setup is rather easy: 1 button, 1 function and 1 php file.
script.js
$(document).ready(function ()
{
$("#btnTestConnectie").click(testConnectie);
});
function testConnectie()
{
$.get("script/SQL/testConnection.php");
}
testConnection.php
<?php
echo "It works!";
php?>
According to this post, it should work (How do I run PHP code when a user clicks on a link?)
Some sources claim that it is impossible to execute php via javascript, so I don't know what to believe.
If I'm wrong, can somebody point me to a method that does work (to connect from a javascript/jQuery script to a mySQL database)?
Thanks!
$.get('script/SQL/testConnection.php', function(data) {
alert(data)
});
You need to process Ajax result
You need to do something with the response that your php script is echoing out.
$.get("script/SQL/testConnection.php", function(data){
alert(data);
});
If you are using chrome of firefox you can bring up the console, enable xhr request logging and view the raw headers and responses.
Javascript is run by the browser (client) and php is run on the remote server so you cannot just run php code from js. However, you can call server to run it for you and give the result back without reloading of the page. Such approach is called AJAX - read about it for a while.
I see you are using jQuery - it has pretty nice API for such calls. It is documented: here
In your case the js should be rather like:
$(document).ready(function ()
{
$("#btnTestConnectie").click($.ajax({
url: '/testConnection.php',
success: function(data) {
//do something
}
}));
});
[EDIT]
Let's say you have simple script on the server that serves data from database based on id given in GET (like www.example.com/userInfo.php?id=1). In the easiest approach server will run userInfo.php script and pass superglobal array $_GET with key id ($_GET['id']=1 to be exact). In a normal call you would prepare some query, render some html and echo it so that the browser could display a new page.
In AJAX call it's pretty much the same: server gets some call, runs a script and return it's result. All the difference is that the browser does not reload page but pass this response to the javascript function and let you do whatever you want with it. Usually you'll probably send only a data encoded (I prefer JSON) and render some proper html on the client side.
You may have a look on the load() of jQuery http://api.jquery.com/load/
You should place all of your functions in the document ready handler:
$(document).ready(function(){
function testConnectie() {
$.get("script/SQL/testConnection.php");
}
$("#btnTestConnectie").click(function(e) {
e.preventDefault();
testConnectie();
});
});
You will have to have your browser's console open to see the result as a response from the server. Please make sure that you change the closing PHP bracket to ?> in testConnection.php.
One other note, if you're testing AJAX functions you must test them on a webserver. Otherwise you may not get any result or the results may not be what you expect.

How to return JavaScript from PHP file through AJAX?

How to do this?
We have button with onclick event, that sends a query using AJAX to PHP file.
PHP file has this JavaScript: echo '<script>alert("hello");</script>';
When pushing onclick event button, JavaScript doesn't work. I don't see a "hello" message.
Does anybody knows how to execute JavaScript from PHP? I need exactly this one. I know that all JavaScript should be executed on the AJAX level. But the situation demands to execute a JavaScript, that PHP returns as response.
Best regards
You cannot execute Javascript from PHP since PHP executes on the server side while JS on the client side. You need to eval the returned Javascript code on the client side.
You can do this in your AJAX callback function:
$('#yourButton').onclick(function(){
//make your ajax request
$.ajax({
url : "url",
success : function(resp){
//resp is the javascript code sent back from PHP
//eval it
eval(resp);
}
})
});
Eval will work, but be careful.
If user generated content can get into your eval statement, someone could use that to create a malicious script for your site.
Just a heads up.
Consider a javascript like:
"alert(\"hello\");"
Return like this:
var js = ajax.r;
And just do:
eval(js);
But seems to me that you have a very serious architecture problem.

Is it okay to use PHP inside a jQuery script?

For example:
$(document).ready(function(){
$('.selector').click(function(){
<?php
// php code goes here
?>
});
});
Will this cause issues or slow down the page? Is this bad practice? Is there anything important that I should know related to this?
Thanks!
If you are trying to bound some PHP code with the click event then this is impossible in the way you are trying and PHP code will be executed as soon as page load without waiting for a click event.
If you are trying to generate final javascript or jquery code using PHP then this is okay.
It won't slow down the page; the PHP runs on the server and emits text which is sent to the browser, as on any PHP page. Is it bad practice? I wouldn't say "bad" necessarily, but not great. It makes for messy code - in the event where I need to do something like this, I usually try to break it up, as in:
<script>
var stuff = <?php print $stuff; ?>;
var blah = "<?php print $blah; ?>";
// Do things in JS with stuff and blah here, no more PHP mixed in
</script>
PHP is executed on the server, and then the javascript will be executed on the client. So what you'd be doing here is using php to generate javascript that will become the function body. If that's what you were trying to do then there's nothing wrong with doing it.
If you thought you were going to invoke some PHP code from javascript, then you're on the wrong track. You'd need to put the PHP code in a separate page and use an ajax request to get the result.
Sure, as long as you keep in mind that PHP code will be executed by the server before the page is sent out. Other than that, have fun.
PHP is a "backend" language and javascript is a "frontend" language. In short, as long as the PHP code is loaded through a web server that understands PHP - the downside is that you have to inline the JS, losing caching ability (there are workarounds to parse php in .js files but you shouldn't really do this). To the user it will just look like javascript and HTML. Here's the server order:
User requests page.
Apache (or equivalent) notices this
is a php file. It then renders all
the php that are between php tags.
Apache sends the page to the user.
User's browser sees the JavaScript
and executes it.
Just be sure the PHP is outputting valid JavaScript.
you have a better choice to use ajax that runs the php script when you are handling a click event
$(document).ready(function(){
$('.selector').click(function(){
$.ajax({url:"phpfile.php",type:"POST",
data:"datastring="+value+"&datastring2="othervalue,
,success:function(data){
//get the result from the php file after it's executed on server
}
});
});
});
No it's not. Just as long as you know that the JS is executed after the PHP page is parsed.

Calling JavaScript with PHP

I want to call a PHP function when pressing on a button, sort of like:
<?php
function output(){
// do something
}
?>
<input type="button" value="Enter" onclick="output()"/>
I tried to make something like:
<input type="button" value="Enter" onclick="test.php?execute=1"/>
where test.php is current page and then by php
<? if(isset(&execute)){ echo "Hello"; } ?>
but it doesn't work.
Since PHP runs on the webserver, and buttons (and JavaScript in this case) appear on the client, you have to make an HTTP request to the server.
The easiest way to do this is to use a form. No JavaScript is required. You can add JavaScript (although it should be layered on top of a working non-JS version). Using JavaScript to make an HTTP request without leaving the page is known as Ajax, and generally achieved with the XMLHttpRequest object. There are various libraries such as YUI and jQuery that can do some of the heavy lifting for you.
I think using an AJAX call would do sort of what you are asking. I don't know PHP very well but you can use the following example, and add another variable with the data you are passing in to the server to indicate which function you want to call on the server. On the server you can add some "IF" statements that will call a certain function based on the name passed in and return the result.
Here is what you could use on in your javascript client using the jQuery library as a helper to do the AJAX call:
<input type="button" value="Enter" onclick="output()"/>
<script type="text/javascript">
function output(){
$.ajax({
type: "POST",
url: "submit_data.php",
data: "username=" + "SomeUser"
+ "&email=" + "someEmail#google.com"
+ "&functionName=" + "theFunction1",
success: function(html){
alert('sucess! Result is:' + html);
}
});
}
</script>
and you can use code such as this to catch the data your javascript is passing in. In this example you would want to call this file name as "submit_data.php" to match the javascript above:
<?php
// Variables
$Username = $_POST['username'];
$Email = $_POST['email'];
$FunctionName = $_POST['functionName'];
//Add code here to choose what function to call and echo the result
// If $FunctionName equals 'theFunction1' then execute theFunction1
// If $FunctionName equals 'theFunction2' then execute theFunction2
echo "You called A Page!";
?>
Here I am doing nothing with the "username" and "email" simply grabbing it and storing them into holding variables. But you can easily add extra functionality here, such as checking for a name of a function that you want to run.
PHP is server side and javascript is client side. So I'm not sure if that is really what you want to be doing??
Perhaps you could explain why you want to specifically call a php function?
I googled PHP function from button and found this question on webdeveloper.com
It doesn't use Javascript.
This is PHP you're talking about, not ASP.NET. In PHP, there is no such thing as a button click event. PHP runs entirely on the server and has absolutely no knowledge of client-side events.
Your first try won't work because the PHP code only runs when the page first loads. It does not run when you call a JavaScript function. Your second example won't work because JavaScript and PHP can't talk directly to eachother like that. Trying to directly call a PHP function from JavaScript just doens't make sense. Remember, PHP only runs on the server. By the time you get to the point where JavaScript can run, the PHP code has long since completed its work.
If you want to do something when a button is clicked, you have to explicitly make a request back to the server. You can do this by just POSTing the form as CTphpnwb suggested. Just be aware that this will reload the page and you will have to manually save and restore the page state, e.g. repopulate input boxes. There is no built-in magic that will do this for you.
Alternatively, you can get all AJAXy and do the POST in JavaScript. However, you will have to write the JavaScript to send the request and process the response, and write the server-side PHP code to handle the request. This gets a little awkward to do in a single page.
From : http://www.dreamincode.net/forums/showtopic72353.htm
You cannot directly invoke a PHP function from Javascript this way :
PHP code is executed on the server
HTML / Javascript are interpreted on the client-side.
One the HTML page has been generated and sent to the client (the browser), there is nothing more PHP can do.
One solution would be to use an Ajax request :
Your onclick event would call a Javascript function
This Javascript function would launch an Ajax request : a request sent to the server
The server would then execute some PHP code
And, then, return the result of that execution to the client
And you'd be able to get that result in your Javascript code, and act depending on what was returned by the server.
There are plenty of solutions to do an Ajax request :
You can re-invent the wheel ; not that complex, I should say -- but see the next point
If already using a Javascript framework, like jQuery, Prototype, ... Those provide classes/methods/functions to do Ajax requests
Googling a bit will get you lots of tutorials/examples, about that ;-)

Categories