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
?>
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.
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.
Related
I'll over simplify the problem in order to make it easier. I'm using the following Ajax script to call another .php file and have it return the results to the original page. I'm using Apache offline and the page is unfortunately returning blank.
<html>
<head>
<script>
function showInfo(str) {
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.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status== 200) {
document.getElementById("result").innerHTML= xmlhttp.responseText;
}
}
xmlhttp.open("GET","practice.php?q="+str,true);
xmlhttp.send();
}
window.onload = function() { showInfo('bleh'); };
</script>
</head>
<body>
<div id="result"></div>
</body>
//Then the code below is another file called practice.php, which corresponds the ajax above
<?
$test = $_GET['q'];
echo $test;
?>
I am pretty sure $_GET is a case-sensitive variable name on most OSes, so $_Get would be empty.
I would comment if I could -
What happens when you try to hit the page directly (ie put practice.php?q=test) in the browser?
Also I can't find any documentation (it's hard to google it), but it wouldn't hurt to make the opening tag <?php instead of just <?
Right up front...I am very new to using Ajax.
I'm working on a web site where I want the results of one Select object to determine the options in the second Select object(from a database query). I'm using PHP and it appears that the only way to do this is to use Ajax. I've written a short html page to test my Ajax knowledge and it seems to work just find on Firefox but not on Chrome or IE. I've done a lot of research and found all sorts of folks with similar problems but no real solution.
I'm making the XMLHTTPRequest call to a local file in the same folder even so I should not be experiencing any cross-domain problems. Any help would be greatly appreciated.
Here's my Javascript function that gets called when the Select box is changed:
...
function getData(str)
{
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","ajax_info.php?color=",true);
xmlhttp.setRequestHeader("Content-Type", "text/xml");
xmlhttp.send();
alert(xmlhttp.responseText);
}
********ajax_info.php
+++++++++++++++++++++
//this is the php file that runs in response to the xmlhttprequest. It just generates a string of number at this time.
<?php
$str = "";
$i = 0;
for($i; $i<1000; $i++)
{
$str = $str.$i."-";
}
echo $str;
?>
You need to attach an event handler to your xmlhttp object to catch the onreadystatechange event. Note that when you alert your value, the asynchronous ajax call has just fired and has not finished yet (you are not checking for that anyway):
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET","ajax_info.php?color=",true);
xmlhttp.setRequestHeader("Content-Type", "text/xml");
xmlhttp.send();
Well in that case you should try jQuery. It will be lot easier for you to make ajax request.
Here is an example for your problem
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
// FOR GET REQUEST
$.get("ajax_info.php",{color:'value'},function(data) {
alert(data); // RETRIEVE THE RESULT
});
</script>
I have an XML request in my javascript file that is not transferring my variable correctly to PHP and I cannot figure out why. Could I possibly be missing a reference library of some sort?
Here is the function in question. I do know that the str variable has what I want inside. I am leaving old trial code in comments just in case you want to see what I have tried.
function PHP_Con(str)
{
var xmlhttp;
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
if(!xmlhttp)
{
alert("Fehler");
}
else
{
/*$.ajax({
type:"POST",
url:"dbConnection.php",
data:{"test" : "str"},
success:function()
{
alert("success");
}
});*/
alert(str);
xmlhttp.open("GET","dbConnection.php?test="+str,true);
// Requestheader senden
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// Request senden
xmlhttp.send();
/*var json_string= JSON.stringify(str); // convert it into a json string.
$.post('dbConnection.php' , {test : json_string },function(){
alert("success");
}); */
}
}
And here is my corresponding PHP code:
$test = intval($_POST['test']);
echo $test;
Also, I know about isset but I am trying to get the variable to show up. I'd rather get an error when it is not there, if that makes since...
Thank you very much. :) If there are easier ways to do this, I would be interested in that as well.
But as of now I feel like I do need to have a Form that calls a JS function, then my JS has variables retrieved from user input, and then those variables go to PHP so that they can be checked against my database... it all seems like the right order to me, but I admit to not having a very clear view of how JS variables show up in PHP and also of how PHP can respond in a way that is reflected through HTML code... for example I would like to "echo" back to a span in a p with the results of the comparison (user input against the database contents) and I have no idea of how that is done...
You are sending a GET request so you have to use $_GET instead of $_POST
$test = intval($_GET['test']);
echo $test;
a POST request would look like
xmlhttp.open("POST","dbConnection.php",true);
// Requestheader senden
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// Request senden
xmlhttp.send("test="+encodeURIComponent(str));
I can't seem to figure out how to get this function working. The crucial thing to see is that the tStat = xmlhttp2.responseText seems to be delayed. I have it test this out with the .innerHTML +=" withintest "+Stat. It prints out "withintest withintest withintest 0". So it does a few iterations until it has the value?? 0 is the value of Stat that I want, and the checktStatus.php gets it from a database.
But since this function returns a value, and I have it being called from another function into a variable for that value, it can't be delayed DB read before it returns. But I can't figure out how to accomplish this! Help?
EDIT: took out some commented code, but the problem still remains. It returns an "undefined" value before it can get a real one.
function gettStatus()
{
var tStat;
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp2=new XMLHttpRequest();
}
else
{ // code for IE6, IE5
xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp2.onreadystatechange=function()
{
if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
{
tStat=xmlhttp2.responseText;
document.getElementById("txtHint").innerHTML+=" withintest "+tStat;
return tStat;
}
}
xmlhttp2.open("GET","checktStatus.php?tID=1",true);
xmlhttp2.send();
}
How onreadystatechange works
onreadystatechange event handler - as the name of the event suggests - is called when the readyState is changed. So you must check for the state and status (as you did in the part you commented).
See more details here: Mozilla Developer Network: AJAX - Getting Started
List of readyState values
From the page referenced above (link to the section):
The full list of the readyState values is as follows:
0 (uninitialized)
1 (loading)
2 (loaded)
3 (interactive)
4 (complete)
Asynchronous nature of AJAX
You should also be aware of the fact, that usually AJAX works asynchronously, so it would be easier for you to just pass callbacks that will be executed once the response is received, like that:
function gettStatus(callback){
// do something here...
callback(result); // ...and execute callback passing the result
}
Solution
Thus you should edit your code to look similarly to this (with readyState / status conditions uncommented):
function gettStatus(callback)
{
var tStat;
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp2=new XMLHttpRequest();
}
else
{ // code for IE6, IE5
xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp2.onreadystatechange=function()
{
if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
{
tStat=xmlhttp2.responseText;
document.getElementById("txtHint").innerHTML+=" withintest "+tStat;
callback(tStat);
}
}
xmlhttp2.open("GET","checktStatus.php?tID=1",true);
xmlhttp2.send();
}
and then just use it like that:
gettStatus(function(tStat){
// tStat here is accessible, use it for further actions
});
instead of using it in the following manner:
var tStat = gettStatus();
// tStat would be available here, if gettStatus() would not involve
// asynchronous requests
The lines you have commented out serves the purpose of filtering readystates.
/*if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
{*/
tStat=xmlhttp2.responseText;
document.getElementById("txtHint").innerHTML+=" withintest "+tStat;
return tStat;
//}
Should be
if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
{
tStat=xmlhttp2.responseText;
document.getElementById("txtHint").innerHTML+=" withintest "+tStat;
return tStat;
}
I am refactoring some code. I have a PHP page that contains a MySQL query and stores the result in a PHP variable $my_result. This result is then echoed to a Flash SWF during embedding with SWFObject.
I now want to call this PHP page that makes the query from a javascript function like so - one change I have made to the PHP is that instead of storing the result in a variable $my_result I am echoing the result.
Javascript function to call the PHP page and make the database query
function getNewUploads() {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
alert(xmlhttp.responseText); // shows the correct output in an alert box
return xmlhttp.responseText;
}
}
xmlhttp.open("GET","dBaseConnect_uploadStep2.php",true);
xmlhttp.send();
}
Then I have the embedding of the Flash which I only want to happen when a certain tab is clicked on a page and is handled by jabvascript -
function show_tab(tab_id) {
$(tab_id).show();
if(tab_id == "#tab_2") {
var data_string = getNewUploads(); // CALLING THE FUNCTION TO CALL THE PHP QUERY
alert(data_string); // shows undefined in the alert box
var so = new SWFObject(".....");
so.addVariable("theDataString", data_string);
so.write("flashcontent2");
}
}
So it seems that the getNewUploads() function does not return the result from the PHP page.
Can anyone shed some light on my mistake please. Thanks
The call is asynchronous. After you call send, the call begins in the background. In the meantime, getNewUploads returns. Later, the function you've assigned is called with the answer. When you do return xmlhttp.responseText, you're returning from this anonymous function (assigned to onreadystatechange), not from getNewUploads (which is already done).
You can use a callback instead. Something like:
function getNewUploads(callback) {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
callback(xmlhttp.responseText);
}
}
xmlhttp.open("GET","dBaseConnect_uploadStep2.php",true);
xmlhttp.send();
}
function show_tab(tab_id) {
$(tab_id).show();
if(tab_id == "#tab_2") {
getNewUploads(function(data_string) {
alert(data_string);
var so = new SWFObject(".....");
so.addVariable("theDataString", data_string);
so.write("flashcontent2");
}); // CALLING THE FUNCTION TO CALL THE PHP QUERY
}
}
We define getNewUploads to take a single argument, callback. Then, in the success function, we call the callback with a single argument, the response text. In show_tab, we pass an anonymous function that takes a single parameter (the response text) to getNewUploads, as the callback parameter.
The true in xmlhttp.open("GET","dBaseConnect_uploadStep2.php", true); makes it asynchronous and hence the error. Change it to:
function getNewUploads() {
//initialize xmlhttp
xmlhttp.open("GET", "dBaseConnect_uploadStep2.php", false);
xmlhttp.send();
if(xmlhttp.status == 200)
return xmlhttp.responseText;
else
return "Oops :(";
}