The reflection value in AJAX-based applications

Ajax and reflection

I am developing an ajax-based application and wondering what role the game plays or can play here?

Perhaps most importantly, I ask myself if this would be a good approach to

  • process all ajax responses through one handler,
  • reflect or interpret data or errors
  • delegate further processing (for example, where to enter html) based on the analysis.

Is this a promising procedure? What pros and cons come to mind?

Additional cleaning

My current implementation, which I am not happy with, is as follows.

  • Register event handlers for user actions that result in ajax requests.
  • For each request:
    • Determine which container is the target for the new content.
    • Confirm ajax answer
    • ,

function setGamedayScoringChangeHandlers() {
    $("#community").delegate("div.community div.nav", "click", function() {
        var orderId = $(this).html();
        var communityId = $(this).closest('.communityView ').dashId();
        requestGamedayScoringByOrderId(communityId, orderId);
    });
}

function requestGamedayScoringByOrderId(communityId, orderId) {
    var $targetContainer = $('#community-' + communityId + '-gameday');
    $.ajax({
        url: '?api=league&func=getGamedayScoringByCommunityIdAndOrderId',
        data: {
            communityId : communityId,
            orderId : orderId
        },
        success: function(result) {

             // custom indicator, that sth. didn't work as supposed 
             if (result.success === false) {

                 // a php error couldn't be handled as expected
                 if (result.error === 'phpRuntimeError') {
                      // ..
                 }

             // ..

             }

             else {
                 renderGamedayScoring(result, $targetContainer);
             }
        }
    });
 }

? Could Reflection, : " ? ?" ? : "" ajax $targetContainer "" ?

,
Robson

+5
2

, , ajax , , , . , , , . ajax-, script. , :

    // myscript.js
var rqPHP = {
            url:'php/dispatcher.php', type:'POST', dataType:'json',
            success:function(json, status, jXHR){
                //console.log('rqPHP.succes : ', json);
                if(!json)   return console.warn('[rqPHP.success] json is null');
                if(!json.cmd)   return console.warn('[rqPHP.success] json.cmd is null');
                if(!json.res)   return console.warn('[rqPHP.success] json.res is null');
                if(json.err && json.err.length){        console.warn('[rqPHP.success errors cmd:'+json.cmd+'] '+json.err);}
                // so if no errors, dispatch actions based on original command asked
                switch(json.cmd){
                    case 'loadfile' :
                        // do whatever with response
                        break;
                    case 'savefile' :
                        // do whatever with response
                        break;
                }
            },
            error:function(jXHR, status, err){
                console.warn('[rqPHP.error] ', status,',',err,',',jXHR.responseText);
            }
        };

, . json-, , , , , :

// myscript.js
rqPHP.data = {'cmd':'loadfile', 'filename':'file.dat', 'arg2':'other argument'};
$.ajax(rqPHP);

script, :

// dispatcher.php    
    $pv = $_POST;
    $res = '';
    $err = array();
    // you check the command asked for :
    switch(strtolower($pv['cmd'])){
      case 'savefile' :
        // do whatever
        break;
      case 'loadfile' :
        // do whatever
        if(any error){
          $err[] = $loadError;// push error with whatever details you'll retrieve in javascript
       }else{
         $res = ',"res":"'.$dataLoaded.'"';// format json response so you'll check the var exist
        }
        break;
    }
    $jsonRes = '{"cmd":"'.$pv['cmd'].'"'.$res.',"err":"'.implode('|', $err).'"}';// json result
    print $jsonRes;

, , , , :

  • requestObject.data URL-, , , jQuery
  • POST, URL , post vars "".
  • , script, 'json' dataType, , . ajax, , URL- , , script, , script , , , "loadfile", fileUrl , , ...

( , ajax ), ,

function rqSuccess(json, status, jXHR){
   // put same checking code as before, then you can also retrieve some particular variables
   // here, 'this' should correspond to the request object used for the $.ajax so :
   console.log('myTarget is : ', this.myTarget, ' , myVariable is : ', this.myVariable);
}
function rqError(jXHR, status, err){
   // put same checking code 
}
// then each time you want make one or many independant calls, build a new request object
var myRq = {url:'dispatcher.php',type:'POST',dataType:'json',
    success:rqSuccess,
    error:rqError,
    myTarget:$('#myblock'),// any variable you want to retrieve in response functions
    myVariable:'Hello !',// after all it is an object, you can store anything you may need, just be carefull of reserved variables of the ajax object (see jQuery $.ajax doc)
    // the data object is sanitized and sended to your server script, so put only variables it will need
    data : {'cmd':'loadfile',...}
}
$.ajax(myRq);
// you may load an other independant one without waiting for the response of the first
var myRq2 = {...myTarget:$('#anotherblock'), data:{'cmd':'anotheraction'}...}
$.ajax(myRq2);
+3

, -OK/200 , . 500. , .

, jQuery : http://api.jquery.com/ajaxError

+3

All Articles