0

Below is my ajax: This will display result from a query from PHP page that filtered by category,postcode and rate keyed in by user.

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

    data = $(this).serialize() + "&" + $.param(data);
    $.ajax({
        type: "POST",
        dataType: "json",
        url: "ajax2.php",
        data: data,
        success: function (data) {

        $("#main_content").slideUp("normal",function(){
         for (i = 0; i < data.length; i++) {

$(".the-return").append("<div class='inside_return'>Name:" + data[i].name + "<br/>Id:" + data[i].id + "<br/>Pricing:" + data[i].rate + "<br/>Postcode:" + data[i].postcode+ "<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;


});

I wish to know how to control this part, I mean how to control which action to take after success:

By default it can show as below: But when 'Sort by rate' clicked it should sort by rate and display inside .the-return. And when 'sort by rank' clicked it should sort by rank and display. How can I locate the switch statement in here and display accordingly please? I'm worn out looking for an answer to this, any help would be greatly appreciated! Thanks in advance!!!!

success: function (data) {

            $("#main_content").slideUp("normal",function(){
             for (i = 0; i < data.length; i++) {

    $(".the-return").append("<div class='inside_return'>Name:" + data[i].name + "<br/>Id:" + data[i].id + "<br/>Pricing:" + data[i].rate + "<br/>Postcode:" + data[i].postcode+ "<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>");

            }

        });
       }        



    });
   return false;

  });
Mox Shah
  • 2,967
  • 2
  • 26
  • 42
sherly
  • 305
  • 1
  • 7
  • 18

3 Answers3

1

Json object can be sorted this way:

data.sort(function (a, b) {
    var retVal = 0;
    switch (sortOption) {
        case 1:
            retVal = a.property > b.property ? 1 : (a.property < b.property ? -1 : 0);
            break;
        ....
    }
    return retVal;
});

Explaination: The data here is a json object. The sort() is a javascript function. This function is called for each pair of json objects in the json array. The returned value (retVal here) is used by js to decide if the json element a precedes json element b. If the retVal value is 1, b precedes a, vice-versa for -1 and undecided for 0. sortOption is for your requirement. You can use it to decide on what to compare the elements, depending on the Sort by value selected by the user.
You can place this code at the place where you want to sort the json array.

Code for you:

success: function (data) {
    data.sort(function (a, b) {
        var retVal = 0;
        switch (sortOption) {
            case 1:
                retVal = a.property > b.property ? 1 : (a.property < b.property ? -1 : 0);
                break;
                // .... many cases here
        }
        return retVal;
    });
    $("#main_content").slideUp("normal", function () {
        for (i = 0; i < data.length; i++) {

            $(".the-return").append("<div class='inside_return'>Name:" + data[i].name + "<br/>Id:" + data[i].id + "<br/>Pricing:" + data[i].rate + "<br/>Postcode:" + data[i].postcode + "<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>");

        }

    });
}
Ganesh Jadhav
  • 2,830
  • 1
  • 20
  • 32
  • can you explain in detail plz.. I'm vey new to ajax,jqury and json... where do I place this code, and how do I call this function – sherly May 07 '15 at 13:22
  • thanks fro the explanation: Can I locate this inside success function? BUt how do I append the html to the .the-return div? – sherly May 07 '15 at 13:32
  • Please see I've updated my answer. The `data.sort()` just sorts the array. Rest of your code can be used as it is to create and append the html. – Ganesh Jadhav May 07 '15 at 13:37
  • just one more thing, how to call the function? Say $("#rate").on("click",function(){ //how to call the function here???}); – sherly May 07 '15 at 13:45
  • You can directly do `$("#rate").on("click",function(){ data.sort(); });` or create another independent function for `data.sort()` and call it there. You can even pass the `sortOption` depending on the value of `#rate` to the new function. – Ganesh Jadhav May 07 '15 at 13:50
  • can I pass string value? If I pass "rate" the function should recognize which data I need to sort right? – sherly May 07 '15 at 13:55
  • You can pass and `switch()` the string. "which data" means to filter the json array. The `switch()` can be used to determine "which property to sort on". – Ganesh Jadhav May 07 '15 at 13:59
  • Nope I cannot get it work..when I place the above function after success function like above, form is not submitted..I placed it outside as a separate function also same. – sherly May 07 '15 at 14:27
0

Call sortByProperty, pass it the property name, the array to sort, and a bool signifying whether to sort descending or not.

var currentlySortingBy = '';
var sortDesc = true;

var sortByProperty = function (propertyName, array, sortDescending) {
    currentlySortingBy = propertyName;
    sortDesc = sortDescending;

    return array.slice(0).sort(propertyComparer);
};

var propertyComparer = function (a, b) {
    var isString = typeof a[currentlySortingBy] === 'string';

    var aProp = isString ? a[currentlySortingBy].toLowerCase() : a[currentlySortingBy];
    var bProp = isString ? b[currentlySortingBy].toLowerCase() : b[currentlySortingBy];

    var sortDir = sortDesc ? 1 : -1;
    return ((aProp < bProp) ? sortDir : ((aProp > bProp) ? -sortDir : 0));
};
TomSlick
  • 717
  • 5
  • 21
  • can I locate this function inside success function? BUt I'm unsure how to appendthe html to the .the-return div? – sherly May 07 '15 at 13:34
  • You put these functions outside the ajax call and then call them whenever you need. Appending the html the way you are doing is fine. Just sort the array first, then loop and append. `data = sortByProperty('rate', data, true);` – TomSlick May 07 '15 at 14:11
0

There actually are multiple ways of sorting JSON objects. The first way is to write your own order function.

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
myJson.sort(sort_by('price', true, parseInt));

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

Obtained from: https://stackoverflow.com/a/979325/2076351

Another option would be to use underscorejs.

_.sortBy([1, 2, 3, 4, 5, 6], function(num){ return Math.sin(num); });
=> [5, 4, 6, 3, 1, 2]

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.sortBy(stooges, 'name');
=> [{name: 'curly', age: 60}, {name: 'larry', age: 50}, {name: 'moe', age: 40}];

As displayed here: http://underscorejs.org/#sortBy

Community
  • 1
  • 1
lt.kraken
  • 1,287
  • 3
  • 10
  • 27