HTML通过Ajax在同一页面上将所选选项发送到PHP

What I want to acheive: I have a HTML/PHP page where I display the home page of the website. I have a highscore section on this page. The data for the highscore page is retrived from a database. There is a Select box where you can choose how the highscores are sorted.

The highscore section on the page

I want to be able to select an option from the dropdown. When an option is selected, the way that the data is displayed changes dynamically, without the page refreshing.

Here is the code on the home.php page (Where the highscore section is)

<div class="third third-center">
            <h2>Highscores</h2>
            <div class="sortby">
                <form id="" method="post" action="home.php">
                    <select id="selectForm" name="sort">
                      <option value="score ASC">Score Ascending</option>
                      <option value="score DESC">Score Descending</option>
                      <option value="userName ASC">Name Ascending</option>
                      <option value="userName DESC">Name Descending</option>
                    </select>
                </form>
            </div>
            <div class="inner">
                <table>
                    <tr>
                        <th style="font-size: 20px">Position</th>
                        <th style="font-size: 20px">Name</th>
                        <th style="font-size: 20px">Score</th>
                    </tr>
                    <?php
                        $i = 0;

                        $choice = "score ASC";

                        $search = mysqli_query($connect, "SELECT * FROM accounts ORDER BY ".$choice."") or die(mysqli_error($connect));


                        while($row = mysqli_fetch_array($search)){
                            $i++;
                            echo "<tr>";
                            echo "<th>" . $i . "</th>";
                            echo "<th>" . $row['userName'] . "</th>";
                            echo "<th>" . $row['score'] . "</th>";
                            echo "</tr>";
                        }
                    ?>
                </table>
            </div>
        </div>

I am using the Mysqli_Query to get all the data from the database. I am passing in a variable in place of the ORDER BY so that I can change the way the data is retrieved.

I know I can use Ajax to get the data, but Im not sure how to do it, I have looked at many other questions posted on this forum.

Any help would be greatly appreciated!

Use JQuery AJAX something like so:

Make two pages one where you display data(index.php) and other from where you fetch data (process.php).

The content of index.php would be something like:

<div class="third third-center">
            <h2>Highscores</h2>
            <div class="sortby">
                <form id="" method="post" action="home.php">
                    <select onChange="getData();" id="selectForm" name="sort">
                      <option value="score ASC">Score Ascending</option>
                      <option value="score DESC">Score Descending</option>
                      <option value="userName ASC">Name Ascending</option>
                      <option value="userName DESC">Name Descending</option>
                    </select>
                </form>
            </div>
            <div class="inner">
                <table>
                    <thead>
                    <th>
                        <th style="font-size: 20px">Position</th>
                        <th style="font-size: 20px">Name</th>
                        <th style="font-size: 20px">Score</th>
                    </th>
                    </thead>
                    <tbody id="data"></tbody>
                </table>
            </div>
        </div>

The code of process.php should be something liek:

            <?php
                $i = 0;
                if($_REQUEST['sortBy'] == "score ASC")
                {
                $choice = "score ASC";
                }
                 else if ()//and so on

                $search = mysqli_query($connect, "SELECT * FROM accounts ORDER BY ".$choice) or die(mysqli_error($connect));


                while($row = mysqli_fetch_array($search)){
                    $i++;
                    echo "<tr>";
                    echo "<th>" . $i . "</th>";
                    echo "<th>" . $row['userName'] . "</th>";
                    echo "<th>" . $row['score'] . "</th>";
                    echo "</tr>";
                }
            ?>

Your Javascript should be like:

            function getData()
            {
            $.ajax({
                url     : 'process.php',
                method    : 'GET',
                data:{ sortBy:$('#selectForm').val() }
                success   : function(response)
                {
                   $('#data').html(response);
                },
                error : function(e)
                {
                    alert('error');
                }
            });
          }

you can make another page by the name of highscores.php and get all the code there.then make a call on page load to get the scores dynamically in this div.

  $(document.ready(function(){
//on page load,for the first time.
$('#highscore').load('http://site_url/highscores.php');
//on selectbox change
$('#selectbox').change(function(){
 $.post("highscores.php", {sort: val}, function(data){
    //perform sorting and return the data div.
 $('#highscore').html(data);
});
 })
});
//// homepage section where the scores load,add a div by the id 
<div id="highscore"></div>

//////// highscore page
<div class="third third-center">
        <h2>Highscores</h2>
        <div class="sortby">
            <form id="" method="post" action="home.php">
                <select id="selectForm" name="sort">
                  <option value="score ASC">Score Ascending</option>
                  <option value="score DESC">Score Descending</option>
                  <option value="userName ASC">Name Ascending</option>
                  <option value="userName DESC">Name Descending</option>
                </select>
            </form>
        </div>
        <div class="inner">
            <table>
                <tr>
                    <th style="font-size: 20px">Position</th>
                    <th style="font-size: 20px">Name</th>
                    <th style="font-size: 20px">Score</th>
                </tr>
                <?php
                    $i = 0;

                    $choice = "score ASC";

                    $search = mysqli_query($connect, "SELECT * FROM accounts ORDER BY ".$choice."") or die(mysqli_error($connect));


                    while($row = mysqli_fetch_array($search)){
                        $i++;
                        echo "<tr>";
                        echo "<th>" . $i . "</th>";
                        echo "<th>" . $row['userName'] . "</th>";
                        echo "<th>" . $row['score'] . "</th>";
                        echo "</tr>";
                    }
                ?>
            </table>
        </div>
    </div>

There are couple of changes to be done by you, first you need to change the selection box code such that you need to write an on change function and read the value in the javascript and then execute your AJAX call. Second is after the ajax call get the response from the server you need to do a DOM manipulation and populate the value in your desired format.

For example

$(document).on("change", "#select_box_id", function(){
  //your ajax call here based on the value 
});

I don't know whether you use jquery, if not import the library in your file and use it, which will make your life simpler

Look at this for basic AJAX http://api.jquery.com/jquery.ajax/

If you don't wish to have "live" high-scores that are reloaded from the database every time someone changes the sorting, you might be better off loading the scores into a JavaScript object and then (re)arranging them with JavaScript.

For this you'd need to have a div-element into which you recreate the data (+table structure, if needed) with something like innerHTML after you have sorted the array as you wish with sort. You run this with onChange event in the dropdown list, for example.

If you have a div, for example:

<div id="targetdiv"></div>

So your PHP-generated array could look something like:

var scores = [
  {
    "name" : "Adam",
    "score": "100"
  },
  {
    "name" : "Bert",
    "score": "150"
  },
  {
    "name" : "Cecilia",
    "score": "75"
  } ];

And your sorting algorith could be something like:

scores.sort(function(a, b) {
 return parseFloat(a.scores) - parseFloat(b.scores);
});

Then just save the result to a string variable in a for-loop or whatever you want and output it into that "targetdiv" div:

var intostring = "By SCORES!<br><br>"

for (var index = 0; index < scores.length; ++index) {
    intostring += scores[index]["name"] + ": " + scores[index]["score"] + "<br>";
}

document.getElementById('targetdiv').innerHTML = intostring;

I made a JSFiddle example for you to better demonstrate the above code:

https://jsfiddle.net/docweird/oaqoysm6/

(Without the onChange and dropdown).