1

Is it possible to process a JSON response from a Server in jQuery.ajax(), before the complete or error is executed?

Or let me extend the question:

While processing the JSON data (each response property), tell $.ajax() if it is a success and complete AJAX request, or it is an error, so $.ajax({error: function() {} }); is executed?


Example Psuedocode:

$.ajax({
    url: 'script.php',
    type: 'POST',
    data: {some: 'data-1'},
    dataType: 'json',
    process: function(data) {
        if(data.success == true && (data.data.length > 0)) {
            this.success = true;
        } else {
            this.success = false;
        }
    },
    success: function() {
        if( this.success == true ) {
            // it was a success
        }
    },
    error: function() {
        if( this.success == false ) {
            alert('there was an error');
        }
    }
});

Why you might ask? Because I want to use a single $.ajax() syntax everywhere, and only $.ajax({ process: function(data) {} }); should be altered from time to time.

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52

3 Answers3

0

Yes it is

function setDefaultPoint(){
    var officeId =  $('#clientTrip_officeId').val();

    $.ajax({
        url:"${createLink(controller:'clientTrip',action:'setDefaultPoint')}",
        dataType: "json",
        data: { officeId: officeId },
        success: function(data) {
            console.log(data.defaultPoint.id, data.defaultPoint.name);
            console.log(data.company.id, data.company.name);
        }

    });
}
fizampou
  • 717
  • 2
  • 10
  • 29
0

The simple answer is no, unless you wanted to write your own JSON parser.

Using standard jQuery features, AJAX success and error handlers will fire in response to successful/unsuccessful retrieval of data respectively, without regard to the correctness of the data other than it being well formed JSON.

Data is only provided to the success handler, so if you want to filter it, you must do so in therein.

The good news is that you can get the kind of action you seek, with a $.Deferred() under your own control, which is resolved/rejected in response to whatever conditions you choose, in either of the two handlers. This would typically be done inside a function which returns the Deferred's promise.

The code would be something like this :

function getData() {
    var dfrd = $.Deferred();
    $.ajax({
        url: 'script.php',
        type: 'POST',
        data: {some: 'data-1'},
        dataType: 'json'
    }).done(function(data, textStatus, jqXHR) {
        if(data.success == true && (data.data.length > 0)) {
            dfrd.resolve(data, textStatus, jqXHR);
        } else {
            dfrd.reject(jqXHR, "client-side error", "data.success==false and/or data.data.length==0");
        }
    }).fail(dfrd.reject);
    return dfrd.promise();
}

Thus, the function performs the additional checks you require, and the returned promise emulates the done/fail characteristics of an jqXHR.

It would take a little more thought to give the returned promise the full functionality of an jqXHR - eg. the .abort() method.

Beetroot-Beetroot
  • 18,022
  • 3
  • 37
  • 44
0

There are global event handlers for ajax events:

$(document).ajaxComplete() //called when Ajax requests complete
$(document).ajaxError() //called when Ajax requests complete with an error
$(document).ajaxSend() //executed before an Ajax request is sent
$(document).ajaxStart() //called when the first Ajax request begins
$(document).ajaxStop() //called when all Ajax requests have completed
$(document).ajaxSuccess() 
//function to be executed whenever an Ajax request completes successfully

as well as ajax setup:

$(document).ajaxSetup({
    url: 'script.php',
    type: 'POST',
    data: '{}',
    dataType: 'json'
});

then you can call:

 $.ajax({ data: myData });

and it uses all the above

Here is an example using asp.net where it sends back the .d property and this converts that to just the JSON you need:

$(document).ajaxSetup({
    data: "{}",
    dataType: "json",
    type: "POST",
    contentType: "application/json",
    converters: {
        "json jsond": function(msg) {
            return msg.hasOwnProperty('d') ? msg.d : msg;
        }
    },
    error: function(xhr, textStatus, errorThrown) {
        var errorMessage = "Ajax error: " + this.url
             + " : " + textStatus + " : " + errorThrown 
             + " : " + xhr.statusText + " : " + xhr.status;
        alert(errorMessage);
        if (xhr.status != "0" || errorThrown != "abort") {
            alert(errorMessage);
        }
    }
});

NOTE: this converter executes prior to the success or complete - so I "think" this is what you are asking.

Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100