When a user views a certain profile page I need to send the end user an email but would like to do this asynchronously if at all possible. Can this be done with PHP? I really don't want to wait for the PHP function to complete before rendering the rest of the page. It should be seamless to the user.
Or is this a better solution from the client side:
$.post("msg.php?user=xxx", function(data) {
....
}, "json");
Is there a preferred method?
If you want interactivity, go for the ajax()
method; if you just want to hit a listener script (and thereby initialize a set piece of PHP functionality), use post()
which is a short-hand version of the same method:
$(function() {
// If you just want to activate a listener script (with no interaction)
$.post('/path/to/script.php');
// If you want to receive data back from your script for use in the DOM
$.ajax({
type: "POST",
url: "/path/to/script.php",
data: { name: "John", location: "Boston" }
}).done(function( response ) {
alert( response );
});
});
The best way to have your page perform asynchronous actions is to use AJAX, as you've suggested.
You can execute a script with proc_open or shell_exec if you're stuck with a server side solution. There may be some restrictions on this depending on your environment, but this is generally a quick and dirty way to multi-thread PHP and thus allow for things to happen asynchronously.
That is, somewhere in the script, if a flag is set (such as a notify flag) it will dispatch a process like '../private/notify.php' ... see how to pass arguments to a command line call of php. There is also the option of calling sendmail directly.
Make sure you test it out a bit before trying it; you need to make sure that: