3

I have 3 buttons on my page and depending on which one the user is clickingi want to run through ajax call a delete query in my database. When the user clicks on a button the javascript function seems to work but it doesn't run the query in php script.

The html page:

<?php session_start(); ?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-7"> 
<script>
    function myFunction(name)
    {
        var r=confirm("Are you sure? This action cannot be undone!");
        if (r==true)
        {
            alert(name); // check if is getting in if statement and confirm the parameter's value
            var xmlhttp;
            if (str.length==0)
            { 
                document.getElementById("clearMessage").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("clearMessage").innerHTML= responseText;
                }
            }
            xmlhttp.open("GET","clearDatabase.php?q="+name,true);
            xmlhttp.send();
        }
        else
            alert('pff');
    }
</script>
</head>
<body>
<div id="wrapper">
<div id="header"></div>
<div id="main">
    <?php if (session_is_registered("username")){ ?>
    <!--<a href="#">Εκκαθάριση παλαιών μηνυμάτων</a><br />
    <a href="#">Εκκαθάριση παλαιών συνεδρίων</a><br />
    <a href="#">Εκκαθάριση push notifications</a><br />-->
    <input type="button" value="Εκκαθάριση παλαιών μηνυμάτων" onclick="myFunction('messages')" />
    <input type="button" value="Εκκαθάριση παλαιών συνεδρίων" onclick="myFunction('conferences')" />
    <input type="button" value="Εκκαθάριση push notifications" onclick="myFunction('notifications')" />
    <div id="clearMessage"></div>
    <?php } else echo "Login first."; ?>
</div>
<div id="footer"></div>
</div>
</body>
</html>

and the php script:

<?php
if (isset($_GET["q"]))
    $q=$_GET["q"];

$host = "localhost";
$database = "dbname";
$user = "dbuser";
$pass = "dbpass";

$con = mysql_connect($host,$user,$pass) or die(mysql_error()); 
mysql_select_db($database,$con) or die(mysql_error()); 

if ($q=="messages")
    $query = "DELETE FROM push_message WHERE time_sent IS NOT NULL";
else if ($q=="conferences")
    $query = "DELETE FROM push_message WHERE time_sent IS NOT NULL";
else if ($q=="notifications") {
    $query = "DELETE FROM push_friend WHERE time_sent IS NOT NULL";
}

$res = mysql_query($query,$con) or die(mysql_error());

if ($res)
    echo "success";
else
    echo "failed";

mysql_close($con);
?>
Kostis
  • 953
  • 9
  • 21
  • If you manually request e.g. `clearDatabase.php?q=messages` does it work? – George Brighton Nov 06 '13 at 15:55
  • Where does it fail? Is the GET request made to the server-side script? Does it contain the values you expect it to contain? How does the server-side script respond? Is there a MySQL error? A PHP error? You have to do some debugging here and find out specifically where it fails. – David Nov 06 '13 at 15:55
  • and the php is on `clearDatabase.php`... right? are there any errors? or is it just not deleting? does `clearDatabase.php` work on its own? have you isolated the problem to just the ajax call? **how do you know this is failing?** – gloomy.penguin Nov 06 '13 at 15:55
  • 1
    **Warning** This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0 - [`session_is_registered()`](http://php.net/manual/en/function.session-is-registered.php) – Funk Forty Niner Nov 06 '13 at 15:58
  • 1
    @gloomy.penguin yes it's on clearDatabase.php. It works well on it's own. – Kostis Nov 06 '13 at 16:02
  • 3
    So anybody who runs `http://yoururl.com/clearDatabase.php?q=messages` can clear out the database..... wow. – stUrb Nov 06 '13 at 16:05
  • yes you are right. I suppose i have to change it with POST method :D – Kostis Nov 06 '13 at 16:08
  • 1
    @Kostis: That will not improve security in the least. – Duroth Nov 06 '13 at 16:12
  • 2
    I strongly suggest you [**read this**](http://stackoverflow.com/q/60174/1415724) and [**this also**](https://www.owasp.org/index.php/Top_10_2013-Top_10) @Kostis – Funk Forty Niner Nov 06 '13 at 16:13
  • how do you know it's failing? are there errors or is it just not running? and what isn't running? the ajax? does it even get to the php page? – gloomy.penguin Nov 06 '13 at 16:32
  • in the line `if (str.length==0)`... I don't see `str` set anywhere – gloomy.penguin Nov 06 '13 at 16:36
  • The function gets called and it gets on if statement as i see the alert box. The php script runs without errors on it's own so i guess is the ajax thing. – Kostis Nov 06 '13 at 16:38
  • @gloomy.penguin thank you soooooo much!!! that was it!! A mistake in copy paste! :) It's time for a big break!! Add it as answer so i can accept it. – Kostis Nov 06 '13 at 16:41

4 Answers4

0

Try;

xmlhttp.open("POST","clearDatabase.php?q="+name,true);

instead of;

xmlhttp.open("GET","clearDatabase.php?q="+name,true);
  • 1
    It's not about the type of request, also in the php it receives the request in GET – SamYan Nov 06 '13 at 15:59
  • 2
    @SamuelPedrosa [It **should be** about it now](http://stackoverflow.com/questions/19816590/php-ajax-not-working#comment29463787_19816590) and Orbay should get an upvote now, for an indirect suggestion. – Funk Forty Niner Nov 06 '13 at 16:09
  • Yes I know. But I "**JUST**" said "**TRY**" So; can you say me what's the diffrenet POST and GET? One of them made ​​redundant! – Orbay Yeşil Nov 06 '13 at 16:10
  • @Orbay Yeşil If you know PHP, then you'd know that your solution would give the same result, since it is clear that the problem is not in the type of request made. You just want to get points. – SamYan Nov 06 '13 at 16:12
  • @SamuelPedrosa I am writing them with "Answer". Because I can't write "comment" under the "question". OK? ... I want to help. If I just want to gaint points, I would not risk. – Orbay Yeşil Nov 06 '13 at 16:17
0

first open the xmlhttp request.

try this:

xmlhttp.open("GET","clearDatabase.php?q="+name,true);
xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        document.getElementById("clearMessage").innerHTML= responseText;
    }
}
xmlhttp.send(null);
mehdi
  • 1,755
  • 2
  • 15
  • 21
0

why dont you use jquery -> ajax() ?

And your code will look like this:

function myFunction(name)
    {
        var r=confirm("Are you sure? This action cannot be undone!");
        if (r==true)
        {
            alert(name); // check if is getting in if statement and confirm the parameter's value

             $.ajax({
               type: "GET",
               url: "clearDatabase.php?q="+name,true,
               success: function (res){
                    $("#clearMessage").html(res );
              }
             });

        }
        else{
            alert('pff');
           }
    }
0

You have a few issues.... and this got the text from clearDatabase.php... I just had it output some generic text

<?php session_start(); ?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-7"> 
<script>
    function myFunction(name)
    {
        var r=confirm("Are you sure? This action cannot be undone!");
        if (r==true)
        {
            // Issue #1: str is not defined anywhere 
            var str = "sfs"; 

            alert("name " + name); // check if is getting in if statement and confirm the parameter's value
            var xmlhttp;
            if (str.length==0)
            { 
                document.getElementById("clearMessage").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)
                {
                    // Issue #2: responseText was not defined... it needs to belong to something
                    document.getElementById("clearMessage").innerHTML= xmlhttp.responseText;
                }
            } 
            xmlhttp.open("GET","clearDatabase.php?q="+name,true);
            xmlhttp.send();
        }
        else
            alert('pff');
    }
</script>

note: anyone who runs "clearDatabase.php?q="+name can delete whatever from your database. Also, make those changes but it still may not work if the code on "clearDatabase.php?q="+name doesn't work.

Also: it would have been a lot easier for us to troubleshoot this for you if you had provided the console errors.

How I solved this: I just copied and pasted this in a document myself and opened up the Chrome version of Firebug (control+shift+j) and there was red text to tell me str wasn't defined. So I defined it as var str="". Then I realized it was hitting if (str.length==0) so I give it a value. Then, I got a new error that the responseText wasn't defined. I googled how to use the response form a javascript ajax call (I only know jquery) and looked at the examples. I saw it needed to be from the request and added xmlhttp.responseText;. Then it worked.

gloomy.penguin
  • 5,833
  • 6
  • 33
  • 59
  • Yeap...the responseText it was a misstyping error. Thank you for all the useful advices (security, debugging). I'm new to this and as it seems i have much to learn! – Kostis Nov 06 '13 at 16:51
  • 1
    Debugging is a skill in itself and universal... It will help you out no matter what language, environment, platform, client side, sever side or database. – gloomy.penguin Nov 06 '13 at 16:55
  • To hep with security issues, look into session variables. They're not entirely safe but at least you can check the session on both ends of that code. Or hash it or do something with a token. I don't really know. – gloomy.penguin Nov 06 '13 at 16:58
  • i use session variables on other pages but i wasn't sure if it works on ajax calling (now that i think of it i don't find a reason not to work) and i haven't tried it yet. Anyway my main task was to develop an iphone app and now i have to make an admin website to provide some extra support. – Kostis Nov 06 '13 at 17:05