-2

I am currently coding for sorting of names in a table column. When the user clicks the header(link to js func), the table will the names. However, I am having some trouble. I get a notice of an undefined index(which I know many people do and I have searched online for it) which means that the variable is not declared. I can't seem to understand why though.

I did achieve my desired outcome, which is when the end user clicks the delete button(that is available for each row/record) it will delete the record(execture the sql query of delete) in the database. I am currently debugging to find out what's wrong but it'd be great if I'd had some help.

Note: If you notice, I did not use and jQuery or jQuery plugins and I know it will make it easier for me to use but I am a student learning so I want to start or rather use and hone my JavaScript coding so I prefer JavaScript. Besides, I tried learning jQuery once and I found it difficult(ironically). Don't worry about SQL injections as well.

Coding Note: displayTable() is called when a button in my html file(not using any forms) is clicked. Take note of the windows.onload function I have used for it. Everything is done in a new pop up window.

EDIT: I added which line the undefined index was at.

2nd EDIT: Added in the action because I forgot to put it in this question, pointed out by @Barmar.

This is in the PHP file:

<?php

// Define database parameters //
DEFINE ('DB_USER' ,'iaqwgvaqn');
DEFINE ('DB_PASSWORD', 'qawf23');
DEFINE ('DB_HOST', 'lqwfqwt');
DEFINE ('DB_NAME', 'hqwfcaqwq');

// Connect to database
$conn = @mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect to Database:'. mysql_error());
@mysql_select_db (DB_NAME) OR die ('Could not select the Database: '.mysql_error()); 


function selectAll($enableSorting)
{
    $table_info = "dummyTest";

    if($enableSorting == "sortingEnabled")
    {
        $query_string = "select * from $table_info order by name";
    }
    else
    {
        $query_string = "select * from $table_info";
    }
    $result = @mysql_query($query_string) or die (mysql_error());
    $num_row = mysql_num_rows($result);

    if($num_row)
    {
        $count = 0;

        echo "<table id='table2' class='table2' border=1>"; 

        //Table headers
        echo "<tr><th>ID</th>";
        echo "<th><a href=\"javascript:sortTable();\">Name</a></th>";
        echo "<th>Badge Number</th>";
        echo "<th>Category</th>";
        echo "<th>Action</th>";

        while($row = mysql_fetch_array($result))
        {
            $id = $row['id'];
            $name = $row['name'];
            $badge_number = $row['badge_number'];
            $category = $row['category'];
            $privilege = $row['privilege'];
            $count++;

            echo "<tr>";
            echo "<td id=\"row$count\">$id</td>";
            echo "<td>$name</td>"; 
            echo "<td>$badge_number</td>";
            echo "<td>$category</td>";
            echo "<td><input type=\"button\" name=\"delete\" value=\"Delete\" onclick=\"deleteThis($count, $privilege)\"/></td>";
            echo "</tr>";

        }
        echo "</table>";
    }
    else
    {
        echo "No records available. Click 'Add User' to add new user.";
    }
}

function deleteRow($id)
{
    $table_info = "dummyTest";
    $query_string = "delete from $table_info where id='$id'";
    $result = @mysql_query($query_string) or die (mysql_error()); 
}

 .
 .
//"INSERT QUERY" function, not relevant
 .
 .

<?php
$action = rtrim($_REQUEST['action']);
$enableSorting = $_REQUEST['enableSorting']; //Here is where I got undefined index, but it only shows up when I delete a record

if($action=="delete")
{
    $id  = rtrim($_REQUEST['id']);

    echo deleteRow($id);
    echo selectAll($enableSorting);
}
elseif($action=="insert")
{
    $name = $_REQUEST['name'];
    $badge_number = $_REQUEST['badge_number'];
    $privilege = $_REQUEST['privilege'];
    $category = $_REQUEST['category'];

    echo insertRow($name, $badge_number, $privilege, $category);
}
elseif($action == "update")
{
    echo selectAll($enableSorting);
}

?>

And here are the relevant codes in my external javascript file:

 function displayTable()
 {
    window.onload = function()
    {
    var page = "database.php"
    var parameters = "enableSorting=sortingDisabled&action=update";
    var xmlhttp = new XMLHttpRequest();

    if(xmlhttp==null)
    {
        alert("Your browser does not support AJAX!");
        return false;
    }
    xmlhttp.onreadystatechange=function()
    {      
       document.getElementById("divTable").innerHTML=xmlhttp.responseText;
    };
    xmlhttp.open("GET", page+"?"+parameters, true);
    xmlhttp.send(null);
    } 
}//displayTable()

function sortTable()
{
    var page = "database.php";
    var parameters = "enableSorting=sortingEnabled&action=update";
    var xmlhttp = new XMLHttpRequest();

    if(xmlhttp==null)
    {
        alert("Your browser does not support AJAX!");
        return false;
    }
    xmlhttp.onreadystatechange=function()
    {      
    document.getElementById("divTable").innerHTML=xmlhttp.responseText;
    };
    xmlhttp.open("GET", page+"?"+parameters, true);
    xmlhttp.send(null);
}//sortTable(sort_key)

function deleteThis(count, privilege)
{
var id  = document.getElementById("row"+count).innerHTML;
var page = "database.php";
var parameters = "id="+id+"&action=delete";
var xmlhttp = new XMLHttpRequest();


if(confirm('Are you sure you want to delete this?')==true)
{
    if(privilege==1)
    {
        alert("You cannot delete a Super Admin!");
        return false;
    }
    else
    {
        if(xmlhttp==null)
        {
            alert("Your browser does not support ajax!");
            return false;
        }
        xmlhttp.onreadystatechange=function()
        {
            document.getElementById("divTable").innerHTML=xmlhttp.responseText; 
        };
        xmlhttp.open("GET", page+"?"+parameters, true);
        xmlhttp.send(null);
        }
    }
    else
    {
        return false;
    }
  }//deleteThis(count)
kross
  • 475
  • 1
  • 11
  • 31
  • You don't have an `action` parameter in `sortTable` – Barmar May 21 '15 at 05:53
  • Are you sure the error is for `$_REQUEST['enableSorting']`, not `$_REQUEST['action']`? – Barmar May 21 '15 at 05:54
  • What does `var_dump($_REQUEST)` show? – Barmar May 21 '15 at 05:57
  • @Barmar Yes, to be exact it's `Notice: Undefined index: enableSorting in /myfolders/database.php on line 85`. – kross May 21 '15 at 05:58
  • Does this happen for all the actions? – Barmar May 21 '15 at 05:59
  • @Barmar Not all, only specifically delete. Although that's because after using insert I don't display the table. Also, `var_dump($_REQUEST)` shows `array(2) { ["enableSorting"]=> string(15) "sortingDisabled" ["action"]=> string(6) "update" }` and after I click delete, `array(2) { ["id"]=> string(2) "83" ["action"]=> string(6) "delete" }` – kross May 21 '15 at 06:02
  • You don't send an `enableSorting` parameter in `deleteThis()`. – Barmar May 21 '15 at 06:09

2 Answers2

1

You're not sending the enableSorting parameter from deleteThis. Try:

function deleteThis(count, privilege)
{
var id  = document.getElementById("row"+count).innerHTML;
var page = "database.php";
var parameters = "id="+id+"&action=delete&enableSorting=sortingDisabled";
var xmlhttp = new XMLHttpRequest();


if(confirm('Are you sure you want to delete this?')==true)
{
    if(privilege==1)
    {
        alert("You cannot delete a Super Admin!");
        return false;
    }
    else
    {
        if(xmlhttp==null)
        {
            alert("Your browser does not support ajax!");
            return false;
        }
        xmlhttp.onreadystatechange=function()
        {
            document.getElementById("divTable").innerHTML=xmlhttp.responseText; 
        };
        xmlhttp.open("GET", page+"?"+parameters, true);
        xmlhttp.send(null);
        }
    }
    else
    {
        return false;
    }
  }//deleteThis(count)

Another option is to change the PHP to use a default if the parameter isn't supplied:

$enableSorting = isset($_REQUEST['enableSorting']) ? $_REQUEST['enableSorting'] : 'sortingDisabled';
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Sorry, I forgot to put that in the question(edited already). It's the same error. – kross May 21 '15 at 05:57
  • But that would mean if I delete without sorting, after the record is deleted, wouldn't the whole table be sorted? – kross May 21 '15 at 06:14
  • OK, then say `&enableSorting=sortingDisabled`. But your PHP script expects the parameter. – Barmar May 21 '15 at 06:19
  • Well now it would mean if the table is sorted then if I delete a record, the table sort would be disabled instead. Thing is, I want to delete while maintaining the state of the table, whether it is sorted or unsorted. Example: If table is already sorted(by clicking the `Name` header) and I delete, just the record would be removed. No unsorting occurs. – kross May 21 '15 at 06:24
  • Then remember the state in a Javascript variable, and use that to put the appropriate parameter in the AJAX call. – Barmar May 21 '15 at 14:09
  • Why does `delete` need to redraw the whole table anyway? Why not just delete the current row from the table in the DOM? – Barmar May 21 '15 at 14:11
  • already did that, will post my solution up soon. As for the delete, how would you suggest I delete the current from the table in DOM? I am not quite sure on how to do that. – kross May 22 '15 at 01:19
  • One way: https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/deleteRow – Barmar May 22 '15 at 01:23
  • See this google search: https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=javascript%20remove%20row%20from%20table – Barmar May 22 '15 at 01:23
  • Hmm I see, but does that really remove the row in the database as well? Because that's the main purpose of my function. – kross May 22 '15 at 01:26
  • No, it just removes it from the web page. I'm suggesting that you use AJAX to remove the row from the database, and Javascript to remove it from the web page. The AJAX call doesn't have to return the table when you delete, so it doesn't need to worry about sorting. – Barmar May 22 '15 at 01:28
0

Instead of using "asc" or "desc" I used 0, 1, or 2. I'm not quite sure why when I use numbers it works though but here's the solution that I came up with. I changed some variable names by the way, but it's the same ones as posted in the question.

    function displayTable()
    {
        window.onload = function()
        {
            var order = 0;
            var page = "database.php";
            var parameters = "order="+order+"&action=update";
            var xmlhttp = new XMLHttpRequest();

            if(xmlhttp==null)
            {
                alert("Your browser does not support AJAX!");
                return false;
            }
            xmlhttp.onreadystatechange=function()
            {      
               document.getElementById("divTable").innerHTML=xmlhttp.responseText;
            };
            xmlhttp.open("GET", page+"?"+parameters, true);
            xmlhttp.send(null);
        } 
    } //displayTable()

    function sortTableName(order)
    {
        //Check if sorting order is default or desc
        if(order==0||order==2)
        {
            order = 1;
        }
        //Check if order is ascending
        else if(order==1)
        {
            order = 2;
        }

        var page = "database.php";
        var parameters = "order="+order+"&action=update";
        var xmlhttp = new XMLHttpRequest();

        if(xmlhttp==null)
        {
            alert("Your browser does not support AJAX!");
            return false;
        }
        xmlhttp.onreadystatechange=function()
        {      
            document.getElementById("divTable").innerHTML=xmlhttp.responseText;
        };
        xmlhttp.open("GET", page+"?"+parameters, true);
        xmlhttp.send(null);
    } //sortTableName(order)

    function deleteThisUser(count, priviledge, order)
    {
        var id  = document.getElementById("row"+count).innerHTML;
        var page = "database.php";
        var parameters = "id="+id+"&order="+order+"&action=delete";
        var xmlhttp = new XMLHttpRequest(); 

        if(confirm('Are you sure you want to delete this?')==true)
        {
            if(priviledge==1)
            {
                alert("You cannot delete a Super Admin!");
                return false;
            }
            else
            {
                if(xmlhttp==null)
                {
                    alert("Your browser does not support ajax!");
                    return false;
                   }
                xmlhttp.onreadystatechange=function()
                {
                    document.getElementById("divTable").innerHTML=xmlhttp.responseText; 
                };
                xmlhttp.open("GET", page+"?"+parameters, true);
                xmlhttp.send(null);
            }
        }
        else
        {
            return false;
        }
    } //deleteThisUser()
kross
  • 475
  • 1
  • 11
  • 31