-1

I have a MySql table as:

id           Name
1            John
2            Ray
3            Tom

And this is code for front end html file used to called the ajax and display result:

<html>
<head>
<script language="javascript" type="text/javascript" src="jquery-1.6.2.js"></script>
<script language="javascript" type="text/javascript" src="ajax.js"></script>
</head>
<body>
<input type="button" value="Click Here" id="ajaxButton"/>
<div id="result"></div>
</body>
</html>

I want to create a client sided script to display the table as random order every time the user refreshes:

 2            Ray 
 1            John
 3            Tom

Here is the script which will be retriving the data from MySql:

$(document).ready(function() {
    $("#ajaxButton").click(function() {
        $.ajax({
              type: "Post",
              url: "employee.php",
              success: function(data) {
                    var obj = $.parseJSON(data);      


               --CODE HERE---


              }
        }); 
    });
});

Pleas help as to what should be written in place of ---CODE HERE---- to get the random table as mentioned before.

1 Answers1

1

As suggested by @Barmar, to get random results, add ORDER BY RAND() in your mysql query. If you want to use it only using javascript, try this solution: https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array

If your JSON is in format: [{id: 1, name: 'John'},{id: 2, name: 'Ray'}]

Try this code in JS:

$(document).ready(function() {
    $("#ajaxButton").click(function() {
        $.ajax({
              type: "POST",
              url: "employee.php",
              success: function(data) {
                    var obj = $.parseJSON(data);      
                    var str = '<table>';
                    for(i in obj)
                    {
                     str+='<tr><td>'+obj[i].id+'</td><td>'+obj[i].name+'</td></tr>';
                    }
                    str+='</table>';

                   $('#result').html(str);
              }
        }); 
    });
});
Community
  • 1
  • 1
Apul Gupta
  • 3,044
  • 3
  • 22
  • 30