Tips for avoiding code breaks when working with AJAX

When it comes to programming with AJAX, I find it challenging to maintain readable and understandable code.

Overview:

The basic concept is simple. I use an AJAX function called getServerData to fetch data from the server. One of the arguments in this function is callbackFunc, which gets invoked once the data is retrieved.

Here's the AJAX routine I typically follow to retrieve data:

function getServerData(urlAddress, params, callbackFunc, sender, method){
    if (method !== "GET"){method = "POST";}
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
            if (callbackFunc){callbackFunc(xhttp.responseText, sender);}
        }
    };
    if (method == "GET"){
        xhttp.open(method, urlAddress, true);
        xhttp.send();
    }
    else {
        xhttp.open(method, urlAddress, true);
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.send(params);
    }
}

And here's a sample callback routine:

do_Select = function(responseText, sender){
 alert(responseText);
}

So, whenever I need to load data and execute something afterwards, I utilize it like this:

getServerData("example.com/select.php", someParams, do_Select, this, "POST");

The issue:

However, my dilemma arises when my do_Select function becomes too lengthy like this:

do_Select = function (responseText, sender) {
            switch (responseText) {
                case "one":
                    if (something1 === something2) {
                        //....
                        getServerData("example.com/select.php", someParams, callback2, this, "POST");
                    } else
                    {
                        //....
                        getServerData("example.com/select.php", someParams, callback3, this, "POST");
                    }

                    break;
                case "two":
                        //....
                        getServerData("example.com/select.php", someParams, callback4, this, "POST");
                    break;
            }
        }

Having to declare multiple callback functions elsewhere in the code complicates the logic and readability as the code expands over time.

Is there a more efficient way to streamline and enhance the code for better readability?

Answer №1

Simplify your code by utilizing either anonymous functions or promises:

getServerData("example.com/select.php", someParams,function(arg){
    alert(arg);}
, this, "POST");

Alternatively, you can make use of promises to achieve the same result:

function getServerData(urlAdress, params, sender, method){
return new Promise(function(callbackFunc){
if (method !== "GET"){method = "POST";}
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
        if (callbackFunc){callbackFunc(xhttp.responseText, sender);}
    }
};
if (method == "GET"){
    xhttp.open(method, urlAdress, true);
    xhttp.send();
 }
 else {
    xhttp.open(method, urlAdress, true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.send(params);
  }
 });
}

To implement this approach, simply do:

getServerData("example.com",someparams,this,"POST").then(console.log);

Answer №2

Just one phrase: Embracing Promises. Perhaps add another term: fetch, to eliminate messy XHR code. The final code structure could be envisioned as:

fetch(arguments)
  .then(response => response.text())
  .then(textResponse => {
    // Process first fetch response and proceed to the next step.
    return (condition1) ? fetch(arguments)
         : (condition2) ? fetch(arguments)
         : fetch(arguments);
  })
  .then(response => response.text())
  .then(textResponse => {
    // Continue with processing the response from whichever fetch was performed.
  });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to update JSON file on server using JavaScript

I am encountering an issue that has been discussed quite frequently. Despite trying various solutions, none have proven effective so far. The problem lies in my JavaScript file where I have some data that I need to append to an existing .json file on my s ...

Using specific sections of JSON data to display in an alert message (Vanilla JavaScript)

I am seeking a bookmarklet that, upon clicking, will access JSON data and retrieve the "temp" information to display in an alert indicating the weather with just one click. Is there a method to achieve this or do I need to utilize a different API? Here&ap ...

The file upload process did not return a successful response for Ajax

Recently delved into the world of Ajax and encountered a perplexing issue. Here is the dilemma: I successfully upload a .csv file to the server. However, after the upload "success" in the ajax call fails to trigger a response. Neither does complete or er ...

Disabling the shadow when setting the face color in Three.js

When creating geometric objects in my project, I am randomly setting colors on the faces: // Material used to create the mesh var material = new THREE.MeshLambertMaterial({ color: 0xffffff, ambient: 0xffffff, vertexColors: THREE.FaceColors}) function ad ...

Error: Trying to access 'product-1' property on an undefined object

Having trouble displaying JSON data in my React.js project, I've been stuck on an error for the past couple of days with no luck in solving it. The JSON data is stored in a file named products.json: { "product-1": [ { ...

Executing a JavaScript function within a C# file

I am implementing a JavaScript function within a C# file using the Page Load method <script type="text/javascript"> function googleMaps(aLocations, aTitles, aSummary) { $(document).ready(function () { $('#test').Goo ...

JavaScript Event Listener Triggered when the DOM is Fully Loaded

I am experiencing an issue with my JavaScript code that is meant to trigger AJAX requests when specific HTML elements are clicked. However, instead of waiting for the click event, all the URLs listed in the code seem to be firing as soon as the page load ...

Tips for enlarging the tree view when running protractor exams. Check out this code excerpt below:

I have a code snippet below that represents one item out of many, each distinguished by ng-reflect-index. I am trying to write a test case to expand these nodes individually using Protractor. However, I am facing an issue in expanding the node using Prot ...

Waiting for seed data prior to accepting server requests

Highlighted by the titles, the main concern in this scenario is a function within the server.js file that executes after the base root has been loaded. The code snippet below showcases the function call along with the root. seedDB(); app.get("/",function( ...

Having Difficulty Converting JavaScript Objects/JSON into PHP Arrays

This particular inquiry has no relation to the previously mentioned identical answer/question... In JavaScript, I am dealing with a substantial list of over 1,000 items displayed in this format... var plugins = [ { name: "Roundabout - Interac ...

Ways to implement pointer event styling within a span element

Hi, I'm having trouble with styling and I can't seem to figure out how to resolve it. The style pointer-events: none doesn't seem to be working for me. Here is an example of my code: The style snippet: .noclick { cursor: default; ...

Using jQuery in Rails 3 to display the id of a td element

I am working with a 3x3 table that contains td elements with unique id's (id='a1'...id='c3'). I want to enable the user to click on any of these 9 td elements and receive an alert displaying the id of the clicked td. Below is my C ...

Comparing the use of jQuery's data() method versus directly accessing attributes with native JavaScript using get

I want to retrieve general information from my website using javascript. I have a few different options available: I could use an html element: <input type="hidden" value="MyValue"/> Another option is to use a custom attribute in an existing h ...

The formatting of the list is not being correctly displayed in the Ajax Jquery list

Trying to dynamically generate an unordered list from XML onto a jQuery mobile page has been a bit of a challenge for me. While I can display the items on the page, the styling never seems to work properly, only showing up as plain text with blue links. Is ...

What are some ways to render a React component when its ID is only determined after making an AJAX call?

Currently, I am working on developing a chat application where a chat message is immediately displayed (using a React component) once the user sends it by hitting the Enter key: https://i.sstatic.net/MJXLd.png https://i.sstatic.net/S6thO.png As shown in ...

Error caused by live data dynamic update on Highstock chart: Cannot access property 'info' of undefined

Utilizing Laravel, I was able to create Highcharts by consuming data from a Rest API link (Spring app) at . The data is currently displayed statically, but I want to dynamically visualize it on charts. I attempted to follow this example on Fiddle and inte ...

Is there a way to invoke an Angular2 function from within a Google Map infowindow?

I am currently working on integrating Google Maps using javascript in a project, and I'm facing a challenge. I want to call an Angular2 function inside an infowindow as shown in the code snippet below. Pay attention to the infoContent variable that co ...

Internet Explorer is experiencing difficulties in loading content using jQuery

I'm trying to implement a method similar to the one shown in this link on the link provided below. The first link works fine in IE, but for some reason my approach is failing in IE. It's loading the content, but the old content seems to still be ...

Click to move directly to a specific section

This question may be common, but despite my research efforts, I have been unable to find a solution. I want to issue a disclaimer that I am new to javascript and jQuery. Here is an overview of what I am trying to achieve: I want two images that, when cli ...

Why is the code able to execute following the setState hook without any listener declared in the useEffect hook?

Recently, I came across an expo barcode scanner example where a function is executed after a setState hook. This puzzled me as I thought that calling the setState hook would trigger a re-render of the component. Can anyone explain why the function runs aft ...