How to sort data retrieved from database using jquery / ajax?

Below is my query that fetches data using filters:

$statement = $pdo->prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2 AND pricing=:rate2");
    $statement->execute(array(':key2' => $key2,':postcode2'=>$postcode,':rate2'=>$rate));
 // $row = $statement->fetchAll(PDO::FETCH_ASSOC);
  $json = array();
 while( $row = $statement->fetch()) {

     array_push($json, array("name" => $row['Name'], "id" => $row['PostUUID'],"rate" => $row['pricing'],"reputation" => $row['Reputation'],"plus" => $row['ReviewPlus'],"neg" => $row['ReviewNeg'],"weekM" => $row['week_morning'],"weekA" => $row['week_afternoon'],"weekE" => $row['week_evening'],"endM" => $row['weekend_morning'],"endA" => $row['weekend_afternoon'],"endE" => $row['weekend_evening']));
 }

    header('Content-Type: application/json');

    echo json_encode($json);

      

This is my ajax

$("form").on("submit", function () {
    var data = {
        "action": "test"
    };

    data = $(this).serialize() + "&" + $.param(data);
    $.ajax({
        type: "POST",
        dataType: "json",
        url: "ajax2.php", //Relative or absolute path to response.php file
        data: data,
        success: function (data) {

            $("#main_content").slideUp("normal",function(){

            //$(".the-return").html("<br />JSON: " + data+"<br/>");
            for (i = 0; i < data.length; i++) {

$(".the-return").append("<div class='inside_return'>Name:" + data[i].name + "<br/>Id:" + data[i].id + "Pricing:" + data[i].rate + "<br/>Reputation:" + data[i].reputation+"<br/>Review Plus:" + data[i].plus+"<br/>Review Negative:" + data[i].neg+"<br/><h1>Availability</h1>Week Morning:" + data[i].weekM+"<br/>Week Afternoon:" + data[i].weekA+"<br/>Week Evening:" + data[i].weekE+"<br/>Weekend Morning:" + data[i].endM+"<br/>Weekend Afternoon:" + data[i].endA+"<br/>Week Evening:" + data[i].endE+"</div>");
            //alert(data[i].name) 
        }



            });
        }
    });
    return false;


});

      

Now I already have a display of data on a page with the specified filters, that is, the result should be counted using subad, poscode and the speed collected from user input.

I let the user sort the already received data by view, rank and so on ... It should be fast (ajax). But am I really doing this? Can anyone give an idea please.

The result is not in the form of a table row, but they are displayed in a div block per entry.

How can I use jquery to achieve this, for example if the user clicked the "Sort by Rating" button.

I have an idea: instead of starting a new query in db each user to sort, how can I loop over the array of data received in json above and just from there from there?

$('#rank').on("click", function(){ //how to sort here});

      

SEPARATE PART:

referring to this link: Sorting an Array of JavaScript Objects

I am trying something like:

var sort_by = function(field, reverse, primer){

   var key = primer ? 
       function(x) {return primer(x[field])} : 
       function(x) {return x[field]};

   reverse = !reverse ? 1 : -1;

   return function (a, b) {
       return a = key(a), b = key(b), reverse * ((a > b) - (b > a));
     } 
}

// Sort by price high to low
data.sort(sort_by('rate', true, parseInt));

// Sort by city, case-insensitive, A-Z
data.sort(sort_by('Name', false, function(a){return a.toUpperCase()}));

      

But it doesn't work, can anyone help?

+3


source to share


1 answer


This solution tries to use inline view.

// I assume in the code that there are 2 properties "name" and "rating".

// a and b are of the same type as the data
function ratingComparer(a, b)
{
   if(parseInt(a.rating) < parseInt(b.rating))
     return -1;
   if(parseInt(a.rating) > parseInt(b.rating))
     return 1;

   return 0;
}

function nameComparer(a,b)
{
    // Same thing as with rating except we do string comparisons with a.name
    // and b.name
}

//Sort by rating
data.sort(ratingComparer);

// Sort by name
data.sort(nameComparer);

      



See link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort . The section right above the example is especially important for your situation, I think.

EDIT: , , , 2 . , -, , .

0









All Articles