how can i execute php instructions when closing the browser? - php

I want to execute instructions in the momant of closing the browser, for example the instruction is a requeste sended to update the database?

PHP has nothing to do with the browser. PHP can't interact with it in any way directly, but you can use JavaScript to communicate with your PHP. Doing something when the browser is closed is not always reliable because the browser could close unexpectedly, but you can attempt to gather the info using an onunload event listener to send an HTTP request to run your PHP script.
window.onunload = function(){
var xmlhttp = (window.XMLHttpRequest)? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
var url = "MyPHPScript.php";
xmlhttp.open("GET",url,false);
xmlhttp.send();
}

Related

Post JSON to PHP and then trigger a file download from PHP?

I'm thinking about a webpage that posts json object to a PHP page, and then the PHP page generates some data and exports the data to a local file. Because in the first step, the data will be too large to pass through URL, I need to use JSON. However, when I passed the JSON object to PHP in an AJAX way, no downloading is triggered. I'm wondering how this downloading can be triggered.
//the code will not trigger a download from PHP
var xmlhttp;
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("POST", "export.php");
xmlhttp.setRequestHeader("Content-type", "application/json", true);
xmlhttp.send(JSON.stringify(obj));
I can receive the echoed data in JavaScript, but creating local files in JavaScript is more complex than in PHP.
Don't use xmlhttprequest, just submit the form with your json to PHP and in PHP specify the correct Content-Type.
I found the solution: create a form and use JavaScript to dynamically create hidden input fields. And use a submit button to post the form to the php file in a newly opened window.

How to run a php file in background [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Best way to manage long-running php script?
I have to built a big email list.Everything works perfectly,but when i submit the form page is loading untill every email is send.So i want this email sending script run in background.and notice the user that script is runnign in background.
I cant use Ajax.
i want something like.. proc_open,exec,shell_exec..
You can have cron job which would run php script which will get queue from db and send email
On main script you just need to add emails to queue
I would use ajax only if you need progress bar. With ajax solution you would need to keep window open until it's ended.
You could build an AJAX call that calls the php script. This way, your site will still be operational while the request is fulfilled. And when it's finished, your AJAX will return and you can show a messagebox to the user.
For more information, check at least this and if you understand what AJAX is and what it does, use it with this
Ajax request would be the best choice for this. You can send a request using javascript and even report progress to user (which might require some additional work)
If you find ajax too difficult - run script in an iframe. This is not the most elegant, but the most simple method.
Submit the form with AJAX and update the progress in a Div
For example - write to some place "A"(db or file) current state of your script runtime: "complete"/"incomplete". After start script in background send to your user waiting page which using AJAX handling changes at "A".
This Ajax script will execute a PHP file on the background. It could also send the response to a HTML element if you want.
<script type="text/javascript" language="javascript">
function execute(filename,var1,var2,var3)
{
var xmlhttp;
if(window.XMLHttpRequest)
{
//Code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
//Code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert("Your browser does not support AJAX!");
}
var url = filename+"?";
var params = "var1="+var1+"&var2="+var2+"&var3="+var3;
xmlhttp.open("POST", url, true);
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
//Below line will fill a DIV with ID 'response'
//with the reply from the server. You can use this to troubleshoot
//document.getElementById('response').innerHTML=xmlhttp.responseText;
xmlhttp.close;
}
}
//Send the proper header information along with the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
}
</script>
You can try to run the script through an ajax function as well if you don't want to set cron script.
PHP has an function that can keep an process running even if the user that requested the page leaves the page : ignore_user_abort if you check the comments there you can see this example :
<?php
ignore_user_abort(1); // run script in background
set_time_limit(0); // run script forever
$interval=60*15; // do every 15 minutes...
do{
// add the script that has to be ran every 15 minutes here
// ...
sleep($interval); // wait 15 minutes
}while(true);
?>
It IS an pure php cron job BUT, the risk with this script is that it continues indefinitely or atleast untill you reset/kill php.
Setting the set_time_limit(0); to set_time_limit(86400); would kill the script after an day.
This should point you in the right direction/.
IMPORTANT
After the problem by the OP, it is advisable to only run this script if you have SSH access to the server so you can KILL/RESTART php apache in case the server keeps hanging.
Also do not run the script on a LIVE server.

PHP and Javascript working together

It may sound odd, but I've been programming games in PHP. The main problem I've found was that the only way to update PHP is to load a page. That makes real-time slow. Javascript can interact with a page without reloading it. Is it possible to load PHP pages on a page using Javascript? So that it would allow PHP to be loaded over and over without reloading.
I've seen it done with Chat rooms but not sure how it works.
We mostly use Ajax, which consists in a client-side Javascript code that calls a server-side page, with out leaving the page.
Here's an example that will get the displayed content of a page, using the GET method (JSFiddle):
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp');
xhr.onreadystatechange = function(){
if(xhr.readyState==4 && ((xhr.status>=200 && xhr.status<300) || xhr.status==304)){//Checks if the content was loaded
console.log(this.responseText);
}
}
xhr.open('GET','myPHPPage.php?foo=foo&bar=bar',true);
xhr.send();
And here using the POST method (JSFiddle):
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp');
var data = 'foo=foo&bar=bar';
xhr.onreadystatechange = function(){
if(xhr.readyState==4 && ((xhr.status>=200 && xhr.status<300) || xhr.status==304)){//Checks if the content was loaded
console.log(this.responseText);
}
}
xhr.open('POST','myPHPPage.php',true);
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.setRequestHeader('Content-length',data.length);
xhr.send(data);
Note that here we use the setRequestHeader method to change the headers of this HTTP request and, in this case, to change the Content-type and the Content-length (this header has a default value of 4096 bytes). Also, the setRequestHeader method must be called after the open method.
These links should help you:
https://developer.mozilla.org/en/Ajax
http://code.google.com/intl/pt-BR/edu/ajax/tutorials/ajax-tutorial.html
Yes it's incredibly common.
Read up on Ajax.
We call that AJAX!!!
Just Read The documentation on internet about ajax

How to insert a PHP dropdown in a HTML / Javascript page

Ok, this is my second post, and PLEASE accept that I am a complete newbie, willing to learn, spending many hours trauling various sites for answers, and I've almost got to where I need to be (at least for this bit).
I have a web page which has a nubmer of javascript functions that work together to generate a Google Map with various lines etc. using the google maps API.
I also have a MySQL Database with some information in.
I have created a PHP script to dynamically generate a dropdown box with information from the database. (and that bit seems to work fine) - http://www.bournvilleconservatives.com/temp/select.php
What I now need to do is get that dropdown box to appear in the HTML / Javascript page that I already have, so that when a user selects something from the list, it calls a javascript function with the value selected.
I'm told I need to use AJAX to pull the box in, and use innerhtml to display it, but I really have no idea how, and could do with an example of something similar to help me on my way.
I would put the PHP in the html page, but that page is actually wrapped up in a Joomla! wrapper, so its all rather complicated.
Thanks in advance.
jQuery solution
If you are willing to use jQuery, it will help you a lot with accessing the DOM, making Ajax calls and stuff. Let me give you a solution in jQuery:
First, put a div into HTML (this will store your select box):
<div id="i_want_my_select_here"></div>
Then put this code in the end of you HTML before </body>.
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#i_want_my_select_here').load('/temp/select.php');
});
</script>
In the first script tag, we include the jQuery library from Google's CDN. In the second, we write our Javascript/jQuery code. The .load() function makes it easy to make an Ajax call and load the response into an HTML element.
You can see this is much easier than all that code in my other answer :).
If you're using prototype, you can use either Ajax.Request or Ajax.Updater, tho you should have a parent div with either to replace/insert into.
Example w/ Request:
new Ajax.Request('select.php', {
method: 'post',
onSuccess: function(r) {
var select = r.responseText;
$('parent_div').update(select);
}
});
Example w/ Updater:
new Ajax.Request('parent_div', 'select.php', { method: 'post' });
First, the Ajax example (taken from tizag.com and modified), Javascript code comes:
var ajaxRequest; // The variable that we will put an XMLHTTPRequest object in
//We try to create an XMLHTTPRequest object,
//it is the object that lets us use Ajax
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
// and do stuff with it (this function will only run,
// when the data arrives back from the server!)
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){ //if request is successful
//HERE COMES THE DOM INSERTION
}
}
//We call the PHP file
ajaxRequest.open("GET", "/temp/select.php", true);
ajaxRequest.send(null);
What basically happened is that through XMLHTTPRequest we called your PHP file. When the response (PHP file's output) comes, ajaxRequest.onreadystatechange will run instantly. So whatever we want to do with the data received, we have to do it in the place I've written //HERE COMES THE DOM INSERTION.
We want to insert the output into the HTML. To take the easiest route, first create a div/span in your HTML at the exact place you want your select to appear (it's very important to define the ID).
<div id="i_want_my_select_here"></div>
Then again, here comes the Javascript that replaces //HERE COMES THE DOM INSERTION.
//use the id to get Javascript access to the DIV
var div=document.getElementById('i_want_my_select_here');
//put the output of PHP into the div
div.innerHTML=ajaxRequest.responseText;

How to activate PHP file in JavaScript function

I am trying to write some information into my database when I activate a javascript function.
I use PHP and MySQL. How can I open the .php file, execute it and return to .js file in order the function to continue its operation?
Thanks in advance.
I think you may be a bit confused. Javascript runs in the browser, on the client's computer. Php/MySQL runs on the server, responds to HTTP requests, and creates the content for the browser to display/run.
In order to get the two to communicate dynamically, you need to look at how to send/receive HTTP requests from javascript on the client to your php script on the server. You'll also need to be able to process responses in javascript. This practice is known as AJAX. The simplest way to do this is in my experience to use JSON and jQuery, http://api.jquery.com/jQuery.getJSON/
First of all, it is not possible to call PHP functions directly from JavaScript, or vice versa. This is because PHP is a server-side script, running on the server, and JavaScript is a client-side script, running on the browser.
But there is a solution, however, using a technique called "AJAX" (Asynchronous JavaScript and XML), which can be used to send a request to a server from JavaScript.
For instance, using a "user" page that the user sees, and a "request" page that is called from the JavaScript code, I could write the following code:
userpage.php:
<!-- JavaScript code -->
<script type="text/javascript">
function sendRequestToServer()
{
// The XMLHttpRequest object is used to make AJAX requests
var ajax = new XMLHttpRequest();
// The onreadystatechange function will be called when the request state changes
ajax.onreadystatechange = function()
{
// If ajax.readyState is 4, then the connection was successful
// If ajax.status (the HTTP return code) is 200, the request was successful
if(ajax.readyState == 4 && ajax.status == 200)
{
// Use ajax.responseText to get the raw response from the server
alert(ajax.responeText);
}
}
// Open the connection with the open() method
// (the third parameter is for "asynchronous" requests, meaning that
// JavaScript won't pause while the request is processing).
ajax.open('get', 'requestpage.php', true);
// Send the request using the send() method
ajax.send();
}
</script>
<!-- HTML code -->
<button onclick="sendRequestToServer();">Send request!</button>
requestpage.php (the output of this page will be returned to your JavaScript code):
<?php
echo "Hello World!";
?>
This example would, when the button is pressed, send a HTTP request to the server requesting requestpage.php, where the server would execute some server-side code and echo the result. The browser would then take the data it received from the server and use it in the script - in this case, alert() it.
Some resources:
AJAX wikipedia page
AJAX tutorials on Mozilla Developer Center and w3schools.com.
You might also want to check out JSON encoding, which is very common method of sending objects and arrays between clients and servers (especially when using AJAX):
JSON tutorial on MDC
json_encode() and json_decoder() PHP functions
(Sorry for such a long answer, hope it helped though)
You will need AJAX, there http://www.ajaxf1.com/tutorial/ajax-php.html a simple tutorial for AJAX using PHP server
look up AJAX... also think about using jQuery it has a simple and easy to use ajax() function.
If you're not already using an AJAX enabled framework (e.g. jQuery), you could just use a really lightweight XHR implementation to make a HTTP request. This request could have any PHP resource (performing the desired DB updates) as destination.
The smallest code I know of is found here: http://dengodekode.dk/artikler/ajax/xmlhttprequest_wrapper.php (Danish, sorry)
<script type="text/JavaScript">(function(){if(window.XMLHttpRequest)return;var o=null,s,
a=["MSXML2.XMLHTTP.6.0", "MSXML2.XMLHTTP.3.0","Msxml2.XMLHTTP","Microsoft.XMLHTTP"];
for(var i=0,j=a.length;i<j;s=a[i],i++){try{if(o=new ActiveXObject(s))break}
catch(e){}}window.XMLHttpRequest=o?function(){return new ActiveXObject(s)}:null;o=null})()</script>
And the request:
var oHttp = new XMLHttpRequest();
oHttp.open("post", "http://www.domain.dk/page.php", true);
oHttp.onreadystatechange = function(){ myCallBack(oHttp) };
oHttp.send("id=123&noget=andet");

Categories