Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6252245
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T13:45:43+00:00 2026-05-24T13:45:43+00:00

Ajax and Reflection I am developing an ajax-based application and wondering, what role reflection

  • 0

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

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T13:45:45+00:00Added an answer on May 24, 2026 at 1:45 pm

    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);
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an application that uses AJAX liberally. I have several places where a
I am writing an Ajax application which uses a callback function to add a
I am building an AJAX application that uses both HTTP Content and HTTP Header
Ajax , Flex and Silverlight are a few ways to make more interactive web
Problem: Ajax suggest-search on [ n ] ingredients in recipes. That is: match recipes
In AJAX applications that need to poll the server in regular intervals (like a
I'm writing an AJAX app, but as the user moves through the app, I'd
When using jQuery 's ajax method to submit form data, what is the best
I have an Ajax.Net enabled ASP.Net 2.0 web site. Hosting for both the site
The ASP.NET AJAX ModalPopupExtender has OnCancelScript and OnOkScript properties, but it doesn't seem to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.