I have been searching for almost an hour without finding proper example to fix my problem: I would like to call a PHP function (it's a simple unlink with the path given from a javascript function that's executed on page load). I am not good at all with AJAX and I would like to understand how to call directly the PHP function, contained in the index.php file, from the javascript code.
Here's what I have in my javascript code snippet:
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","/dev/templates/absolu/index.php?s=" + Math.random(),true);
//@unlink(listeImages[i].toString());
You send the function name (in case you will have more functions in the future) and params as get params
var fileToDelete;
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","/dev/templates/absolu/index.php?s=" + Math.random()+"&action=delete&file="+fileToDelete,true);
On your PHP script, you should handle it:
<?php
if (isset($_GET['action'])){
switch($_GET['action']){
case 'delete':
@unlink(listeImages[$_GET['action']].toString());
break;
//Other functions you may call
}
exit;
}
//The rest of your index.php code
?>
Using jquery (http://jquery.com/) you could make the call as:
$(document).ready(function() {
$.get("/dev/templates/absolu/index.php?", {
'action': 'delete',
'other': 'get-parameters',
'r': Math.random()
});
});
Server side example:
<?php
switch( $_GET['action'] ) {
case 'delete':
// call unlink here
break;
case 'dosomething':
// else
break;
default:
// Invalid request
break;
}
Please note that deleting files should be handled responsibly (enforce security checks) to make sure no wrong file gets accidentally or on purpose deleted.
You can't call directly a php function from an ajax call, it will only call the php script like if you were opening the page index.php from a browser.
You have to add tests in your php script to know which function has to be called, eg. :
If you call in ajax the page /dev/templates/absolu/index.php?mode=delete_image&image=filename.png
<?php
if($_GET['mode'] == "delete_image") {
unlink($_GET['image']);
}
?>
Please take care that anybody could call this page so you have to check what will be deleted and to verify what you receive in GET parameters. Here i could call /dev/templates/absolu/index.php?mode=delete_image&image=index.php
to delete the php script page.