Using same button twice will not work

I want to use ONE button to change which order the sql database table is being showed.
I will appreciate it if you can tell me why it wont help.

I think I read somewhere a very long time ago that it is some kind of a security parameter to disallow sending a request twice in a row with a single button. Please do refresh my memory if that is the case.

I am doing this (here is the button .1.):[code]

table { width: 100%; border-collapse: collapse; }

table, td, th {
border: 1px solid black;
padding: 5px;
}

th {text-align: left;}

Hey
Hey

Select a person: Peter Griffin Lois Griffin Joseph Swanson Glenn Quagmire
Person info will be listed here...
[/code]

to this (here is the response):

[code]

table { width: 100%; border-collapse: collapse; }

table, td, th {
border: 1px solid black;
padding: 5px;
}

th {text-align: left;}

<?php $q = intval($_GET['q']); $con = mysqli_connect('localhost','...','...','...'); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } if(!isset($change)){$change = "DESC";} switch($change){ case "ASC": $change = "DESC"; break; case "DESC": $change = "ASC"; break; } mysqli_select_db($con,"id1659345_factory"); if ($q == 1){ $sql="SELECT * FROM MyGuests ORDER BY id $change"; $result = mysqli_query($con,$sql); } if ($q === 2){ $sql="SELECT * FROM MyGuests ORDER BY id DESC"; $result = mysqli_query($con,$sql); } echo ""; while($row = mysqli_fetch_array($result)) { echo ""; echo ""; echo ""; echo ""; } echo "
Firstname Lastname
" . $row['firstname'] . "" . $row['lastname'] . "
"; mysqli_close($con); ?> [/code]

If personally would just have an if statement with different queries depending on ASC or DESC.

For example:

[php]if ( $order === “ASC” ) {
$sql=“SELECT * FROM MyGuests ORDER BY id ASC”;
} else {
$sql=“SELECT * FROM MyGuests ORDER BY id DESC”;
}
$result = mysqli_query($con,$sql);[/php]

Don’t use ->
[php]$q = intval($_GET[‘q’]);[/php]

Me bad you are using javascript…hold on I give you solution.

OK, here it is and sorry for the delay I had to dust some cobwebs off. :stuck_out_tongue:

Here’s the main file I named sortDatabase.php (I should had named it sortTable lol)
[php]

Sort by ASC Sort by DESC
    <script>
        var ascBtn = document.getElementById('asc');
        var descBtn = document.getElementById('desc');
        var status = "ASC";
        
        sortTable(status);
        ascBtn.addEventListener('click', function (e) {
            e.preventDefault();
            status = "ASC";
            sortTable(status);
        });
        descBtn.addEventListener('click', function (e) {
            e.preventDefault();
            status = "DESC";
            sortTable(status);
        });
        function sortTable(status) {
            var check = "status=" + status; // Put it in $_POST Format:
            //console.log(check);
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                //console.log('readyState: ' + xhr.readyState, 'xhr.status: ' + xhr.status);
                if (xhr.readyState === 2) {
                    //console.log(xhr.status);
                    if (xhr.status === 410) {

                    }
                }
                if (xhr.readyState === 4 && xhr.status === 200) {
                    var info = JSON.parse(xhr.responseText);
                    
                    for (var x = 0; x <= info.length; x++) {
                        console.log(info[x].Name);
                    }
                    
                }
            }; // End of Ready State:

            xhr.open('POST', 'result.php', true);
            xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            xhr.send(check);
        }</script>
</body>
[/php]

and here’s a separate file that retrieves the data from the result.php file:
[php]<?php

include ‘connection.php’;
/* Makes it so we don’t have to decode the json coming from JavaScript */
header(‘Content-type: application/json’);
$check = filter_input(INPUT_POST, ‘status’, FILTER_SANITIZE_FULL_SPECIAL_CHARS); // Grab The Post

/* Retrieving Data using PDO /
function retreiveData($sql) {
$db_options = [
/
important! use actual prepared statements (default: emulate prepared statements) /
PDO::ATTR_EMULATE_PREPARES => false
/
throw exceptions on errors (default: stay silent) /
, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
/
fetch associative arrays (default: mixed arrays) */
, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
];

$pdo = new PDO('mysql:host=' . DATABASE_HOST . ';dbname=world;charset=utf8', DATABASE_USERNAME, DATABASE_PASSWORD, $db_options);
$stmt = $pdo->prepare($sql); // Prepare the query:
$stmt->execute(); // Execute the query with the supplied user's parameter(s):
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
return $data;

}

if ($check === “ASC”) {
$sql = ‘SELECT Name, Continent, Population FROM country ORDER BY Name ASC’;
} else {
$sql = ‘SELECT Name, Continent, Population FROM country ORDER BY Name DESC’;
}

$data = retreiveData($sql);
$output = $data;
output($output);

/*

  • Set error code then send message to Ajax / JavaScript
    */

function errorOutput($output, $code = 500) {
http_response_code($code);
echo json_encode($output);
}

/*

  • If everything validates OK then send success message to Ajax / JavaScript
    */

function output($output) {
http_response_code(200);
echo json_encode($output);
}
[/php]

I didn’t do any HTML or CSS, but if I were doing this I would do the HTML in the result.php file and just output it to sortDatabase.php in XML format or something that wouldn’t use innerHTML.

HTH John

P.S. I just used the world database table country just to see what I was coding worked. :wink:

Thank you!
It will take some time to figure out what you have done. :slight_smile:
I am very new to PHP, SQL and AJAX.

Here’s how to do it with one (same) button ->
[php]

Descending Order
    <script>
        var sortBtn = document.getElementById("sortBtn");
        var status = sortBtn.getAttribute('data-order');

        sortBtn.addEventListener('click', function (e) {
            e.preventDefault();
            console.log(this.getAttribute('data-order'));
            var order = this.getAttribute('data-order');

            if (order === "ASC") {
                status = "ASC";
                this.setAttribute("data-order", "DESC");
                this.innerText = "Descending Order";
            } else if ( order === "DESC") {
                status = "DESC";
                this.setAttribute("data-order", "ASC");
                this.innerText= "Ascending Order";
            }
            sortTable(status);
        });


        sortTable(status);

        function sortTable(status) {
            var check = "status=" + status; // Put it in $_POST Format:
            //console.log(check);
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                //console.log('readyState: ' + xhr.readyState, 'xhr.status: ' + xhr.status);
                if (xhr.readyState === 2) {
                    //console.log(xhr.status);
                    if (xhr.status === 410) {

                    }
                }
                if (xhr.readyState === 4 && xhr.status === 200) {
                    var info = JSON.parse(xhr.responseText);

                    for (var x = 0; x < info.length; x++) {
                        console.log(info[x].Name);
                    }

                }
            }; // End of Ready State:

            xhr.open('POST', 'result.php', true);
            xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            xhr.send(check);
        }</script>
</body>
[/php]

I must have been bored, so I put this in a table and spiffed the page with CSS. ;D
[php]

Sort By Name
        button {
            cursor: pointer;
            outline: none;
            border: none;
            background-color: green;
            display: block;
            width: 100%;
            max-width: 180px;
            height: 40px;
            font-family: Arial, Helvetica, sans-serif;
            font-size: 1.2em;
            color: #fff;
            margin: 10px auto;
        }
        
        button:hover {
            background-color: red;
            color: #ffa;
        }
        
        /* Table CSS Styling */
        .turnOn {
            display: block;
        }
        .turnOff {
            display: none;
        }
        #search
        {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 1.0rem;
            background: #fff;
            margin: 45px;
            width: 100%;
            width: 500px;
            border-collapse: collapse;
            text-align: left;
            margin: 0 auto;
        }
        #search th
        {
            font-size: 1.2em;
            font-weight: normal;
            color: #039;
            padding: 10px 12px;
            border-bottom: 2px solid #6678b1;
        }
        #search td
        {
            font-size: 0.8em;
            color: #669;
            padding: 9px 8px 0px 8px;
        }
        #search tbody tr:hover td
        {
            color: #009;
        }
    </style>
</head>
<body>
    <button id="sortBtn" name="sorting" value="" data-order="DESC">Ascending Order</button>
    <table id="search" summary="Cities Around the World!">
        <thead>
            <tr>
                <th scope="col">Name</th>
                <th scope="col">Continent</th>
                <th scope="col">Population</th>
            </tr>
        </thead>
        <tbody id="insertData">

        </tbody>
    </table>
    <script>
        var sortBtn = document.getElementById("sortBtn");
        var status = sortBtn.getAttribute('data-order');

        /*
         * Sort Button Script Routine
         */
        sortBtn.addEventListener('click', function (e) {
            e.preventDefault();
            console.log(this.getAttribute('data-order'));
            var order = this.getAttribute('data-order');

            if (order === "ASC") {
                status = "ASC";
                this.setAttribute("data-order", "DESC");
                this.innerText = "Ascending Order";
            } else if (order === "DESC") {
                status = "DESC";
                this.setAttribute("data-order", "ASC");
                this.innerText = "Descending Order";
            }
            sortTable(status);
        });


        sortTable('ASC');

        /*
         *  Ajax and JSON script 
         */
        function sortTable(status) {
            var check = "status=" + status; // Put it in $_POST Format:
            //console.log(check);
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                //console.log('readyState: ' + xhr.readyState, 'xhr.status: ' + xhr.status);
                if (xhr.readyState === 2) {
                    //console.log(xhr.status);
                    if (xhr.status === 410) {

                    }
                }
                if (xhr.readyState === 4 && xhr.status === 200) {
                    var info = JSON.parse(xhr.responseText);
                    var tBody = document.getElementById('insertData');
                    var element = document.getElementById('name1');
                    /*
                     * Don't create elements if they already exists!
                     */
                    if (typeof (element) !== 'undefined' && element !== null) {
                        for (var i = 0; i < info.length; i++) {
                            document.getElementById('name' + (i + 1)).innerHTML = info[i].Name;
                            document.getElementById('continent' + (i + 1)).innerHTML = info[i].Continent;
                            document.getElementById('population' + (i + 1)).innerHTML = info[i].Population;
                        }
                    } else { // Does not exist!
                        for (var x = 0; x < info.length; x++) {
                            var row1 = document.createElement('tr');
                            var tableName = document.createElement('td');
                            var tableNameId = document.createAttribute('id');
                            tableNameId.value = 'name' + (x + 1);
                            tableName.setAttributeNode(tableNameId);
                            tableName.innerHTML = info[x].Name;
                            row1.appendChild(tableName);
                            tBody.appendChild(row1);
                            var row2 = document.createElement('tr');
                            var tableContinent = document.createElement('td');
                            var tableContinentId = document.createAttribute('id');
                            tableContinentId.value = 'continent' + (x + 1);
                            tableContinent.setAttributeNode(tableContinentId);
                            tableContinent.innerHTML = info[x].Continent;
                            row1.appendChild(tableContinent);
                            tBody.appendChild(row2);
                            var row3 = document.createElement('tr');
                            var tablePopulation = document.createElement('td');
                            var tablePopulationId = document.createAttribute('id');
                            tablePopulationId.value = 'population' + (x + 1);
                            tablePopulation.setAttributeNode(tablePopulationId);
                            tablePopulation.innerHTML = info[x].Population;
                            row1.appendChild(tablePopulation);
                            tBody.appendChild(row3);
                        }
                    }
                }
            }; // End of Ready State:

            xhr.open('POST', 'result.php', true);
            xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            xhr.send(check);
        }</script>
</body>
[/php]

Thank you very much for trying! I had a bunch of things to do before I could get to play with your code but now it’s all done.

I have tried to understand your code.
Sadly :stuck_out_tongue: (for me), I cannot get it to work.

I vaguely understand first part; sortDatabase.php
But I probably would not be able to spot a hidden error.

[php]

Gi

Sort by ASC Sort by DESC
     <script>
         var ascBtn = document.getElementById('asc');
         var descBtn = document.getElementById('desc');
         var status = "ASC";
         
         sortTable(status);
         ascBtn.addEventListener('click', function (e) {
             e.preventDefault();
             status = "ASC";
			 document.getElementById("gi").innerHTML= "ok " + status;
             sortTable(status);
         });
         descBtn.addEventListener('click', function (e) {
             e.preventDefault();
             status = "DESC";
			 document.getElementById("gi").innerHTML= "ok " + status;
             sortTable(status);
         });
         function sortTable(status) {
             var check = "status=" + status; // Put it in $_POST Format:
             //console.log(check);
			
             var xhr = new XMLHttpRequest();
             xhr.onreadystatechange = function () {
                 //console.log('readyState: ' + xhr.readyState, 'xhr.status: ' + xhr.status);
                 if (xhr.readyState === 2) {
                     //console.log(xhr.status);
                     if (xhr.status === 410) {

                     }
                 }
                 if (xhr.readyState === 4 && xhr.status === 200) {
                     var info = JSON.parse(xhr.responseText);

                     for (var x = 0; x <= info.length; x++) {
						 console.log(info[x].Name);
                     }
                     
                 }
             }; // End of Ready State:

             xhr.open('POST', 'result.php', true);
             xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
             xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
             xhr.send(check);
         }</script>
 </body>
[/php]

This :o I dont get

  1. I dont know what would be needed in connection.php
  2. Headers
  3. $db_options
  4. Little bit of it all

I dont get any results when I click on the buttons, only the button change.
Thank you for the comments, helped a lot.
[php]<?php

include ‘connection.php’;
/* Makes it so we don’t have to decode the json coming from JavaScript */
header(‘Content-type: application/json’);
$check = filter_input(INPUT_POST, ‘status’, FILTER_SANITIZE_FULL_SPECIAL_CHARS); // Grab The Post

/* Retrieving Data using PDO /
function retrieveData($sql) {
$db_options = [
/
important! use actual prepared statements (default: emulate prepared statements) /
PDO::ATTR_EMULATE_PREPARES => false
/
throw exceptions on errors (default: stay silent) /
, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
/
fetch associative arrays (default: mixed arrays) */
, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
];

 $pdo = new PDO('mysql:host=' . localhost . ';dbname=idi;charset=utf8', idi, notreal12, $db_options);
 $stmt = $pdo->prepare($sql); // Prepare the query:
 $stmt->execute(); // Execute the query with the supplied user's parameter(s):
 $data = $stmt->fetchAll(PDO::FETCH_OBJ);
 return $data;

}

if ($check === “ASC”) {
$sql = ‘SELECT * FROM FolketsDB ORDER BY navn ASC’;
} else {
$sql = ‘SELECT * FROM FolketsDB ORDER BY nave DESC’;
}

$data = retrieveData($sql);
$output = $data;
output($output);

/*

  • Set error code then send message to Ajax / JavaScript
    */

function errorOutput($output, $code = 500) {
http_response_code($code);
echo json_encode($output);
}

/*

  • If everything validates OK then send success message to Ajax / JavaScript
    */

function output($output) {
http_response_code(200);

 echo json_encode($output);

}

?>[/php]

-meanwhile- Mr. Bumblebee is bumping its head in to my window right in front of me, which it does every day -meanwhile-

Now I know why they are named Bumb-lebee

it should be noted that I do google all my problems and check posts, with no luck this time around.

I have essentially fixed my problem with inspiration from you.

Can you tell me why I should not use $_GET([‘q’])?

I personally like $_POST better than $_GET for in my opinion it’s more secure and it doesn’t show up in the URL.
[php]var check = “status=” + status; // Put it in $_POST Format:[/php]
To answer the question of connection.php, it’s just all my connection constants so I don’t accidently post them on the internet. :o
[php]if (filter_input(INPUT_SERVER, ‘SERVER_NAME’, FILTER_SANITIZE_URL) == “localhost”) {
define(‘DATABASE_HOST’, ‘localhost’);
define(‘DATABASE_NAME’, ‘database name’);
define(‘DATABASE_USERNAME’, ‘local user name — usually root’);
define(‘DATABASE_PASSWORD’, ‘local_password’);
define(‘DATABASE_TABLE’, ‘database table’);
} else {
define(‘DATABASE_HOST’, ‘Internet Provider’);
define(‘DATABASE_NAME’, ‘remote database name’);
define(‘DATABASE_USERNAME’, ‘remote_username’);
define(‘DATABASE_PASSWORD’, ‘remote_password’);
define(‘DATABASE_TABLE’, ‘database table’);
}[/php]

the above is just a generic connection constants that I use and have an if statement so I don’t have to bother change when I start my final testing on my remote server.

The database I use is world.sql (See file attached) for the example I use and instructions on how to set it up → http://download.nust.na/pub6/mysql/doc/world-setup/en/world-setup.html

a good resource to understand PDO is https://phpdelusions.net/pdo. In my opinion it explains PDO very well and I sometimes use it when I have a brainfart. ;D PDO in my opinion is more versatile than mysqli and it is easier to grasp once you finally understand the syntax.


world.sql.zip (90.1 KB)

Sponsor our Newsletter | Privacy Policy | Terms of Service