Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Significance of Reflection in AJAX-Based Applications

Ajax and Reflection

I am developing an ajax-based application and wondering, what role reflection plays or might play here?

Probably most importantly I am asking myself, if it would be a good approach to

  • handle all ajax responses through a single handler,
  • reflect or interpret the data or error
  • delegate further processing (e.g. where to inject the html) based upon the analysis.

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

Additional clearification

My current implementation, which I am not happy with, looks like this.

  • Register eventhandlers for user action, which lead to ajax requests.
  • For each request:
    • Determine which container is the target for the new content
    • Validate the ajax response
    • Pass the result to the appropiate rendering function if everything is as expected

Here is an example

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);
             }
        }
    });
 }

Question

How can this and especially the redundant error checking be simplified? Could Reflection, in a sense of: "Is the response valid? And what does the error message say or data look like?" be a reasonable structure do deal with this? Additionally: Is the "coupling" of the actual ajax request and determing the $targetContainer a "normal" procedure?

Many thanks,
Robson

like image 892
SunnyRed Avatar asked Aug 12 '11 19:08

SunnyRed


People also ask

Why use Ajax?

AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.

How PHP can be used in an Ajax applications?

Create an XMLHttpRequest object. Create the function to be executed when the server response is ready. Send the request off to a PHP file (gethint. php) on the server.

Does Ajax still exist?

Yes, AJAX (XHR) is used all the time in web pages. It is still the primary way that JavaScript in a web page makes an in-page request to a server.


1 Answers

Yes I think register ajax handler trought one pipe is a good way, because it is more easy to control, you will have less redundant code and less boarding effects. If I look at your code comments it seems the response is not as you expect. I use to do like this for controling a group of ajax request talking with server script. I build one request object like :

    // 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);
            }
        };

then when use this object trought all my group of different actions and I precise wich action and arguments I pass. I use to ask for a json data so I am able to receive an easy parsing response, so I am able to return the original command asked, and some details on errors that may occured for example, and when I need to fire the request :

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

Then an example of one server script that will respond :

// 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;

They may be some errors, it is just for the principe, I hope that will help, just some last advices :

  • you should better use the requestObject.data to pass any arguments instead of setting the url like you did, this is much more easy because jQuery does the properly encoding work
  • you may use POST so the url stay clean, post vars are 'hidden'
  • in your case, because you may want to centralize server actions with ONE server script, you should use 'json' as dataType because it is much easier to retrieve details from the response, such errors. You have to distinct the ajax error that is trigger when the url doesn't exist, or access denied, well when the server replies it just can't respond to this request, and distinct the properly response of your server script, I mean the script responds well but it may occur an command error, for example for a 'loadfile' command, the argument fileUrl may be wrong or unreadable, so the action is done but the response will be not valid for you...

If you plan to fire many loads for differents parts (I mean you may don't wait response for an ajax before loading a new one), it should be better to set main success and errors functions for keeping centralization and then build one new request object each time you make a load

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);
like image 128
dmidz Avatar answered Nov 04 '22 00:11

dmidz